repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
Autodesk/aomi
aomi/cli.py
secretfile_args
def secretfile_args(parser): """Add Secretfile management command line arguments to parser""" parser.add_argument('--secrets', dest='secrets', help='Path where secrets are stored', default=os.path.join(os.getcwd(), ".secrets")) parser.add_argument('--policies', dest='policies', help='Path where policies are stored', default=os.path.join(os.getcwd(), "vault", "")) parser.add_argument('--secretfile', dest='secretfile', help='Secretfile to use', default=os.path.join(os.getcwd(), "Secretfile")) parser.add_argument('--tags', dest='tags', help='Tags of things to seed', default=[], type=str, action='append') parser.add_argument('--include', dest='include', help='Specify paths to include', default=[], type=str, action='append') parser.add_argument('--exclude', dest='exclude', help='Specify paths to exclude', default=[], type=str, action='append')
python
def secretfile_args(parser): """Add Secretfile management command line arguments to parser""" parser.add_argument('--secrets', dest='secrets', help='Path where secrets are stored', default=os.path.join(os.getcwd(), ".secrets")) parser.add_argument('--policies', dest='policies', help='Path where policies are stored', default=os.path.join(os.getcwd(), "vault", "")) parser.add_argument('--secretfile', dest='secretfile', help='Secretfile to use', default=os.path.join(os.getcwd(), "Secretfile")) parser.add_argument('--tags', dest='tags', help='Tags of things to seed', default=[], type=str, action='append') parser.add_argument('--include', dest='include', help='Specify paths to include', default=[], type=str, action='append') parser.add_argument('--exclude', dest='exclude', help='Specify paths to exclude', default=[], type=str, action='append')
[ "def", "secretfile_args", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'--secrets'", ",", "dest", "=", "'secrets'", ",", "help", "=", "'Path where secrets are stored'", ",", "default", "=", "os", ".", "path", ".", "join", "(", "os", ".", "...
Add Secretfile management command line arguments to parser
[ "Add", "Secretfile", "management", "command", "line", "arguments", "to", "parser" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L143-L174
train
44,400
Autodesk/aomi
aomi/cli.py
base_args
def base_args(parser): """Add the generic command line options""" generic_args(parser) parser.add_argument('--monochrome', dest='monochrome', help='Whether or not to use colors', action='store_true') parser.add_argument('--metadata', dest='metadata', help='A series of key=value pairs for token metadata.', default='') parser.add_argument('--lease', dest='lease', help='Lease time for intermediary token.', default='10s') parser.add_argument('--reuse-token', dest='reuse_token', help='Whether to reuse the existing token. Note' ' this will cause metadata to not be preserved', action='store_true')
python
def base_args(parser): """Add the generic command line options""" generic_args(parser) parser.add_argument('--monochrome', dest='monochrome', help='Whether or not to use colors', action='store_true') parser.add_argument('--metadata', dest='metadata', help='A series of key=value pairs for token metadata.', default='') parser.add_argument('--lease', dest='lease', help='Lease time for intermediary token.', default='10s') parser.add_argument('--reuse-token', dest='reuse_token', help='Whether to reuse the existing token. Note' ' this will cause metadata to not be preserved', action='store_true')
[ "def", "base_args", "(", "parser", ")", ":", "generic_args", "(", "parser", ")", "parser", ".", "add_argument", "(", "'--monochrome'", ",", "dest", "=", "'monochrome'", ",", "help", "=", "'Whether or not to use colors'", ",", "action", "=", "'store_true'", ")", ...
Add the generic command line options
[ "Add", "the", "generic", "command", "line", "options" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L187-L206
train
44,401
Autodesk/aomi
aomi/cli.py
export_args
def export_args(subparsers): """Add command line options for the export operation""" export_parser = subparsers.add_parser('export') export_parser.add_argument('directory', help='Path where secrets will be exported into') secretfile_args(export_parser) vars_args(export_parser) base_args(export_parser)
python
def export_args(subparsers): """Add command line options for the export operation""" export_parser = subparsers.add_parser('export') export_parser.add_argument('directory', help='Path where secrets will be exported into') secretfile_args(export_parser) vars_args(export_parser) base_args(export_parser)
[ "def", "export_args", "(", "subparsers", ")", ":", "export_parser", "=", "subparsers", ".", "add_parser", "(", "'export'", ")", "export_parser", ".", "add_argument", "(", "'directory'", ",", "help", "=", "'Path where secrets will be exported into'", ")", "secretfile_a...
Add command line options for the export operation
[ "Add", "command", "line", "options", "for", "the", "export", "operation" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L209-L216
train
44,402
Autodesk/aomi
aomi/cli.py
render_args
def render_args(subparsers): """Add command line options for the render operation""" render_parser = subparsers.add_parser('render') render_parser.add_argument('directory', help='Path where Secrefile and accoutrement' ' will be rendered into') secretfile_args(render_parser) vars_args(render_parser) base_args(render_parser) thaw_from_args(render_parser)
python
def render_args(subparsers): """Add command line options for the render operation""" render_parser = subparsers.add_parser('render') render_parser.add_argument('directory', help='Path where Secrefile and accoutrement' ' will be rendered into') secretfile_args(render_parser) vars_args(render_parser) base_args(render_parser) thaw_from_args(render_parser)
[ "def", "render_args", "(", "subparsers", ")", ":", "render_parser", "=", "subparsers", ".", "add_parser", "(", "'render'", ")", "render_parser", ".", "add_argument", "(", "'directory'", ",", "help", "=", "'Path where Secrefile and accoutrement'", "' will be rendered int...
Add command line options for the render operation
[ "Add", "command", "line", "options", "for", "the", "render", "operation" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L219-L228
train
44,403
Autodesk/aomi
aomi/cli.py
diff_args
def diff_args(subparsers): """Add command line options for the diff operation""" diff_parser = subparsers.add_parser('diff') secretfile_args(diff_parser) vars_args(diff_parser) base_args(diff_parser) thaw_from_args(diff_parser)
python
def diff_args(subparsers): """Add command line options for the diff operation""" diff_parser = subparsers.add_parser('diff') secretfile_args(diff_parser) vars_args(diff_parser) base_args(diff_parser) thaw_from_args(diff_parser)
[ "def", "diff_args", "(", "subparsers", ")", ":", "diff_parser", "=", "subparsers", ".", "add_parser", "(", "'diff'", ")", "secretfile_args", "(", "diff_parser", ")", "vars_args", "(", "diff_parser", ")", "base_args", "(", "diff_parser", ")", "thaw_from_args", "(...
Add command line options for the diff operation
[ "Add", "command", "line", "options", "for", "the", "diff", "operation" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L231-L237
train
44,404
Autodesk/aomi
aomi/cli.py
seed_args
def seed_args(subparsers): """Add command line options for the seed operation""" seed_parser = subparsers.add_parser('seed') secretfile_args(seed_parser) vars_args(seed_parser) seed_parser.add_argument('--mount-only', dest='mount_only', help='Only mount paths if needed', default=False, action='store_true') thaw_from_args(seed_parser) seed_parser.add_argument('--remove-unknown', dest='remove_unknown', action='store_true', help='Remove mountpoints that are not ' 'defined in the Secretfile') base_args(seed_parser)
python
def seed_args(subparsers): """Add command line options for the seed operation""" seed_parser = subparsers.add_parser('seed') secretfile_args(seed_parser) vars_args(seed_parser) seed_parser.add_argument('--mount-only', dest='mount_only', help='Only mount paths if needed', default=False, action='store_true') thaw_from_args(seed_parser) seed_parser.add_argument('--remove-unknown', dest='remove_unknown', action='store_true', help='Remove mountpoints that are not ' 'defined in the Secretfile') base_args(seed_parser)
[ "def", "seed_args", "(", "subparsers", ")", ":", "seed_parser", "=", "subparsers", ".", "add_parser", "(", "'seed'", ")", "secretfile_args", "(", "seed_parser", ")", "vars_args", "(", "seed_parser", ")", "seed_parser", ".", "add_argument", "(", "'--mount-only'", ...
Add command line options for the seed operation
[ "Add", "command", "line", "options", "for", "the", "seed", "operation" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L240-L256
train
44,405
Autodesk/aomi
aomi/cli.py
thaw_from_args
def thaw_from_args(parser): """Adds command line options for things related to inline thawing of icefiles""" parser.add_argument('--thaw-from', dest='thaw_from', help='Thaw an ICE file containing secrets') parser.add_argument('--gpg-password-path', dest='gpg_pass_path', help='Vault path of GPG passphrase location')
python
def thaw_from_args(parser): """Adds command line options for things related to inline thawing of icefiles""" parser.add_argument('--thaw-from', dest='thaw_from', help='Thaw an ICE file containing secrets') parser.add_argument('--gpg-password-path', dest='gpg_pass_path', help='Vault path of GPG passphrase location')
[ "def", "thaw_from_args", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'--thaw-from'", ",", "dest", "=", "'thaw_from'", ",", "help", "=", "'Thaw an ICE file containing secrets'", ")", "parser", ".", "add_argument", "(", "'--gpg-password-path'", ",", ...
Adds command line options for things related to inline thawing of icefiles
[ "Adds", "command", "line", "options", "for", "things", "related", "to", "inline", "thawing", "of", "icefiles" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L259-L267
train
44,406
Autodesk/aomi
aomi/cli.py
thaw_args
def thaw_args(subparsers): """Add command line options for the thaw operation""" thaw_parser = subparsers.add_parser('thaw') thaw_parser.add_argument('--gpg-password-path', dest='gpg_pass_path', help='Vault path of GPG passphrase location') thaw_parser.add_argument('--ignore-missing', dest='ignore_missing', help='Warn when secrets are missing from icefiles' 'instead of exiting', action='store_true', default=False) secretfile_args(thaw_parser) archive_args(thaw_parser) vars_args(thaw_parser) base_args(thaw_parser)
python
def thaw_args(subparsers): """Add command line options for the thaw operation""" thaw_parser = subparsers.add_parser('thaw') thaw_parser.add_argument('--gpg-password-path', dest='gpg_pass_path', help='Vault path of GPG passphrase location') thaw_parser.add_argument('--ignore-missing', dest='ignore_missing', help='Warn when secrets are missing from icefiles' 'instead of exiting', action='store_true', default=False) secretfile_args(thaw_parser) archive_args(thaw_parser) vars_args(thaw_parser) base_args(thaw_parser)
[ "def", "thaw_args", "(", "subparsers", ")", ":", "thaw_parser", "=", "subparsers", ".", "add_parser", "(", "'thaw'", ")", "thaw_parser", ".", "add_argument", "(", "'--gpg-password-path'", ",", "dest", "=", "'gpg_pass_path'", ",", "help", "=", "'Vault path of GPG p...
Add command line options for the thaw operation
[ "Add", "command", "line", "options", "for", "the", "thaw", "operation" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L277-L292
train
44,407
Autodesk/aomi
aomi/cli.py
freeze_args
def freeze_args(subparsers): """Add command line options for the freeze operation""" freeze_parser = subparsers.add_parser('freeze') freeze_parser.add_argument('--icefile-prefix', dest='icefile_prefix', help='Prefix of icefilename') secretfile_args(freeze_parser) archive_args(freeze_parser) vars_args(freeze_parser) base_args(freeze_parser)
python
def freeze_args(subparsers): """Add command line options for the freeze operation""" freeze_parser = subparsers.add_parser('freeze') freeze_parser.add_argument('--icefile-prefix', dest='icefile_prefix', help='Prefix of icefilename') secretfile_args(freeze_parser) archive_args(freeze_parser) vars_args(freeze_parser) base_args(freeze_parser)
[ "def", "freeze_args", "(", "subparsers", ")", ":", "freeze_parser", "=", "subparsers", ".", "add_parser", "(", "'freeze'", ")", "freeze_parser", ".", "add_argument", "(", "'--icefile-prefix'", ",", "dest", "=", "'icefile_prefix'", ",", "help", "=", "'Prefix of ice...
Add command line options for the freeze operation
[ "Add", "command", "line", "options", "for", "the", "freeze", "operation" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L295-L304
train
44,408
Autodesk/aomi
aomi/cli.py
password_args
def password_args(subparsers): """Add command line options for the set_password operation""" password_parser = subparsers.add_parser('set_password') password_parser.add_argument('vault_path', help='Path which contains password' 'secret to be udpated') base_args(password_parser)
python
def password_args(subparsers): """Add command line options for the set_password operation""" password_parser = subparsers.add_parser('set_password') password_parser.add_argument('vault_path', help='Path which contains password' 'secret to be udpated') base_args(password_parser)
[ "def", "password_args", "(", "subparsers", ")", ":", "password_parser", "=", "subparsers", ".", "add_parser", "(", "'set_password'", ")", "password_parser", ".", "add_argument", "(", "'vault_path'", ",", "help", "=", "'Path which contains password'", "'secret to be udpa...
Add command line options for the set_password operation
[ "Add", "command", "line", "options", "for", "the", "set_password", "operation" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L307-L313
train
44,409
Autodesk/aomi
aomi/cli.py
vars_args
def vars_args(parser): """Add various command line options for external vars""" parser.add_argument('--extra-vars', dest='extra_vars', help='Extra template variables', default=[], type=str, action='append') parser.add_argument('--extra-vars-file', dest='extra_vars_file', help='YAML files full of variables', default=[], type=str, action='append')
python
def vars_args(parser): """Add various command line options for external vars""" parser.add_argument('--extra-vars', dest='extra_vars', help='Extra template variables', default=[], type=str, action='append') parser.add_argument('--extra-vars-file', dest='extra_vars_file', help='YAML files full of variables', default=[], type=str, action='append')
[ "def", "vars_args", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'--extra-vars'", ",", "dest", "=", "'extra_vars'", ",", "help", "=", "'Extra template variables'", ",", "default", "=", "[", "]", ",", "type", "=", "str", ",", "action", "=",...
Add various command line options for external vars
[ "Add", "various", "command", "line", "options", "for", "external", "vars" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L322-L335
train
44,410
Autodesk/aomi
aomi/cli.py
parser_factory
def parser_factory(fake_args=None): """Return a proper contextual OptionParser""" parser = ArgumentParser(description='aomi') subparsers = parser.add_subparsers(dest='operation', help='Specify the data ' ' or extraction operation') extract_file_args(subparsers) environment_args(subparsers) aws_env_args(subparsers) seed_args(subparsers) render_args(subparsers) diff_args(subparsers) freeze_args(subparsers) thaw_args(subparsers) template_args(subparsers) password_args(subparsers) token_args(subparsers) help_args(subparsers) export_args(subparsers) if fake_args is None: return parser, parser.parse_args() return parser, parser.parse_args(fake_args)
python
def parser_factory(fake_args=None): """Return a proper contextual OptionParser""" parser = ArgumentParser(description='aomi') subparsers = parser.add_subparsers(dest='operation', help='Specify the data ' ' or extraction operation') extract_file_args(subparsers) environment_args(subparsers) aws_env_args(subparsers) seed_args(subparsers) render_args(subparsers) diff_args(subparsers) freeze_args(subparsers) thaw_args(subparsers) template_args(subparsers) password_args(subparsers) token_args(subparsers) help_args(subparsers) export_args(subparsers) if fake_args is None: return parser, parser.parse_args() return parser, parser.parse_args(fake_args)
[ "def", "parser_factory", "(", "fake_args", "=", "None", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "'aomi'", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", "dest", "=", "'operation'", ",", "help", "=", "'Specify the data...
Return a proper contextual OptionParser
[ "Return", "a", "proper", "contextual", "OptionParser" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L344-L367
train
44,411
Autodesk/aomi
aomi/cli.py
template_runner
def template_runner(client, parser, args): """Executes template related operations""" if args.builtin_list: aomi.template.builtin_list() elif args.builtin_info: aomi.template.builtin_info(args.builtin_info) elif args.template and args.destination and args.vault_paths: aomi.render.template(client, args.template, args.destination, args.vault_paths, args) else: parser.print_usage() sys.exit(2) sys.exit(0)
python
def template_runner(client, parser, args): """Executes template related operations""" if args.builtin_list: aomi.template.builtin_list() elif args.builtin_info: aomi.template.builtin_info(args.builtin_info) elif args.template and args.destination and args.vault_paths: aomi.render.template(client, args.template, args.destination, args.vault_paths, args) else: parser.print_usage() sys.exit(2) sys.exit(0)
[ "def", "template_runner", "(", "client", ",", "parser", ",", "args", ")", ":", "if", "args", ".", "builtin_list", ":", "aomi", ".", "template", ".", "builtin_list", "(", ")", "elif", "args", ".", "builtin_info", ":", "aomi", ".", "template", ".", "builti...
Executes template related operations
[ "Executes", "template", "related", "operations" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L370-L385
train
44,412
Autodesk/aomi
aomi/cli.py
ux_actions
def ux_actions(parser, args): """Handle some human triggers actions""" # cryptorito uses native logging (as aomi should tbh) normal_fmt = '%(message)s' if hasattr(args, 'verbose') and args.verbose and args.verbose >= 2: logging.basicConfig(level=logging.DEBUG) elif hasattr(args, 'verbose') and args.verbose >= 1: logging.basicConfig(level=logging.INFO, format=normal_fmt) else: logging.basicConfig(level=logging.WARN, format=normal_fmt) if args.operation == 'help': help_me(parser, args)
python
def ux_actions(parser, args): """Handle some human triggers actions""" # cryptorito uses native logging (as aomi should tbh) normal_fmt = '%(message)s' if hasattr(args, 'verbose') and args.verbose and args.verbose >= 2: logging.basicConfig(level=logging.DEBUG) elif hasattr(args, 'verbose') and args.verbose >= 1: logging.basicConfig(level=logging.INFO, format=normal_fmt) else: logging.basicConfig(level=logging.WARN, format=normal_fmt) if args.operation == 'help': help_me(parser, args)
[ "def", "ux_actions", "(", "parser", ",", "args", ")", ":", "# cryptorito uses native logging (as aomi should tbh)", "normal_fmt", "=", "'%(message)s'", "if", "hasattr", "(", "args", ",", "'verbose'", ")", "and", "args", ".", "verbose", "and", "args", ".", "verbose...
Handle some human triggers actions
[ "Handle", "some", "human", "triggers", "actions" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L388-L400
train
44,413
Autodesk/aomi
aomi/cli.py
do_thaw
def do_thaw(client, args): """Execute the thaw operation, pulling in an actual Vault client if neccesary""" vault_client = None if args.gpg_pass_path: vault_client = client.connect(args) aomi.filez.thaw(vault_client, args.icefile, args) sys.exit(0)
python
def do_thaw(client, args): """Execute the thaw operation, pulling in an actual Vault client if neccesary""" vault_client = None if args.gpg_pass_path: vault_client = client.connect(args) aomi.filez.thaw(vault_client, args.icefile, args) sys.exit(0)
[ "def", "do_thaw", "(", "client", ",", "args", ")", ":", "vault_client", "=", "None", "if", "args", ".", "gpg_pass_path", ":", "vault_client", "=", "client", ".", "connect", "(", "args", ")", "aomi", ".", "filez", ".", "thaw", "(", "vault_client", ",", ...
Execute the thaw operation, pulling in an actual Vault client if neccesary
[ "Execute", "the", "thaw", "operation", "pulling", "in", "an", "actual", "Vault", "client", "if", "neccesary" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L403-L411
train
44,414
Autodesk/aomi
aomi/cli.py
action_runner
def action_runner(parser, args): """Run appropriate action, or throw help""" ux_actions(parser, args) client = aomi.vault.Client(args) if args.operation == 'extract_file': aomi.render.raw_file(client.connect(args), args.vault_path, args.destination, args) sys.exit(0) elif args.operation == 'environment': aomi.render.env(client.connect(args), args.vault_paths, args) sys.exit(0) elif args.operation == 'aws_environment': aomi.render.aws(client.connect(args), args.vault_path, args) sys.exit(0) elif args.operation == 'seed': aomi.validation.gitignore(args) aomi.seed_action.seed(client.connect(args), args) sys.exit(0) elif args.operation == 'render': aomi.seed_action.render(args.directory, args) sys.exit(0) elif args.operation == 'export': aomi.seed_action.export(client.connect(args), args) sys.exit(0) elif args.operation == 'diff': aomi.seed_action.diff(client.connect(args), args) sys.exit(0) elif args.operation == 'template': template_runner(client.connect(args), parser, args) elif args.operation == 'token': print(client.connect(args).token) sys.exit(0) elif args.operation == 'set_password': aomi.util.password(client.connect(args), args.vault_path) sys.exit(0) elif args.operation == 'freeze': aomi.filez.freeze(args.icefile, args) sys.exit(0) elif args.operation == 'thaw': do_thaw(client, args) parser.print_usage() sys.exit(2)
python
def action_runner(parser, args): """Run appropriate action, or throw help""" ux_actions(parser, args) client = aomi.vault.Client(args) if args.operation == 'extract_file': aomi.render.raw_file(client.connect(args), args.vault_path, args.destination, args) sys.exit(0) elif args.operation == 'environment': aomi.render.env(client.connect(args), args.vault_paths, args) sys.exit(0) elif args.operation == 'aws_environment': aomi.render.aws(client.connect(args), args.vault_path, args) sys.exit(0) elif args.operation == 'seed': aomi.validation.gitignore(args) aomi.seed_action.seed(client.connect(args), args) sys.exit(0) elif args.operation == 'render': aomi.seed_action.render(args.directory, args) sys.exit(0) elif args.operation == 'export': aomi.seed_action.export(client.connect(args), args) sys.exit(0) elif args.operation == 'diff': aomi.seed_action.diff(client.connect(args), args) sys.exit(0) elif args.operation == 'template': template_runner(client.connect(args), parser, args) elif args.operation == 'token': print(client.connect(args).token) sys.exit(0) elif args.operation == 'set_password': aomi.util.password(client.connect(args), args.vault_path) sys.exit(0) elif args.operation == 'freeze': aomi.filez.freeze(args.icefile, args) sys.exit(0) elif args.operation == 'thaw': do_thaw(client, args) parser.print_usage() sys.exit(2)
[ "def", "action_runner", "(", "parser", ",", "args", ")", ":", "ux_actions", "(", "parser", ",", "args", ")", "client", "=", "aomi", ".", "vault", ".", "Client", "(", "args", ")", "if", "args", ".", "operation", "==", "'extract_file'", ":", "aomi", ".",...
Run appropriate action, or throw help
[ "Run", "appropriate", "action", "or", "throw", "help" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L414-L460
train
44,415
Autodesk/aomi
aomi/cli.py
main
def main(): """Entrypoint, sweet Entrypoint""" parser, args = parser_factory() try: action_runner(parser, args) # this is our uncaught handler so yes we want to actually # catch every error. the format may vary based on the error handler tho except Exception as uncaught: # pylint: disable=broad-except unhandled(uncaught, args) sys.exit(1)
python
def main(): """Entrypoint, sweet Entrypoint""" parser, args = parser_factory() try: action_runner(parser, args) # this is our uncaught handler so yes we want to actually # catch every error. the format may vary based on the error handler tho except Exception as uncaught: # pylint: disable=broad-except unhandled(uncaught, args) sys.exit(1)
[ "def", "main", "(", ")", ":", "parser", ",", "args", "=", "parser_factory", "(", ")", "try", ":", "action_runner", "(", "parser", ",", "args", ")", "# this is our uncaught handler so yes we want to actually", "# catch every error. the format may vary based on the error hand...
Entrypoint, sweet Entrypoint
[ "Entrypoint", "sweet", "Entrypoint" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L463-L473
train
44,416
Autodesk/aomi
aomi/model/aws.py
grok_ttl
def grok_ttl(secret): """Parses the TTL information""" ttl_obj = {} lease_msg = '' if 'lease' in secret: ttl_obj['lease'] = secret['lease'] lease_msg = "lease:%s" % (ttl_obj['lease']) if 'lease_max' in secret: ttl_obj['lease_max'] = secret['lease_max'] elif 'lease' in ttl_obj: ttl_obj['lease_max'] = ttl_obj['lease'] if 'lease_max' in ttl_obj: lease_msg = "%s lease_max:%s" % (lease_msg, ttl_obj['lease_max']) return ttl_obj, lease_msg
python
def grok_ttl(secret): """Parses the TTL information""" ttl_obj = {} lease_msg = '' if 'lease' in secret: ttl_obj['lease'] = secret['lease'] lease_msg = "lease:%s" % (ttl_obj['lease']) if 'lease_max' in secret: ttl_obj['lease_max'] = secret['lease_max'] elif 'lease' in ttl_obj: ttl_obj['lease_max'] = ttl_obj['lease'] if 'lease_max' in ttl_obj: lease_msg = "%s lease_max:%s" % (lease_msg, ttl_obj['lease_max']) return ttl_obj, lease_msg
[ "def", "grok_ttl", "(", "secret", ")", ":", "ttl_obj", "=", "{", "}", "lease_msg", "=", "''", "if", "'lease'", "in", "secret", ":", "ttl_obj", "[", "'lease'", "]", "=", "secret", "[", "'lease'", "]", "lease_msg", "=", "\"lease:%s\"", "%", "(", "ttl_obj...
Parses the TTL information
[ "Parses", "the", "TTL", "information" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/aws.py#L13-L29
train
44,417
Autodesk/aomi
aomi/helpers.py
my_version
def my_version(): """Return the version, checking both packaged and development locations""" if os.path.exists(resource_filename(__name__, 'version')): return resource_string(__name__, 'version') return open(os.path.join(os.path.dirname(__file__), "..", "version")).read()
python
def my_version(): """Return the version, checking both packaged and development locations""" if os.path.exists(resource_filename(__name__, 'version')): return resource_string(__name__, 'version') return open(os.path.join(os.path.dirname(__file__), "..", "version")).read()
[ "def", "my_version", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "resource_filename", "(", "__name__", ",", "'version'", ")", ")", ":", "return", "resource_string", "(", "__name__", ",", "'version'", ")", "return", "open", "(", "os", ".",...
Return the version, checking both packaged and development locations
[ "Return", "the", "version", "checking", "both", "packaged", "and", "development", "locations" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L19-L25
train
44,418
Autodesk/aomi
aomi/helpers.py
abspath
def abspath(raw): """Return what is hopefully a OS independent path.""" path_bits = [] if raw.find('/') != -1: path_bits = raw.split('/') elif raw.find('\\') != -1: path_bits = raw.split('\\') else: path_bits = [raw] return os.path.abspath(os.sep.join(path_bits))
python
def abspath(raw): """Return what is hopefully a OS independent path.""" path_bits = [] if raw.find('/') != -1: path_bits = raw.split('/') elif raw.find('\\') != -1: path_bits = raw.split('\\') else: path_bits = [raw] return os.path.abspath(os.sep.join(path_bits))
[ "def", "abspath", "(", "raw", ")", ":", "path_bits", "=", "[", "]", "if", "raw", ".", "find", "(", "'/'", ")", "!=", "-", "1", ":", "path_bits", "=", "raw", ".", "split", "(", "'/'", ")", "elif", "raw", ".", "find", "(", "'\\\\'", ")", "!=", ...
Return what is hopefully a OS independent path.
[ "Return", "what", "is", "hopefully", "a", "OS", "independent", "path", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L31-L41
train
44,419
Autodesk/aomi
aomi/helpers.py
hard_path
def hard_path(path, prefix_dir): """Returns an absolute path to either the relative or absolute file.""" relative = abspath("%s/%s" % (prefix_dir, path)) a_path = abspath(path) if os.path.exists(relative): LOG.debug("using relative path %s (%s)", relative, path) return relative LOG.debug("using absolute path %s", a_path) return a_path
python
def hard_path(path, prefix_dir): """Returns an absolute path to either the relative or absolute file.""" relative = abspath("%s/%s" % (prefix_dir, path)) a_path = abspath(path) if os.path.exists(relative): LOG.debug("using relative path %s (%s)", relative, path) return relative LOG.debug("using absolute path %s", a_path) return a_path
[ "def", "hard_path", "(", "path", ",", "prefix_dir", ")", ":", "relative", "=", "abspath", "(", "\"%s/%s\"", "%", "(", "prefix_dir", ",", "path", ")", ")", "a_path", "=", "abspath", "(", "path", ")", "if", "os", ".", "path", ".", "exists", "(", "relat...
Returns an absolute path to either the relative or absolute file.
[ "Returns", "an", "absolute", "path", "to", "either", "the", "relative", "or", "absolute", "file", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L44-L53
train
44,420
Autodesk/aomi
aomi/helpers.py
is_tagged
def is_tagged(required_tags, has_tags): """Checks if tags match""" if not required_tags and not has_tags: return True elif not required_tags: return False found_tags = [] for tag in required_tags: if tag in has_tags: found_tags.append(tag) return len(found_tags) == len(required_tags)
python
def is_tagged(required_tags, has_tags): """Checks if tags match""" if not required_tags and not has_tags: return True elif not required_tags: return False found_tags = [] for tag in required_tags: if tag in has_tags: found_tags.append(tag) return len(found_tags) == len(required_tags)
[ "def", "is_tagged", "(", "required_tags", ",", "has_tags", ")", ":", "if", "not", "required_tags", "and", "not", "has_tags", ":", "return", "True", "elif", "not", "required_tags", ":", "return", "False", "found_tags", "=", "[", "]", "for", "tag", "in", "re...
Checks if tags match
[ "Checks", "if", "tags", "match" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L56-L68
train
44,421
Autodesk/aomi
aomi/helpers.py
cli_hash
def cli_hash(list_of_kv): """Parse out a hash from a list of key=value strings""" ev_obj = {} for extra_var in list_of_kv: ev_list = extra_var.split('=') key = ev_list[0] val = '='.join(ev_list[1:]) # b64 and other side effects ev_obj[key] = val return ev_obj
python
def cli_hash(list_of_kv): """Parse out a hash from a list of key=value strings""" ev_obj = {} for extra_var in list_of_kv: ev_list = extra_var.split('=') key = ev_list[0] val = '='.join(ev_list[1:]) # b64 and other side effects ev_obj[key] = val return ev_obj
[ "def", "cli_hash", "(", "list_of_kv", ")", ":", "ev_obj", "=", "{", "}", "for", "extra_var", "in", "list_of_kv", ":", "ev_list", "=", "extra_var", ".", "split", "(", "'='", ")", "key", "=", "ev_list", "[", "0", "]", "val", "=", "'='", ".", "join", ...
Parse out a hash from a list of key=value strings
[ "Parse", "out", "a", "hash", "from", "a", "list", "of", "key", "=", "value", "strings" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L71-L80
train
44,422
Autodesk/aomi
aomi/helpers.py
merge_dicts
def merge_dicts(dict_a, dict_b): """Deep merge of two dicts""" obj = {} for key, value in iteritems(dict_a): if key in dict_b: if isinstance(dict_b[key], dict): obj[key] = merge_dicts(value, dict_b.pop(key)) else: obj[key] = value for key, value in iteritems(dict_b): obj[key] = value return obj
python
def merge_dicts(dict_a, dict_b): """Deep merge of two dicts""" obj = {} for key, value in iteritems(dict_a): if key in dict_b: if isinstance(dict_b[key], dict): obj[key] = merge_dicts(value, dict_b.pop(key)) else: obj[key] = value for key, value in iteritems(dict_b): obj[key] = value return obj
[ "def", "merge_dicts", "(", "dict_a", ",", "dict_b", ")", ":", "obj", "=", "{", "}", "for", "key", ",", "value", "in", "iteritems", "(", "dict_a", ")", ":", "if", "key", "in", "dict_b", ":", "if", "isinstance", "(", "dict_b", "[", "key", "]", ",", ...
Deep merge of two dicts
[ "Deep", "merge", "of", "two", "dicts" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L83-L96
train
44,423
Autodesk/aomi
aomi/helpers.py
get_tty_password
def get_tty_password(confirm): """When returning a password from a TTY we assume a user is entering it on a keyboard so we ask for confirmation.""" LOG.debug("Reading password from TTY") new_password = getpass('Enter Password: ', stream=sys.stderr) if not new_password: raise aomi.exceptions.AomiCommand("Must specify a password") if not confirm: return new_password confirm_password = getpass('Again, Please: ', stream=sys.stderr) if confirm_password != new_password: raise aomi.exceptions.AomiCommand("Passwords do not match") return new_password
python
def get_tty_password(confirm): """When returning a password from a TTY we assume a user is entering it on a keyboard so we ask for confirmation.""" LOG.debug("Reading password from TTY") new_password = getpass('Enter Password: ', stream=sys.stderr) if not new_password: raise aomi.exceptions.AomiCommand("Must specify a password") if not confirm: return new_password confirm_password = getpass('Again, Please: ', stream=sys.stderr) if confirm_password != new_password: raise aomi.exceptions.AomiCommand("Passwords do not match") return new_password
[ "def", "get_tty_password", "(", "confirm", ")", ":", "LOG", ".", "debug", "(", "\"Reading password from TTY\"", ")", "new_password", "=", "getpass", "(", "'Enter Password: '", ",", "stream", "=", "sys", ".", "stderr", ")", "if", "not", "new_password", ":", "ra...
When returning a password from a TTY we assume a user is entering it on a keyboard so we ask for confirmation.
[ "When", "returning", "a", "password", "from", "a", "TTY", "we", "assume", "a", "user", "is", "entering", "it", "on", "a", "keyboard", "so", "we", "ask", "for", "confirmation", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L99-L114
train
44,424
Autodesk/aomi
aomi/helpers.py
path_pieces
def path_pieces(vault_path): """Will return a two part tuple comprising of the vault path and the key with in the stored object""" path_bits = vault_path.split('/') path = '/'.join(path_bits[0:len(path_bits) - 1]) key = path_bits[len(path_bits) - 1] return path, key
python
def path_pieces(vault_path): """Will return a two part tuple comprising of the vault path and the key with in the stored object""" path_bits = vault_path.split('/') path = '/'.join(path_bits[0:len(path_bits) - 1]) key = path_bits[len(path_bits) - 1] return path, key
[ "def", "path_pieces", "(", "vault_path", ")", ":", "path_bits", "=", "vault_path", ".", "split", "(", "'/'", ")", "path", "=", "'/'", ".", "join", "(", "path_bits", "[", "0", ":", "len", "(", "path_bits", ")", "-", "1", "]", ")", "key", "=", "path_...
Will return a two part tuple comprising of the vault path and the key with in the stored object
[ "Will", "return", "a", "two", "part", "tuple", "comprising", "of", "the", "vault", "path", "and", "the", "key", "with", "in", "the", "stored", "object" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L131-L137
train
44,425
Autodesk/aomi
aomi/helpers.py
mount_for_path
def mount_for_path(path, client): """Returns the mountpoint for this path""" backend_data = client.list_secret_backends()['data'] backends = [mnt for mnt in backend_data.keys()] path_bits = path.split('/') if len(path_bits) == 1: vault_path = "%s/" % path if vault_path in backends: return vault_path[0:len(vault_path) - 1] else: for i in range(1, len(path_bits) + 1): vault_path = "%s/" % '/'.join(path_bits[0:i]) if vault_path in backends: return vault_path[0:len(vault_path) - 1] return None
python
def mount_for_path(path, client): """Returns the mountpoint for this path""" backend_data = client.list_secret_backends()['data'] backends = [mnt for mnt in backend_data.keys()] path_bits = path.split('/') if len(path_bits) == 1: vault_path = "%s/" % path if vault_path in backends: return vault_path[0:len(vault_path) - 1] else: for i in range(1, len(path_bits) + 1): vault_path = "%s/" % '/'.join(path_bits[0:i]) if vault_path in backends: return vault_path[0:len(vault_path) - 1] return None
[ "def", "mount_for_path", "(", "path", ",", "client", ")", ":", "backend_data", "=", "client", ".", "list_secret_backends", "(", ")", "[", "'data'", "]", "backends", "=", "[", "mnt", "for", "mnt", "in", "backend_data", ".", "keys", "(", ")", "]", "path_bi...
Returns the mountpoint for this path
[ "Returns", "the", "mountpoint", "for", "this", "path" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L140-L155
train
44,426
Autodesk/aomi
aomi/helpers.py
backend_type
def backend_type(path, client): """Returns the type of backend at the given mountpoint""" backends = client.list_secret_backends()['data'] vault_path = "%s/" % path return backends[vault_path]['type']
python
def backend_type(path, client): """Returns the type of backend at the given mountpoint""" backends = client.list_secret_backends()['data'] vault_path = "%s/" % path return backends[vault_path]['type']
[ "def", "backend_type", "(", "path", ",", "client", ")", ":", "backends", "=", "client", ".", "list_secret_backends", "(", ")", "[", "'data'", "]", "vault_path", "=", "\"%s/\"", "%", "path", "return", "backends", "[", "vault_path", "]", "[", "'type'", "]" ]
Returns the type of backend at the given mountpoint
[ "Returns", "the", "type", "of", "backend", "at", "the", "given", "mountpoint" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L158-L162
train
44,427
Autodesk/aomi
aomi/helpers.py
load_word_file
def load_word_file(filename): """Loads a words file as a list of lines""" words_file = resource_filename(__name__, "words/%s" % filename) handle = open(words_file, 'r') words = handle.readlines() handle.close() return words
python
def load_word_file(filename): """Loads a words file as a list of lines""" words_file = resource_filename(__name__, "words/%s" % filename) handle = open(words_file, 'r') words = handle.readlines() handle.close() return words
[ "def", "load_word_file", "(", "filename", ")", ":", "words_file", "=", "resource_filename", "(", "__name__", ",", "\"words/%s\"", "%", "filename", ")", "handle", "=", "open", "(", "words_file", ",", "'r'", ")", "words", "=", "handle", ".", "readlines", "(", ...
Loads a words file as a list of lines
[ "Loads", "a", "words", "file", "as", "a", "list", "of", "lines" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L165-L171
train
44,428
Autodesk/aomi
aomi/helpers.py
choose_one
def choose_one(things): """Returns a random entry from a list of things""" choice = SystemRandom().randint(0, len(things) - 1) return things[choice].strip()
python
def choose_one(things): """Returns a random entry from a list of things""" choice = SystemRandom().randint(0, len(things) - 1) return things[choice].strip()
[ "def", "choose_one", "(", "things", ")", ":", "choice", "=", "SystemRandom", "(", ")", ".", "randint", "(", "0", ",", "len", "(", "things", ")", "-", "1", ")", "return", "things", "[", "choice", "]", ".", "strip", "(", ")" ]
Returns a random entry from a list of things
[ "Returns", "a", "random", "entry", "from", "a", "list", "of", "things" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L174-L177
train
44,429
Autodesk/aomi
aomi/helpers.py
subdir_path
def subdir_path(directory, relative): """Returns a file path relative to another path.""" item_bits = directory.split(os.sep) relative_bits = relative.split(os.sep) for i, _item in enumerate(item_bits): if i == len(relative_bits) - 1: return os.sep.join(item_bits[i:]) else: if item_bits[i] != relative_bits[i]: return None return None
python
def subdir_path(directory, relative): """Returns a file path relative to another path.""" item_bits = directory.split(os.sep) relative_bits = relative.split(os.sep) for i, _item in enumerate(item_bits): if i == len(relative_bits) - 1: return os.sep.join(item_bits[i:]) else: if item_bits[i] != relative_bits[i]: return None return None
[ "def", "subdir_path", "(", "directory", ",", "relative", ")", ":", "item_bits", "=", "directory", ".", "split", "(", "os", ".", "sep", ")", "relative_bits", "=", "relative", ".", "split", "(", "os", ".", "sep", ")", "for", "i", ",", "_item", "in", "e...
Returns a file path relative to another path.
[ "Returns", "a", "file", "path", "relative", "to", "another", "path", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L187-L198
train
44,430
Autodesk/aomi
aomi/helpers.py
open_maybe_binary
def open_maybe_binary(filename): """Opens something that might be binary but also might be "plain text".""" if sys.version_info >= (3, 0): data = open(filename, 'rb').read() try: return data.decode('utf-8') except UnicodeDecodeError: return data return open(filename, 'r').read()
python
def open_maybe_binary(filename): """Opens something that might be binary but also might be "plain text".""" if sys.version_info >= (3, 0): data = open(filename, 'rb').read() try: return data.decode('utf-8') except UnicodeDecodeError: return data return open(filename, 'r').read()
[ "def", "open_maybe_binary", "(", "filename", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "data", "=", "open", "(", "filename", ",", "'rb'", ")", ".", "read", "(", ")", "try", ":", "return", "data", ".", "decode",...
Opens something that might be binary but also might be "plain text".
[ "Opens", "something", "that", "might", "be", "binary", "but", "also", "might", "be", "plain", "text", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L201-L211
train
44,431
Autodesk/aomi
aomi/helpers.py
ensure_dir
def ensure_dir(path): """Ensures a directory exists""" if not (os.path.exists(path) and os.path.isdir(path)): os.mkdir(path)
python
def ensure_dir(path): """Ensures a directory exists""" if not (os.path.exists(path) and os.path.isdir(path)): os.mkdir(path)
[ "def", "ensure_dir", "(", "path", ")", ":", "if", "not", "(", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "os", ".", "path", ".", "isdir", "(", "path", ")", ")", ":", "os", ".", "mkdir", "(", "path", ")" ]
Ensures a directory exists
[ "Ensures", "a", "directory", "exists" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L214-L218
train
44,432
Autodesk/aomi
aomi/helpers.py
clean_tmpdir
def clean_tmpdir(path): """Invoked atexit, this removes our tmpdir""" if os.path.exists(path) and \ os.path.isdir(path): rmtree(path)
python
def clean_tmpdir(path): """Invoked atexit, this removes our tmpdir""" if os.path.exists(path) and \ os.path.isdir(path): rmtree(path)
[ "def", "clean_tmpdir", "(", "path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", "and", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "rmtree", "(", "path", ")" ]
Invoked atexit, this removes our tmpdir
[ "Invoked", "atexit", "this", "removes", "our", "tmpdir" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L221-L225
train
44,433
Autodesk/aomi
aomi/helpers.py
dict_unicodeize
def dict_unicodeize(some_dict): """Ensure that every string in a dict is properly represented by unicode strings""" # some python 2/3 compat if isinstance(some_dict, ("".__class__, u"".__class__)): if sys.version_info >= (3, 0): return some_dict return some_dict.decode('utf-8') elif isinstance(some_dict, collections.Mapping): return dict(map(dict_unicodeize, iteritems(some_dict))) elif isinstance(some_dict, collections.Iterable): return type(some_dict)(map(dict_unicodeize, some_dict)) return some_dict
python
def dict_unicodeize(some_dict): """Ensure that every string in a dict is properly represented by unicode strings""" # some python 2/3 compat if isinstance(some_dict, ("".__class__, u"".__class__)): if sys.version_info >= (3, 0): return some_dict return some_dict.decode('utf-8') elif isinstance(some_dict, collections.Mapping): return dict(map(dict_unicodeize, iteritems(some_dict))) elif isinstance(some_dict, collections.Iterable): return type(some_dict)(map(dict_unicodeize, some_dict)) return some_dict
[ "def", "dict_unicodeize", "(", "some_dict", ")", ":", "# some python 2/3 compat", "if", "isinstance", "(", "some_dict", ",", "(", "\"\"", ".", "__class__", ",", "u\"\"", ".", "__class__", ")", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ","...
Ensure that every string in a dict is properly represented by unicode strings
[ "Ensure", "that", "every", "string", "in", "a", "dict", "is", "properly", "represented", "by", "unicode", "strings" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L235-L250
train
44,434
Autodesk/aomi
aomi/helpers.py
diff_dict
def diff_dict(dict1, dict2, ignore_missing=False): """Performs a base type comparison between two dicts""" unidict1 = dict_unicodeize(dict1) unidict2 = dict_unicodeize(dict2) if ((not ignore_missing) and (len(unidict1) != len(unidict2))) or \ (ignore_missing and (len(unidict1) >= len(unidict2))): return True for comp_k, comp_v in iteritems(unidict1): if comp_k not in unidict2: return True else: if comp_v != unidict2[comp_k]: return True return False
python
def diff_dict(dict1, dict2, ignore_missing=False): """Performs a base type comparison between two dicts""" unidict1 = dict_unicodeize(dict1) unidict2 = dict_unicodeize(dict2) if ((not ignore_missing) and (len(unidict1) != len(unidict2))) or \ (ignore_missing and (len(unidict1) >= len(unidict2))): return True for comp_k, comp_v in iteritems(unidict1): if comp_k not in unidict2: return True else: if comp_v != unidict2[comp_k]: return True return False
[ "def", "diff_dict", "(", "dict1", ",", "dict2", ",", "ignore_missing", "=", "False", ")", ":", "unidict1", "=", "dict_unicodeize", "(", "dict1", ")", "unidict2", "=", "dict_unicodeize", "(", "dict2", ")", "if", "(", "(", "not", "ignore_missing", ")", "and"...
Performs a base type comparison between two dicts
[ "Performs", "a", "base", "type", "comparison", "between", "two", "dicts" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L253-L268
train
44,435
Autodesk/aomi
aomi/helpers.py
map_val
def map_val(dest, src, key, default=None, src_key=None): """Will ensure a dict has values sourced from either another dict or based on the provided default""" if not src_key: src_key = key if src_key in src: dest[key] = src[src_key] else: if default is not None: dest[key] = default
python
def map_val(dest, src, key, default=None, src_key=None): """Will ensure a dict has values sourced from either another dict or based on the provided default""" if not src_key: src_key = key if src_key in src: dest[key] = src[src_key] else: if default is not None: dest[key] = default
[ "def", "map_val", "(", "dest", ",", "src", ",", "key", ",", "default", "=", "None", ",", "src_key", "=", "None", ")", ":", "if", "not", "src_key", ":", "src_key", "=", "key", "if", "src_key", "in", "src", ":", "dest", "[", "key", "]", "=", "src",...
Will ensure a dict has values sourced from either another dict or based on the provided default
[ "Will", "ensure", "a", "dict", "has", "values", "sourced", "from", "either", "another", "dict", "or", "based", "on", "the", "provided", "default" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L278-L288
train
44,436
Autodesk/aomi
aomi/model/context.py
filtered_context
def filtered_context(context): """Filters a context This will return a new context with only the resources that are actually available for use. Uses tags and command line options to make determination.""" ctx = Context(context.opt) for resource in context.resources(): if resource.child: continue if resource.filtered(): ctx.add(resource) return ctx
python
def filtered_context(context): """Filters a context This will return a new context with only the resources that are actually available for use. Uses tags and command line options to make determination.""" ctx = Context(context.opt) for resource in context.resources(): if resource.child: continue if resource.filtered(): ctx.add(resource) return ctx
[ "def", "filtered_context", "(", "context", ")", ":", "ctx", "=", "Context", "(", "context", ".", "opt", ")", "for", "resource", "in", "context", ".", "resources", "(", ")", ":", "if", "resource", ".", "child", ":", "continue", "if", "resource", ".", "f...
Filters a context This will return a new context with only the resources that are actually available for use. Uses tags and command line options to make determination.
[ "Filters", "a", "context", "This", "will", "return", "a", "new", "context", "with", "only", "the", "resources", "that", "are", "actually", "available", "for", "use", ".", "Uses", "tags", "and", "command", "line", "options", "to", "make", "determination", "."...
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L19-L33
train
44,437
Autodesk/aomi
aomi/model/context.py
ensure_backend
def ensure_backend(resource, backend, backends, opt, managed=True): """Ensure the backend for a resource is properly in context""" existing_mount = find_backend(resource.mount, backends) if not existing_mount: new_mount = backend(resource, opt, managed=managed) backends.append(new_mount) return new_mount return existing_mount
python
def ensure_backend(resource, backend, backends, opt, managed=True): """Ensure the backend for a resource is properly in context""" existing_mount = find_backend(resource.mount, backends) if not existing_mount: new_mount = backend(resource, opt, managed=managed) backends.append(new_mount) return new_mount return existing_mount
[ "def", "ensure_backend", "(", "resource", ",", "backend", ",", "backends", ",", "opt", ",", "managed", "=", "True", ")", ":", "existing_mount", "=", "find_backend", "(", "resource", ".", "mount", ",", "backends", ")", "if", "not", "existing_mount", ":", "n...
Ensure the backend for a resource is properly in context
[ "Ensure", "the", "backend", "for", "a", "resource", "is", "properly", "in", "context" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L59-L67
train
44,438
Autodesk/aomi
aomi/model/context.py
py_resources
def py_resources(): """Discovers all aomi Vault resource models. This includes anything extending aomi.model.Mount or aomi.model.Resource.""" aomi_mods = [m for m, _v in iteritems(sys.modules) if m.startswith('aomi.model')] mod_list = [] mod_map = [] for amod in [sys.modules[m] for m in aomi_mods]: for _mod_bit, model in inspect.getmembers(amod): if str(model) in mod_list: continue if model == Mount: mod_list.append(str(model)) mod_map.append((model.config_key, model)) elif (inspect.isclass(model) and issubclass(model, Resource) and model.config_key): mod_list.append(str(model)) if model.resource_key: mod_map.append((model.config_key, model.resource_key, model)) elif model.config_key != 'secrets': mod_map.append((model.config_key, model)) return mod_map
python
def py_resources(): """Discovers all aomi Vault resource models. This includes anything extending aomi.model.Mount or aomi.model.Resource.""" aomi_mods = [m for m, _v in iteritems(sys.modules) if m.startswith('aomi.model')] mod_list = [] mod_map = [] for amod in [sys.modules[m] for m in aomi_mods]: for _mod_bit, model in inspect.getmembers(amod): if str(model) in mod_list: continue if model == Mount: mod_list.append(str(model)) mod_map.append((model.config_key, model)) elif (inspect.isclass(model) and issubclass(model, Resource) and model.config_key): mod_list.append(str(model)) if model.resource_key: mod_map.append((model.config_key, model.resource_key, model)) elif model.config_key != 'secrets': mod_map.append((model.config_key, model)) return mod_map
[ "def", "py_resources", "(", ")", ":", "aomi_mods", "=", "[", "m", "for", "m", ",", "_v", "in", "iteritems", "(", "sys", ".", "modules", ")", "if", "m", ".", "startswith", "(", "'aomi.model'", ")", "]", "mod_list", "=", "[", "]", "mod_map", "=", "["...
Discovers all aomi Vault resource models. This includes anything extending aomi.model.Mount or aomi.model.Resource.
[ "Discovers", "all", "aomi", "Vault", "resource", "models", ".", "This", "includes", "anything", "extending", "aomi", ".", "model", ".", "Mount", "or", "aomi", ".", "model", ".", "Resource", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L86-L113
train
44,439
Autodesk/aomi
aomi/model/context.py
Context.load
def load(config, opt): """Loads and returns a full context object based on the Secretfile""" ctx = Context(opt) seed_map = py_resources() seed_keys = sorted(set([m[0] for m in seed_map]), key=resource_sort) for config_key in seed_keys: if config_key not in config: continue for resource_config in config[config_key]: mod = find_model(config_key, resource_config, seed_map) if not mod: LOG.warning("unable to find mod for %s", resource_config) continue ctx.add(mod(resource_config, opt)) for config_key in config.keys(): if config_key != 'pgp_keys' and \ config_key not in seed_keys: LOG.warning("missing model for %s", config_key) return filtered_context(ctx)
python
def load(config, opt): """Loads and returns a full context object based on the Secretfile""" ctx = Context(opt) seed_map = py_resources() seed_keys = sorted(set([m[0] for m in seed_map]), key=resource_sort) for config_key in seed_keys: if config_key not in config: continue for resource_config in config[config_key]: mod = find_model(config_key, resource_config, seed_map) if not mod: LOG.warning("unable to find mod for %s", resource_config) continue ctx.add(mod(resource_config, opt)) for config_key in config.keys(): if config_key != 'pgp_keys' and \ config_key not in seed_keys: LOG.warning("missing model for %s", config_key) return filtered_context(ctx)
[ "def", "load", "(", "config", ",", "opt", ")", ":", "ctx", "=", "Context", "(", "opt", ")", "seed_map", "=", "py_resources", "(", ")", "seed_keys", "=", "sorted", "(", "set", "(", "[", "m", "[", "0", "]", "for", "m", "in", "seed_map", "]", ")", ...
Loads and returns a full context object based on the Secretfile
[ "Loads", "and", "returns", "a", "full", "context", "object", "based", "on", "the", "Secretfile" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L132-L153
train
44,440
Autodesk/aomi
aomi/model/context.py
Context.thaw
def thaw(self, tmp_dir): """Will thaw every secret into an appropriate temporary location""" for resource in self.resources(): if resource.present: resource.thaw(tmp_dir)
python
def thaw(self, tmp_dir): """Will thaw every secret into an appropriate temporary location""" for resource in self.resources(): if resource.present: resource.thaw(tmp_dir)
[ "def", "thaw", "(", "self", ",", "tmp_dir", ")", ":", "for", "resource", "in", "self", ".", "resources", "(", ")", ":", "if", "resource", ".", "present", ":", "resource", ".", "thaw", "(", "tmp_dir", ")" ]
Will thaw every secret into an appropriate temporary location
[ "Will", "thaw", "every", "secret", "into", "an", "appropriate", "temporary", "location" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L155-L159
train
44,441
Autodesk/aomi
aomi/model/context.py
Context.freeze
def freeze(self, dest_dir): """Freezes every resource within a context""" for resource in self.resources(): if resource.present: resource.freeze(dest_dir)
python
def freeze(self, dest_dir): """Freezes every resource within a context""" for resource in self.resources(): if resource.present: resource.freeze(dest_dir)
[ "def", "freeze", "(", "self", ",", "dest_dir", ")", ":", "for", "resource", "in", "self", ".", "resources", "(", ")", ":", "if", "resource", ".", "present", ":", "resource", ".", "freeze", "(", "dest_dir", ")" ]
Freezes every resource within a context
[ "Freezes", "every", "resource", "within", "a", "context" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L161-L165
train
44,442
Autodesk/aomi
aomi/model/context.py
Context.resources
def resources(self): """Vault resources within context""" res = [] for resource in self._resources: res = res + resource.resources() return res
python
def resources(self): """Vault resources within context""" res = [] for resource in self._resources: res = res + resource.resources() return res
[ "def", "resources", "(", "self", ")", ":", "res", "=", "[", "]", "for", "resource", "in", "self", ".", "_resources", ":", "res", "=", "res", "+", "resource", ".", "resources", "(", ")", "return", "res" ]
Vault resources within context
[ "Vault", "resources", "within", "context" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L186-L192
train
44,443
Autodesk/aomi
aomi/model/context.py
Context.add
def add(self, resource): """Add a resource to the context""" if isinstance(resource, Resource): if isinstance(resource, Secret) and \ resource.mount != 'cubbyhole': ensure_backend(resource, SecretBackend, self._mounts, self.opt, False) elif isinstance(resource, Mount): ensure_backend(resource, SecretBackend, self._mounts, self.opt) elif isinstance(resource, Auth): ensure_backend(resource, AuthBackend, self._auths, self.opt) elif isinstance(resource, AuditLog): ensure_backend(resource, LogBackend, self._logs, self.opt) self._resources.append(resource) else: msg = "Unknown resource %s being " \ "added to context" % resource.__class__ raise aomi_excep.AomiError(msg)
python
def add(self, resource): """Add a resource to the context""" if isinstance(resource, Resource): if isinstance(resource, Secret) and \ resource.mount != 'cubbyhole': ensure_backend(resource, SecretBackend, self._mounts, self.opt, False) elif isinstance(resource, Mount): ensure_backend(resource, SecretBackend, self._mounts, self.opt) elif isinstance(resource, Auth): ensure_backend(resource, AuthBackend, self._auths, self.opt) elif isinstance(resource, AuditLog): ensure_backend(resource, LogBackend, self._logs, self.opt) self._resources.append(resource) else: msg = "Unknown resource %s being " \ "added to context" % resource.__class__ raise aomi_excep.AomiError(msg)
[ "def", "add", "(", "self", ",", "resource", ")", ":", "if", "isinstance", "(", "resource", ",", "Resource", ")", ":", "if", "isinstance", "(", "resource", ",", "Secret", ")", "and", "resource", ".", "mount", "!=", "'cubbyhole'", ":", "ensure_backend", "(...
Add a resource to the context
[ "Add", "a", "resource", "to", "the", "context" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L194-L215
train
44,444
Autodesk/aomi
aomi/model/context.py
Context.remove
def remove(self, resource): """Removes a resource from the context""" if isinstance(resource, Resource): self._resources.remove(resource)
python
def remove(self, resource): """Removes a resource from the context""" if isinstance(resource, Resource): self._resources.remove(resource)
[ "def", "remove", "(", "self", ",", "resource", ")", ":", "if", "isinstance", "(", "resource", ",", "Resource", ")", ":", "self", ".", "_resources", ".", "remove", "(", "resource", ")" ]
Removes a resource from the context
[ "Removes", "a", "resource", "from", "the", "context" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L217-L220
train
44,445
Autodesk/aomi
aomi/model/context.py
Context.sync_policies
def sync_policies(self, vault_client): """Synchronizes policies only""" p_resources = [x for x in self.resources() if isinstance(x, Policy)] for resource in p_resources: resource.sync(vault_client) return [x for x in self.resources() if not isinstance(x, Policy)]
python
def sync_policies(self, vault_client): """Synchronizes policies only""" p_resources = [x for x in self.resources() if isinstance(x, Policy)] for resource in p_resources: resource.sync(vault_client) return [x for x in self.resources() if not isinstance(x, Policy)]
[ "def", "sync_policies", "(", "self", ",", "vault_client", ")", ":", "p_resources", "=", "[", "x", "for", "x", "in", "self", ".", "resources", "(", ")", "if", "isinstance", "(", "x", ",", "Policy", ")", "]", "for", "resource", "in", "p_resources", ":", ...
Synchronizes policies only
[ "Synchronizes", "policies", "only" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L222-L230
train
44,446
Autodesk/aomi
aomi/model/context.py
Context.sync_auth
def sync_auth(self, vault_client, resources): """Synchronizes auth mount wrappers. These happen early in the cycle, to ensure that user backends are proper. They may also be used to set mount tuning""" for auth in self.auths(): auth.sync(vault_client) auth_resources = [x for x in resources if isinstance(x, (LDAP, UserPass))] for resource in auth_resources: resource.sync(vault_client) return [x for x in resources if not isinstance(x, (LDAP, UserPass, AuditLog))]
python
def sync_auth(self, vault_client, resources): """Synchronizes auth mount wrappers. These happen early in the cycle, to ensure that user backends are proper. They may also be used to set mount tuning""" for auth in self.auths(): auth.sync(vault_client) auth_resources = [x for x in resources if isinstance(x, (LDAP, UserPass))] for resource in auth_resources: resource.sync(vault_client) return [x for x in resources if not isinstance(x, (LDAP, UserPass, AuditLog))]
[ "def", "sync_auth", "(", "self", ",", "vault_client", ",", "resources", ")", ":", "for", "auth", "in", "self", ".", "auths", "(", ")", ":", "auth", ".", "sync", "(", "vault_client", ")", "auth_resources", "=", "[", "x", "for", "x", "in", "resources", ...
Synchronizes auth mount wrappers. These happen early in the cycle, to ensure that user backends are proper. They may also be used to set mount tuning
[ "Synchronizes", "auth", "mount", "wrappers", ".", "These", "happen", "early", "in", "the", "cycle", "to", "ensure", "that", "user", "backends", "are", "proper", ".", "They", "may", "also", "be", "used", "to", "set", "mount", "tuning" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L232-L246
train
44,447
Autodesk/aomi
aomi/model/context.py
Context.sync_mounts
def sync_mounts(self, active_mounts, resources, vault_client): """Synchronizes mount points. Removes things before adding new.""" # Create a resource set that is only explicit mounts # and sort so removals are first mounts = [x for x in resources if isinstance(x, (Mount, AWS))] s_resources = sorted(mounts, key=absent_sort) # Iterate over explicit mounts only for resource in s_resources: active_mounts = self.actually_mount(vault_client, resource, active_mounts) # OK Now iterate over everything but make sure it is clear # that ad-hoc mountpoints are deprecated as per # https://github.com/Autodesk/aomi/issues/110 for resource in [x for x in resources if isinstance(x, Secret)]: n_mounts = self.actually_mount(vault_client, resource, active_mounts) if len(n_mounts) != len(active_mounts): LOG.warning("Ad-Hoc mount with %s. Please specify" " explicit mountpoints.", resource) active_mounts = n_mounts return active_mounts, [x for x in resources if not isinstance(x, (Mount))]
python
def sync_mounts(self, active_mounts, resources, vault_client): """Synchronizes mount points. Removes things before adding new.""" # Create a resource set that is only explicit mounts # and sort so removals are first mounts = [x for x in resources if isinstance(x, (Mount, AWS))] s_resources = sorted(mounts, key=absent_sort) # Iterate over explicit mounts only for resource in s_resources: active_mounts = self.actually_mount(vault_client, resource, active_mounts) # OK Now iterate over everything but make sure it is clear # that ad-hoc mountpoints are deprecated as per # https://github.com/Autodesk/aomi/issues/110 for resource in [x for x in resources if isinstance(x, Secret)]: n_mounts = self.actually_mount(vault_client, resource, active_mounts) if len(n_mounts) != len(active_mounts): LOG.warning("Ad-Hoc mount with %s. Please specify" " explicit mountpoints.", resource) active_mounts = n_mounts return active_mounts, [x for x in resources if not isinstance(x, (Mount))]
[ "def", "sync_mounts", "(", "self", ",", "active_mounts", ",", "resources", ",", "vault_client", ")", ":", "# Create a resource set that is only explicit mounts", "# and sort so removals are first", "mounts", "=", "[", "x", "for", "x", "in", "resources", "if", "isinstanc...
Synchronizes mount points. Removes things before adding new.
[ "Synchronizes", "mount", "points", ".", "Removes", "things", "before", "adding", "new", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L265-L295
train
44,448
Autodesk/aomi
aomi/model/context.py
Context.sync
def sync(self, vault_client, opt): """Synchronizes the context to the Vault server. This has the effect of updating every resource which is in the context and has changes pending.""" active_mounts = [] for audit_log in self.logs(): audit_log.sync(vault_client) # Handle policies only on the first pass. This allows us # to ensure that ACL's are in place prior to actually # making any changes. not_policies = self.sync_policies(vault_client) # Handle auth wrapper resources on the next path. The resources # may update a path on their own. They may also provide mount # tuning information. not_auth = self.sync_auth(vault_client, not_policies) # Handle mounts only on the next pass. This allows us to # ensure that everything is in order prior to actually # provisioning secrets. Note we handle removals before # anything else, allowing us to address mount conflicts. active_mounts, not_mounts = self.sync_mounts(active_mounts, not_auth, vault_client) # Now handle everything else. If "best practices" are being # adhered to then every generic mountpoint should exist by now. # We handle "child" resources after the first batch sorted_resources = sorted(not_mounts, key=childless_first) for resource in sorted_resources: resource.sync(vault_client) for mount in self.mounts(): if not find_backend(mount.path, active_mounts): mount.unmount(vault_client) if opt.remove_unknown: self.prune(vault_client)
python
def sync(self, vault_client, opt): """Synchronizes the context to the Vault server. This has the effect of updating every resource which is in the context and has changes pending.""" active_mounts = [] for audit_log in self.logs(): audit_log.sync(vault_client) # Handle policies only on the first pass. This allows us # to ensure that ACL's are in place prior to actually # making any changes. not_policies = self.sync_policies(vault_client) # Handle auth wrapper resources on the next path. The resources # may update a path on their own. They may also provide mount # tuning information. not_auth = self.sync_auth(vault_client, not_policies) # Handle mounts only on the next pass. This allows us to # ensure that everything is in order prior to actually # provisioning secrets. Note we handle removals before # anything else, allowing us to address mount conflicts. active_mounts, not_mounts = self.sync_mounts(active_mounts, not_auth, vault_client) # Now handle everything else. If "best practices" are being # adhered to then every generic mountpoint should exist by now. # We handle "child" resources after the first batch sorted_resources = sorted(not_mounts, key=childless_first) for resource in sorted_resources: resource.sync(vault_client) for mount in self.mounts(): if not find_backend(mount.path, active_mounts): mount.unmount(vault_client) if opt.remove_unknown: self.prune(vault_client)
[ "def", "sync", "(", "self", ",", "vault_client", ",", "opt", ")", ":", "active_mounts", "=", "[", "]", "for", "audit_log", "in", "self", ".", "logs", "(", ")", ":", "audit_log", ".", "sync", "(", "vault_client", ")", "# Handle policies only on the first pass...
Synchronizes the context to the Vault server. This has the effect of updating every resource which is in the context and has changes pending.
[ "Synchronizes", "the", "context", "to", "the", "Vault", "server", ".", "This", "has", "the", "effect", "of", "updating", "every", "resource", "which", "is", "in", "the", "context", "and", "has", "changes", "pending", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L297-L332
train
44,449
Autodesk/aomi
aomi/model/context.py
Context.prune
def prune(self, vault_client): """Will remove any mount point which is not actually defined in this context. """ existing = getattr(vault_client, SecretBackend.list_fun)()['data'].items() for mount_name, _values in existing: # ignore system paths and cubbyhole mount_path = normalize_vault_path(mount_name) if mount_path.startswith('sys') or mount_path == 'cubbyhole': continue exists = [resource.path for resource in self.mounts() if normalize_vault_path(resource.path) == mount_path] if not exists: LOG.info("removed unknown mount %s", mount_path) getattr(vault_client, SecretBackend.unmount_fun)(mount_path)
python
def prune(self, vault_client): """Will remove any mount point which is not actually defined in this context. """ existing = getattr(vault_client, SecretBackend.list_fun)()['data'].items() for mount_name, _values in existing: # ignore system paths and cubbyhole mount_path = normalize_vault_path(mount_name) if mount_path.startswith('sys') or mount_path == 'cubbyhole': continue exists = [resource.path for resource in self.mounts() if normalize_vault_path(resource.path) == mount_path] if not exists: LOG.info("removed unknown mount %s", mount_path) getattr(vault_client, SecretBackend.unmount_fun)(mount_path)
[ "def", "prune", "(", "self", ",", "vault_client", ")", ":", "existing", "=", "getattr", "(", "vault_client", ",", "SecretBackend", ".", "list_fun", ")", "(", ")", "[", "'data'", "]", ".", "items", "(", ")", "for", "mount_name", ",", "_values", "in", "e...
Will remove any mount point which is not actually defined in this context.
[ "Will", "remove", "any", "mount", "point", "which", "is", "not", "actually", "defined", "in", "this", "context", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L334-L351
train
44,450
Autodesk/aomi
aomi/model/context.py
Context.fetch
def fetch(self, vault_client): """Updates the context based on the contents of the Vault server. Note that some resources can not be read after they have been written to and it is up to those classes to handle that case properly.""" backends = [(self.mounts, SecretBackend), (self.auths, AuthBackend), (self.logs, LogBackend)] for b_list, b_class in backends: backend_list = b_list() if backend_list: existing = getattr(vault_client, b_class.list_fun)() for backend in backend_list: backend.fetch(vault_client, existing) for rsc in self.resources(): if issubclass(type(rsc), Secret): nc_exists = (rsc.mount != 'cubbyhole' and find_backend(rsc.mount, self._mounts).existing) if nc_exists or rsc.mount == 'cubbyhole': rsc.fetch(vault_client) elif issubclass(type(rsc), Auth): if find_backend(rsc.mount, self._auths).existing: rsc.fetch(vault_client) elif issubclass(type(rsc), Mount): rsc.existing = find_backend(rsc.mount, self._mounts).existing else: rsc.fetch(vault_client) return self
python
def fetch(self, vault_client): """Updates the context based on the contents of the Vault server. Note that some resources can not be read after they have been written to and it is up to those classes to handle that case properly.""" backends = [(self.mounts, SecretBackend), (self.auths, AuthBackend), (self.logs, LogBackend)] for b_list, b_class in backends: backend_list = b_list() if backend_list: existing = getattr(vault_client, b_class.list_fun)() for backend in backend_list: backend.fetch(vault_client, existing) for rsc in self.resources(): if issubclass(type(rsc), Secret): nc_exists = (rsc.mount != 'cubbyhole' and find_backend(rsc.mount, self._mounts).existing) if nc_exists or rsc.mount == 'cubbyhole': rsc.fetch(vault_client) elif issubclass(type(rsc), Auth): if find_backend(rsc.mount, self._auths).existing: rsc.fetch(vault_client) elif issubclass(type(rsc), Mount): rsc.existing = find_backend(rsc.mount, self._mounts).existing else: rsc.fetch(vault_client) return self
[ "def", "fetch", "(", "self", ",", "vault_client", ")", ":", "backends", "=", "[", "(", "self", ".", "mounts", ",", "SecretBackend", ")", ",", "(", "self", ".", "auths", ",", "AuthBackend", ")", ",", "(", "self", ".", "logs", ",", "LogBackend", ")", ...
Updates the context based on the contents of the Vault server. Note that some resources can not be read after they have been written to and it is up to those classes to handle that case properly.
[ "Updates", "the", "context", "based", "on", "the", "contents", "of", "the", "Vault", "server", ".", "Note", "that", "some", "resources", "can", "not", "be", "read", "after", "they", "have", "been", "written", "to", "and", "it", "is", "up", "to", "those",...
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L353-L383
train
44,451
Autodesk/aomi
aomi/render.py
secret_key_name
def secret_key_name(path, key, opt): """Renders a Secret key name appropriately""" value = key if opt.merge_path: norm_path = [x for x in path.split('/') if x] value = "%s_%s" % ('_'.join(norm_path), key) if opt.add_prefix: value = "%s%s" % (opt.add_prefix, value) if opt.add_suffix: value = "%s%s" % (value, opt.add_suffix) return value
python
def secret_key_name(path, key, opt): """Renders a Secret key name appropriately""" value = key if opt.merge_path: norm_path = [x for x in path.split('/') if x] value = "%s_%s" % ('_'.join(norm_path), key) if opt.add_prefix: value = "%s%s" % (opt.add_prefix, value) if opt.add_suffix: value = "%s%s" % (value, opt.add_suffix) return value
[ "def", "secret_key_name", "(", "path", ",", "key", ",", "opt", ")", ":", "value", "=", "key", "if", "opt", ".", "merge_path", ":", "norm_path", "=", "[", "x", "for", "x", "in", "path", ".", "split", "(", "'/'", ")", "if", "x", "]", "value", "=", ...
Renders a Secret key name appropriately
[ "Renders", "a", "Secret", "key", "name", "appropriately" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/render.py#L18-L31
train
44,452
Autodesk/aomi
aomi/render.py
grok_template_file
def grok_template_file(src): """Determine the real deal template file""" if not src.startswith('builtin:'): return abspath(src) builtin = src.split(':')[1] builtin = "templates/%s.j2" % builtin return resource_filename(__name__, builtin)
python
def grok_template_file(src): """Determine the real deal template file""" if not src.startswith('builtin:'): return abspath(src) builtin = src.split(':')[1] builtin = "templates/%s.j2" % builtin return resource_filename(__name__, builtin)
[ "def", "grok_template_file", "(", "src", ")", ":", "if", "not", "src", ".", "startswith", "(", "'builtin:'", ")", ":", "return", "abspath", "(", "src", ")", "builtin", "=", "src", ".", "split", "(", "':'", ")", "[", "1", "]", "builtin", "=", "\"templ...
Determine the real deal template file
[ "Determine", "the", "real", "deal", "template", "file" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/render.py#L34-L41
train
44,453
Autodesk/aomi
aomi/render.py
blend_vars
def blend_vars(secrets, opt): """Blends secret and static variables together""" base_obj = load_vars(opt) merged = merge_dicts(base_obj, secrets) template_obj = dict((k, v) for k, v in iteritems(merged) if v) # give templates something to iterate over template_obj['aomi_items'] = template_obj.copy() return template_obj
python
def blend_vars(secrets, opt): """Blends secret and static variables together""" base_obj = load_vars(opt) merged = merge_dicts(base_obj, secrets) template_obj = dict((k, v) for k, v in iteritems(merged) if v) # give templates something to iterate over template_obj['aomi_items'] = template_obj.copy() return template_obj
[ "def", "blend_vars", "(", "secrets", ",", "opt", ")", ":", "base_obj", "=", "load_vars", "(", "opt", ")", "merged", "=", "merge_dicts", "(", "base_obj", ",", "secrets", ")", "template_obj", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", ...
Blends secret and static variables together
[ "Blends", "secret", "and", "static", "variables", "together" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/render.py#L44-L51
train
44,454
Autodesk/aomi
aomi/render.py
template
def template(client, src, dest, paths, opt): """Writes a template using variables from a vault path""" key_map = cli_hash(opt.key_map) obj = {} for path in paths: response = client.read(path) if not response: raise aomi.exceptions.VaultData("Unable to retrieve %s" % path) if is_aws(response['data']) and 'sts' not in path: renew_secret(client, response, opt) for s_k, s_v in response['data'].items(): o_key = s_k if s_k in key_map: o_key = key_map[s_k] k_name = secret_key_name(path, o_key, opt) \ .lower() \ .replace('-', '_') obj[k_name] = s_v template_obj = blend_vars(obj, opt) output = render(grok_template_file(src), template_obj) write_raw_file(output, abspath(dest))
python
def template(client, src, dest, paths, opt): """Writes a template using variables from a vault path""" key_map = cli_hash(opt.key_map) obj = {} for path in paths: response = client.read(path) if not response: raise aomi.exceptions.VaultData("Unable to retrieve %s" % path) if is_aws(response['data']) and 'sts' not in path: renew_secret(client, response, opt) for s_k, s_v in response['data'].items(): o_key = s_k if s_k in key_map: o_key = key_map[s_k] k_name = secret_key_name(path, o_key, opt) \ .lower() \ .replace('-', '_') obj[k_name] = s_v template_obj = blend_vars(obj, opt) output = render(grok_template_file(src), template_obj) write_raw_file(output, abspath(dest))
[ "def", "template", "(", "client", ",", "src", ",", "dest", ",", "paths", ",", "opt", ")", ":", "key_map", "=", "cli_hash", "(", "opt", ".", "key_map", ")", "obj", "=", "{", "}", "for", "path", "in", "paths", ":", "response", "=", "client", ".", "...
Writes a template using variables from a vault path
[ "Writes", "a", "template", "using", "variables", "from", "a", "vault", "path" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/render.py#L54-L78
train
44,455
Autodesk/aomi
aomi/render.py
write_raw_file
def write_raw_file(secret, dest): """Writes an actual secret out to a file""" secret_file = None secret_filename = abspath(dest) if sys.version_info >= (3, 0): if not isinstance(secret, str): secret_file = open(secret_filename, 'wb') if not secret_file: secret_file = open(secret_filename, 'w') secret_file.write(secret) secret_file.close() os.chmod(secret_filename, 0o600)
python
def write_raw_file(secret, dest): """Writes an actual secret out to a file""" secret_file = None secret_filename = abspath(dest) if sys.version_info >= (3, 0): if not isinstance(secret, str): secret_file = open(secret_filename, 'wb') if not secret_file: secret_file = open(secret_filename, 'w') secret_file.write(secret) secret_file.close() os.chmod(secret_filename, 0o600)
[ "def", "write_raw_file", "(", "secret", ",", "dest", ")", ":", "secret_file", "=", "None", "secret_filename", "=", "abspath", "(", "dest", ")", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "if", "not", "isinstance", "(", "secre...
Writes an actual secret out to a file
[ "Writes", "an", "actual", "secret", "out", "to", "a", "file" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/render.py#L81-L94
train
44,456
Autodesk/aomi
aomi/render.py
env
def env(client, paths, opt): """Renders a shell snippet based on paths in a Secretfile""" old_prefix = False old_prefix = opt.prefix and not (opt.add_prefix or opt.add_suffix or not opt.merge_path) if old_prefix: LOG.warning("the prefix option is deprecated " "please use" "--no-merge-path --add-prefix $OLDPREFIX_ instead") elif opt.prefix: LOG.warning("the prefix option is deprecated" "please use" "--no-merge-path --add-prefix $OLDPREFIX_ instead") key_map = cli_hash(opt.key_map) for path in paths: secrets = client.read(path) if secrets and 'data' in secrets: if is_aws(secrets['data']) and 'sts' not in path: renew_secret(client, secrets, opt) for s_key, s_val in secrets['data'].items(): o_key = s_key if s_key in key_map: o_key = key_map[s_key] # see https://github.com/Autodesk/aomi/issues/40 env_name = None if old_prefix: env_name = ("%s_%s" % (opt.prefix, o_key)).upper() else: env_name = secret_key_name(path, o_key, opt).upper() print("%s=\"%s\"" % (env_name, s_val)) if opt.export: print("export %s" % env_name)
python
def env(client, paths, opt): """Renders a shell snippet based on paths in a Secretfile""" old_prefix = False old_prefix = opt.prefix and not (opt.add_prefix or opt.add_suffix or not opt.merge_path) if old_prefix: LOG.warning("the prefix option is deprecated " "please use" "--no-merge-path --add-prefix $OLDPREFIX_ instead") elif opt.prefix: LOG.warning("the prefix option is deprecated" "please use" "--no-merge-path --add-prefix $OLDPREFIX_ instead") key_map = cli_hash(opt.key_map) for path in paths: secrets = client.read(path) if secrets and 'data' in secrets: if is_aws(secrets['data']) and 'sts' not in path: renew_secret(client, secrets, opt) for s_key, s_val in secrets['data'].items(): o_key = s_key if s_key in key_map: o_key = key_map[s_key] # see https://github.com/Autodesk/aomi/issues/40 env_name = None if old_prefix: env_name = ("%s_%s" % (opt.prefix, o_key)).upper() else: env_name = secret_key_name(path, o_key, opt).upper() print("%s=\"%s\"" % (env_name, s_val)) if opt.export: print("export %s" % env_name)
[ "def", "env", "(", "client", ",", "paths", ",", "opt", ")", ":", "old_prefix", "=", "False", "old_prefix", "=", "opt", ".", "prefix", "and", "not", "(", "opt", ".", "add_prefix", "or", "opt", ".", "add_suffix", "or", "not", "opt", ".", "merge_path", ...
Renders a shell snippet based on paths in a Secretfile
[ "Renders", "a", "shell", "snippet", "based", "on", "paths", "in", "a", "Secretfile" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/render.py#L123-L158
train
44,457
Autodesk/aomi
aomi/render.py
aws
def aws(client, path, opt): """Renders a shell environment snippet with AWS information""" try: creds = client.read(path) except (hvac.exceptions.InternalServerError) as vault_exception: # this is how old vault behaves if vault_exception.errors[0].find('unsupported path') > 0: emsg = "Invalid AWS path. Did you forget the" \ " credential type and role?" raise aomi.exceptions.AomiFile(emsg) else: raise # this is how new vault behaves if not creds: emsg = "Invalid AWS path. Did you forget the" \ " credential type and role?" raise aomi.exceptions.AomiFile(emsg) renew_secret(client, creds, opt) if creds and 'data' in creds: print("AWS_ACCESS_KEY_ID=\"%s\"" % creds['data']['access_key']) print("AWS_SECRET_ACCESS_KEY=\"%s\"" % creds['data']['secret_key']) if 'security_token' in creds['data'] \ and creds['data']['security_token']: token = creds['data']['security_token'] print("AWS_SECURITY_TOKEN=\"%s\"" % token) else: client.revoke_self_token() e_msg = "Unable to generate AWS credentials from %s" % path raise aomi.exceptions.VaultData(e_msg) if opt.export: print("export AWS_ACCESS_KEY_ID") print("export AWS_SECRET_ACCESS_KEY") if 'security_token' in creds['data'] \ and creds['data']['security_token']: print("export AWS_SECURITY_TOKEN")
python
def aws(client, path, opt): """Renders a shell environment snippet with AWS information""" try: creds = client.read(path) except (hvac.exceptions.InternalServerError) as vault_exception: # this is how old vault behaves if vault_exception.errors[0].find('unsupported path') > 0: emsg = "Invalid AWS path. Did you forget the" \ " credential type and role?" raise aomi.exceptions.AomiFile(emsg) else: raise # this is how new vault behaves if not creds: emsg = "Invalid AWS path. Did you forget the" \ " credential type and role?" raise aomi.exceptions.AomiFile(emsg) renew_secret(client, creds, opt) if creds and 'data' in creds: print("AWS_ACCESS_KEY_ID=\"%s\"" % creds['data']['access_key']) print("AWS_SECRET_ACCESS_KEY=\"%s\"" % creds['data']['secret_key']) if 'security_token' in creds['data'] \ and creds['data']['security_token']: token = creds['data']['security_token'] print("AWS_SECURITY_TOKEN=\"%s\"" % token) else: client.revoke_self_token() e_msg = "Unable to generate AWS credentials from %s" % path raise aomi.exceptions.VaultData(e_msg) if opt.export: print("export AWS_ACCESS_KEY_ID") print("export AWS_SECRET_ACCESS_KEY") if 'security_token' in creds['data'] \ and creds['data']['security_token']: print("export AWS_SECURITY_TOKEN")
[ "def", "aws", "(", "client", ",", "path", ",", "opt", ")", ":", "try", ":", "creds", "=", "client", ".", "read", "(", "path", ")", "except", "(", "hvac", ".", "exceptions", ".", "InternalServerError", ")", "as", "vault_exception", ":", "# this is how old...
Renders a shell environment snippet with AWS information
[ "Renders", "a", "shell", "environment", "snippet", "with", "AWS", "information" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/render.py#L161-L200
train
44,458
Autodesk/aomi
aomi/model/generic.py
generated_key
def generated_key(key): """Create the proper generated key value""" key_name = key['name'] if key['method'] == 'uuid': LOG.debug("Setting %s to a uuid", key_name) return str(uuid4()) elif key['method'] == 'words': LOG.debug("Setting %s to random words", key_name) return random_word() elif key['method'] == 'static': if 'value' not in key.keys(): raise aomi.exceptions.AomiData("Missing static value") LOG.debug("Setting %s to a static value", key_name) return key['value'] else: raise aomi.exceptions.AomiData("Unexpected generated secret method %s" % key['method'])
python
def generated_key(key): """Create the proper generated key value""" key_name = key['name'] if key['method'] == 'uuid': LOG.debug("Setting %s to a uuid", key_name) return str(uuid4()) elif key['method'] == 'words': LOG.debug("Setting %s to random words", key_name) return random_word() elif key['method'] == 'static': if 'value' not in key.keys(): raise aomi.exceptions.AomiData("Missing static value") LOG.debug("Setting %s to a static value", key_name) return key['value'] else: raise aomi.exceptions.AomiData("Unexpected generated secret method %s" % key['method'])
[ "def", "generated_key", "(", "key", ")", ":", "key_name", "=", "key", "[", "'name'", "]", "if", "key", "[", "'method'", "]", "==", "'uuid'", ":", "LOG", ".", "debug", "(", "\"Setting %s to a uuid\"", ",", "key_name", ")", "return", "str", "(", "uuid4", ...
Create the proper generated key value
[ "Create", "the", "proper", "generated", "key", "value" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/generic.py#L101-L118
train
44,459
Autodesk/aomi
aomi/model/generic.py
Generated.generate_obj
def generate_obj(self): """Generates the secret object, respecting existing information and user specified options""" secret_obj = {} if self.existing: secret_obj = deepcopy(self.existing) for key in self.keys: key_name = key['name'] if self.existing and \ key_name in self.existing and \ not key.get('overwrite'): LOG.debug("Not overwriting %s/%s", self.path, key_name) continue else: secret_obj[key_name] = generated_key(key) return secret_obj
python
def generate_obj(self): """Generates the secret object, respecting existing information and user specified options""" secret_obj = {} if self.existing: secret_obj = deepcopy(self.existing) for key in self.keys: key_name = key['name'] if self.existing and \ key_name in self.existing and \ not key.get('overwrite'): LOG.debug("Not overwriting %s/%s", self.path, key_name) continue else: secret_obj[key_name] = generated_key(key) return secret_obj
[ "def", "generate_obj", "(", "self", ")", ":", "secret_obj", "=", "{", "}", "if", "self", ".", "existing", ":", "secret_obj", "=", "deepcopy", "(", "self", ".", "existing", ")", "for", "key", "in", "self", ".", "keys", ":", "key_name", "=", "key", "["...
Generates the secret object, respecting existing information and user specified options
[ "Generates", "the", "secret", "object", "respecting", "existing", "information", "and", "user", "specified", "options" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/generic.py#L133-L150
train
44,460
Autodesk/aomi
aomi/error.py
output
def output(message, opt, extra=None): """ Politely display an unexpected error""" print(message, file=sys.stderr) if opt.verbose: if extra: print(extra) traceback.print_exc(sys.stderr)
python
def output(message, opt, extra=None): """ Politely display an unexpected error""" print(message, file=sys.stderr) if opt.verbose: if extra: print(extra) traceback.print_exc(sys.stderr)
[ "def", "output", "(", "message", ",", "opt", ",", "extra", "=", "None", ")", ":", "print", "(", "message", ",", "file", "=", "sys", ".", "stderr", ")", "if", "opt", ".", "verbose", ":", "if", "extra", ":", "print", "(", "extra", ")", "traceback", ...
Politely display an unexpected error
[ "Politely", "display", "an", "unexpected", "error" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/error.py#L25-L32
train
44,461
Autodesk/aomi
aomi/vault.py
grok_seconds
def grok_seconds(lease): """Ensures that we are returning just seconds""" if lease.endswith('s'): return int(lease[0:-1]) elif lease.endswith('m'): return int(lease[0:-1]) * 60 elif lease.endswith('h'): return int(lease[0:-1]) * 3600 return None
python
def grok_seconds(lease): """Ensures that we are returning just seconds""" if lease.endswith('s'): return int(lease[0:-1]) elif lease.endswith('m'): return int(lease[0:-1]) * 60 elif lease.endswith('h'): return int(lease[0:-1]) * 3600 return None
[ "def", "grok_seconds", "(", "lease", ")", ":", "if", "lease", ".", "endswith", "(", "'s'", ")", ":", "return", "int", "(", "lease", "[", "0", ":", "-", "1", "]", ")", "elif", "lease", ".", "endswith", "(", "'m'", ")", ":", "return", "int", "(", ...
Ensures that we are returning just seconds
[ "Ensures", "that", "we", "are", "returning", "just", "seconds" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L25-L34
train
44,462
Autodesk/aomi
aomi/vault.py
renew_secret
def renew_secret(client, creds, opt): """Renews a secret. This will occur unless the user has specified on the command line that it is not neccesary""" if opt.reuse_token: return seconds = grok_seconds(opt.lease) if not seconds: raise aomi.exceptions.AomiCommand("invalid lease %s" % opt.lease) renew = None if client.version: v_bits = client.version.split('.') if int(v_bits[0]) == 0 and \ int(v_bits[1]) <= 8 and \ int(v_bits[2]) <= 0: r_obj = { 'increment': seconds } r_path = "v1/sys/renew/{0}".format(creds['lease_id']) # Pending discussion on https://github.com/ianunruh/hvac/issues/148 # pylint: disable=protected-access renew = client._post(r_path, json=r_obj).json() if not renew: renew = client.renew_secret(creds['lease_id'], seconds) # sometimes it takes a bit for vault to respond # if we are within 5s then we are fine if not renew or (seconds - renew['lease_duration'] >= 5): client.revoke_self_token() e_msg = 'Unable to renew with desired lease' raise aomi.exceptions.VaultConstraint(e_msg)
python
def renew_secret(client, creds, opt): """Renews a secret. This will occur unless the user has specified on the command line that it is not neccesary""" if opt.reuse_token: return seconds = grok_seconds(opt.lease) if not seconds: raise aomi.exceptions.AomiCommand("invalid lease %s" % opt.lease) renew = None if client.version: v_bits = client.version.split('.') if int(v_bits[0]) == 0 and \ int(v_bits[1]) <= 8 and \ int(v_bits[2]) <= 0: r_obj = { 'increment': seconds } r_path = "v1/sys/renew/{0}".format(creds['lease_id']) # Pending discussion on https://github.com/ianunruh/hvac/issues/148 # pylint: disable=protected-access renew = client._post(r_path, json=r_obj).json() if not renew: renew = client.renew_secret(creds['lease_id'], seconds) # sometimes it takes a bit for vault to respond # if we are within 5s then we are fine if not renew or (seconds - renew['lease_duration'] >= 5): client.revoke_self_token() e_msg = 'Unable to renew with desired lease' raise aomi.exceptions.VaultConstraint(e_msg)
[ "def", "renew_secret", "(", "client", ",", "creds", ",", "opt", ")", ":", "if", "opt", ".", "reuse_token", ":", "return", "seconds", "=", "grok_seconds", "(", "opt", ".", "lease", ")", "if", "not", "seconds", ":", "raise", "aomi", ".", "exceptions", "....
Renews a secret. This will occur unless the user has specified on the command line that it is not neccesary
[ "Renews", "a", "secret", ".", "This", "will", "occur", "unless", "the", "user", "has", "specified", "on", "the", "command", "line", "that", "it", "is", "not", "neccesary" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L37-L69
train
44,463
Autodesk/aomi
aomi/vault.py
approle_token
def approle_token(vault_client, role_id, secret_id): """Returns a vault token based on the role and seret id""" resp = vault_client.auth_approle(role_id, secret_id) if 'auth' in resp and 'client_token' in resp['auth']: return resp['auth']['client_token'] else: raise aomi.exceptions.AomiCredentials('invalid approle')
python
def approle_token(vault_client, role_id, secret_id): """Returns a vault token based on the role and seret id""" resp = vault_client.auth_approle(role_id, secret_id) if 'auth' in resp and 'client_token' in resp['auth']: return resp['auth']['client_token'] else: raise aomi.exceptions.AomiCredentials('invalid approle')
[ "def", "approle_token", "(", "vault_client", ",", "role_id", ",", "secret_id", ")", ":", "resp", "=", "vault_client", ".", "auth_approle", "(", "role_id", ",", "secret_id", ")", "if", "'auth'", "in", "resp", "and", "'client_token'", "in", "resp", "[", "'auth...
Returns a vault token based on the role and seret id
[ "Returns", "a", "vault", "token", "based", "on", "the", "role", "and", "seret", "id" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L72-L78
train
44,464
Autodesk/aomi
aomi/vault.py
app_token
def app_token(vault_client, app_id, user_id): """Returns a vault token based on the app and user id.""" resp = vault_client.auth_app_id(app_id, user_id) if 'auth' in resp and 'client_token' in resp['auth']: return resp['auth']['client_token'] else: raise aomi.exceptions.AomiCredentials('invalid apptoken')
python
def app_token(vault_client, app_id, user_id): """Returns a vault token based on the app and user id.""" resp = vault_client.auth_app_id(app_id, user_id) if 'auth' in resp and 'client_token' in resp['auth']: return resp['auth']['client_token'] else: raise aomi.exceptions.AomiCredentials('invalid apptoken')
[ "def", "app_token", "(", "vault_client", ",", "app_id", ",", "user_id", ")", ":", "resp", "=", "vault_client", ".", "auth_app_id", "(", "app_id", ",", "user_id", ")", "if", "'auth'", "in", "resp", "and", "'client_token'", "in", "resp", "[", "'auth'", "]", ...
Returns a vault token based on the app and user id.
[ "Returns", "a", "vault", "token", "based", "on", "the", "app", "and", "user", "id", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L81-L87
train
44,465
Autodesk/aomi
aomi/vault.py
token_meta
def token_meta(opt): """Generates metadata for a token""" meta = { 'via': 'aomi', 'operation': opt.operation, 'hostname': socket.gethostname() } if 'USER' in os.environ: meta['unix_user'] = os.environ['USER'] if opt.metadata: meta_bits = opt.metadata.split(',') for meta_bit in meta_bits: key, value = meta_bit.split('=') if key not in meta: meta[key] = value for key, value in meta.items(): LOG.debug("Token metadata %s %s", key, value) return meta
python
def token_meta(opt): """Generates metadata for a token""" meta = { 'via': 'aomi', 'operation': opt.operation, 'hostname': socket.gethostname() } if 'USER' in os.environ: meta['unix_user'] = os.environ['USER'] if opt.metadata: meta_bits = opt.metadata.split(',') for meta_bit in meta_bits: key, value = meta_bit.split('=') if key not in meta: meta[key] = value for key, value in meta.items(): LOG.debug("Token metadata %s %s", key, value) return meta
[ "def", "token_meta", "(", "opt", ")", ":", "meta", "=", "{", "'via'", ":", "'aomi'", ",", "'operation'", ":", "opt", ".", "operation", ",", "'hostname'", ":", "socket", ".", "gethostname", "(", ")", "}", "if", "'USER'", "in", "os", ".", "environ", ":...
Generates metadata for a token
[ "Generates", "metadata", "for", "a", "token" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L90-L111
train
44,466
Autodesk/aomi
aomi/vault.py
get_backend
def get_backend(backend, path, backends): """Returns mountpoint details for a backend""" m_norm = normalize_vault_path(path) for mount_name, values in backends.items(): b_norm = normalize_vault_path(mount_name) if (m_norm == b_norm) and values['type'] == backend: return values return None
python
def get_backend(backend, path, backends): """Returns mountpoint details for a backend""" m_norm = normalize_vault_path(path) for mount_name, values in backends.items(): b_norm = normalize_vault_path(mount_name) if (m_norm == b_norm) and values['type'] == backend: return values return None
[ "def", "get_backend", "(", "backend", ",", "path", ",", "backends", ")", ":", "m_norm", "=", "normalize_vault_path", "(", "path", ")", "for", "mount_name", ",", "values", "in", "backends", ".", "items", "(", ")", ":", "b_norm", "=", "normalize_vault_path", ...
Returns mountpoint details for a backend
[ "Returns", "mountpoint", "details", "for", "a", "backend" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L114-L122
train
44,467
Autodesk/aomi
aomi/vault.py
wrap_hvac
def wrap_hvac(msg): """Error catching Vault API wrapper This decorator wraps API interactions with Vault. It will catch and return appropriate error output on common problems. Do we even need this now that we extend the hvac class?""" # pylint: disable=missing-docstring def wrap_call(func): # pylint: disable=missing-docstring def func_wrapper(self, vault_client): try: return func(self, vault_client) except (hvac.exceptions.InvalidRequest, hvac.exceptions.Forbidden) as vault_exception: if vault_exception.errors[0] == 'permission denied': emsg = "Permission denied %s from %s" % (msg, self.path) raise aomi.exceptions.AomiCredentials(emsg) else: raise return func_wrapper return wrap_call
python
def wrap_hvac(msg): """Error catching Vault API wrapper This decorator wraps API interactions with Vault. It will catch and return appropriate error output on common problems. Do we even need this now that we extend the hvac class?""" # pylint: disable=missing-docstring def wrap_call(func): # pylint: disable=missing-docstring def func_wrapper(self, vault_client): try: return func(self, vault_client) except (hvac.exceptions.InvalidRequest, hvac.exceptions.Forbidden) as vault_exception: if vault_exception.errors[0] == 'permission denied': emsg = "Permission denied %s from %s" % (msg, self.path) raise aomi.exceptions.AomiCredentials(emsg) else: raise return func_wrapper return wrap_call
[ "def", "wrap_hvac", "(", "msg", ")", ":", "# pylint: disable=missing-docstring", "def", "wrap_call", "(", "func", ")", ":", "# pylint: disable=missing-docstring", "def", "func_wrapper", "(", "self", ",", "vault_client", ")", ":", "try", ":", "return", "func", "(",...
Error catching Vault API wrapper This decorator wraps API interactions with Vault. It will catch and return appropriate error output on common problems. Do we even need this now that we extend the hvac class?
[ "Error", "catching", "Vault", "API", "wrapper", "This", "decorator", "wraps", "API", "interactions", "with", "Vault", ".", "It", "will", "catch", "and", "return", "appropriate", "error", "output", "on", "common", "problems", ".", "Do", "we", "even", "need", ...
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L130-L151
train
44,468
Autodesk/aomi
aomi/vault.py
Client.server_version
def server_version(self): """Attempts to determine the version of Vault that a server is running. Some actions will change on older Vault deployments.""" health_url = "%s/v1/sys/health" % self.vault_addr resp = self.session.request('get', health_url, **self._kwargs) if resp.status_code == 200 or resp.status_code == 429: blob = resp.json() if 'version' in blob: return blob['version'] else: raise aomi.exceptions.VaultProblem('Health check failed') return None
python
def server_version(self): """Attempts to determine the version of Vault that a server is running. Some actions will change on older Vault deployments.""" health_url = "%s/v1/sys/health" % self.vault_addr resp = self.session.request('get', health_url, **self._kwargs) if resp.status_code == 200 or resp.status_code == 429: blob = resp.json() if 'version' in blob: return blob['version'] else: raise aomi.exceptions.VaultProblem('Health check failed') return None
[ "def", "server_version", "(", "self", ")", ":", "health_url", "=", "\"%s/v1/sys/health\"", "%", "self", ".", "vault_addr", "resp", "=", "self", ".", "session", ".", "request", "(", "'get'", ",", "health_url", ",", "*", "*", "self", ".", "_kwargs", ")", "...
Attempts to determine the version of Vault that a server is running. Some actions will change on older Vault deployments.
[ "Attempts", "to", "determine", "the", "version", "of", "Vault", "that", "a", "server", "is", "running", ".", "Some", "actions", "will", "change", "on", "older", "Vault", "deployments", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L191-L204
train
44,469
Autodesk/aomi
aomi/vault.py
Client.connect
def connect(self, opt): """This sets up the tokens we expect to see in a way that hvac also expects.""" if not self._kwargs['verify']: LOG.warning('Skipping SSL Validation!') self.version = self.server_version() self.token = self.init_token() my_token = self.lookup_token() if not my_token or 'data' not in my_token: raise aomi.exceptions.AomiCredentials('initial token') display_name = my_token['data']['display_name'] vsn_string = "" if self.version: vsn_string = ", v%s" % self.version else: LOG.warning("Unable to deterine Vault version. Not all " "functionality is supported") LOG.info("Connected to %s as %s%s", self._url, display_name, vsn_string) if opt.reuse_token: LOG.debug("Not creating operational token") self.initial_token = self.token self.operational_token = self.token else: self.initial_token = self.token self.operational_token = self.op_token(display_name, opt) if not self.is_authenticated(): raise aomi.exceptions.AomiCredentials('operational token') self.token = self.operational_token return self
python
def connect(self, opt): """This sets up the tokens we expect to see in a way that hvac also expects.""" if not self._kwargs['verify']: LOG.warning('Skipping SSL Validation!') self.version = self.server_version() self.token = self.init_token() my_token = self.lookup_token() if not my_token or 'data' not in my_token: raise aomi.exceptions.AomiCredentials('initial token') display_name = my_token['data']['display_name'] vsn_string = "" if self.version: vsn_string = ", v%s" % self.version else: LOG.warning("Unable to deterine Vault version. Not all " "functionality is supported") LOG.info("Connected to %s as %s%s", self._url, display_name, vsn_string) if opt.reuse_token: LOG.debug("Not creating operational token") self.initial_token = self.token self.operational_token = self.token else: self.initial_token = self.token self.operational_token = self.op_token(display_name, opt) if not self.is_authenticated(): raise aomi.exceptions.AomiCredentials('operational token') self.token = self.operational_token return self
[ "def", "connect", "(", "self", ",", "opt", ")", ":", "if", "not", "self", ".", "_kwargs", "[", "'verify'", "]", ":", "LOG", ".", "warning", "(", "'Skipping SSL Validation!'", ")", "self", ".", "version", "=", "self", ".", "server_version", "(", ")", "s...
This sets up the tokens we expect to see in a way that hvac also expects.
[ "This", "sets", "up", "the", "tokens", "we", "expect", "to", "see", "in", "a", "way", "that", "hvac", "also", "expects", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L206-L243
train
44,470
Autodesk/aomi
aomi/vault.py
Client.init_token
def init_token(self): """Generate our first token based on workstation configuration""" app_filename = appid_file() token_filename = token_file() approle_filename = approle_file() token = None if 'VAULT_ROLE_ID' in os.environ and \ 'VAULT_SECRET_ID' in os.environ and \ os.environ['VAULT_ROLE_ID'] and os.environ['VAULT_SECRET_ID']: token = approle_token(self, os.environ['VAULT_ROLE_ID'], os.environ['VAULT_SECRET_ID']) LOG.debug("Token derived from VAULT_ROLE_ID and VAULT_SECRET_ID") elif 'VAULT_TOKEN' in os.environ and os.environ['VAULT_TOKEN']: LOG.debug('Token derived from VAULT_TOKEN environment variable') token = os.environ['VAULT_TOKEN'].strip() elif 'VAULT_USER_ID' in os.environ and \ 'VAULT_APP_ID' in os.environ and \ os.environ['VAULT_USER_ID'] and os.environ['VAULT_APP_ID']: LOG.debug("Token derived from VAULT_APP_ID and VAULT_USER_ID") token = app_token(self, os.environ['VAULT_APP_ID'].strip(), os.environ['VAULT_USER_ID'].strip()) elif approle_filename: creds = yaml.safe_load(open(approle_filename).read().strip()) if 'role_id' in creds and 'secret_id' in creds: LOG.debug("Token derived from approle file") token = approle_token(self, creds['role_id'], creds['secret_id']) elif token_filename: LOG.debug("Token derived from %s", token_filename) try: token = open(token_filename, 'r').read().strip() except IOError as os_exception: if os_exception.errno == 21: raise aomi.exceptions.AomiFile('Bad Vault token file') raise elif app_filename: token = yaml.safe_load(open(app_filename).read().strip()) if 'app_id' in token and 'user_id' in token: LOG.debug("Token derived from %s", app_filename) token = app_token(self, token['app_id'], token['user_id']) else: raise aomi.exceptions.AomiCredentials('unknown method') return token
python
def init_token(self): """Generate our first token based on workstation configuration""" app_filename = appid_file() token_filename = token_file() approle_filename = approle_file() token = None if 'VAULT_ROLE_ID' in os.environ and \ 'VAULT_SECRET_ID' in os.environ and \ os.environ['VAULT_ROLE_ID'] and os.environ['VAULT_SECRET_ID']: token = approle_token(self, os.environ['VAULT_ROLE_ID'], os.environ['VAULT_SECRET_ID']) LOG.debug("Token derived from VAULT_ROLE_ID and VAULT_SECRET_ID") elif 'VAULT_TOKEN' in os.environ and os.environ['VAULT_TOKEN']: LOG.debug('Token derived from VAULT_TOKEN environment variable') token = os.environ['VAULT_TOKEN'].strip() elif 'VAULT_USER_ID' in os.environ and \ 'VAULT_APP_ID' in os.environ and \ os.environ['VAULT_USER_ID'] and os.environ['VAULT_APP_ID']: LOG.debug("Token derived from VAULT_APP_ID and VAULT_USER_ID") token = app_token(self, os.environ['VAULT_APP_ID'].strip(), os.environ['VAULT_USER_ID'].strip()) elif approle_filename: creds = yaml.safe_load(open(approle_filename).read().strip()) if 'role_id' in creds and 'secret_id' in creds: LOG.debug("Token derived from approle file") token = approle_token(self, creds['role_id'], creds['secret_id']) elif token_filename: LOG.debug("Token derived from %s", token_filename) try: token = open(token_filename, 'r').read().strip() except IOError as os_exception: if os_exception.errno == 21: raise aomi.exceptions.AomiFile('Bad Vault token file') raise elif app_filename: token = yaml.safe_load(open(app_filename).read().strip()) if 'app_id' in token and 'user_id' in token: LOG.debug("Token derived from %s", app_filename) token = app_token(self, token['app_id'], token['user_id']) else: raise aomi.exceptions.AomiCredentials('unknown method') return token
[ "def", "init_token", "(", "self", ")", ":", "app_filename", "=", "appid_file", "(", ")", "token_filename", "=", "token_file", "(", ")", "approle_filename", "=", "approle_file", "(", ")", "token", "=", "None", "if", "'VAULT_ROLE_ID'", "in", "os", ".", "enviro...
Generate our first token based on workstation configuration
[ "Generate", "our", "first", "token", "based", "on", "workstation", "configuration" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L245-L295
train
44,471
Autodesk/aomi
aomi/vault.py
Client.op_token
def op_token(self, display_name, opt): """Return a properly annotated token for our use. This token will be revoked at the end of the session. The token will have some decent amounts of metadata tho.""" args = { 'lease': opt.lease, 'display_name': display_name, 'meta': token_meta(opt) } try: token = self.create_token(**args) except (hvac.exceptions.InvalidRequest, hvac.exceptions.Forbidden) as vault_exception: if vault_exception.errors[0] == 'permission denied': emsg = "Permission denied creating operational token" raise aomi.exceptions.AomiCredentials(emsg) else: raise LOG.debug("Created operational token with lease of %s", opt.lease) return token['auth']['client_token']
python
def op_token(self, display_name, opt): """Return a properly annotated token for our use. This token will be revoked at the end of the session. The token will have some decent amounts of metadata tho.""" args = { 'lease': opt.lease, 'display_name': display_name, 'meta': token_meta(opt) } try: token = self.create_token(**args) except (hvac.exceptions.InvalidRequest, hvac.exceptions.Forbidden) as vault_exception: if vault_exception.errors[0] == 'permission denied': emsg = "Permission denied creating operational token" raise aomi.exceptions.AomiCredentials(emsg) else: raise LOG.debug("Created operational token with lease of %s", opt.lease) return token['auth']['client_token']
[ "def", "op_token", "(", "self", ",", "display_name", ",", "opt", ")", ":", "args", "=", "{", "'lease'", ":", "opt", ".", "lease", ",", "'display_name'", ":", "display_name", ",", "'meta'", ":", "token_meta", "(", "opt", ")", "}", "try", ":", "token", ...
Return a properly annotated token for our use. This token will be revoked at the end of the session. The token will have some decent amounts of metadata tho.
[ "Return", "a", "properly", "annotated", "token", "for", "our", "use", ".", "This", "token", "will", "be", "revoked", "at", "the", "end", "of", "the", "session", ".", "The", "token", "will", "have", "some", "decent", "amounts", "of", "metadata", "tho", "....
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L297-L317
train
44,472
Autodesk/aomi
aomi/vault.py
Client.read
def read(self, path, wrap_ttl=None): """Wrap the hvac read call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, self).read(path, wrap_ttl) self.token = self.operational_token return val return super(Client, self).read(path, wrap_ttl)
python
def read(self, path, wrap_ttl=None): """Wrap the hvac read call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, self).read(path, wrap_ttl) self.token = self.operational_token return val return super(Client, self).read(path, wrap_ttl)
[ "def", "read", "(", "self", ",", "path", ",", "wrap_ttl", "=", "None", ")", ":", "path", "=", "sanitize_mount", "(", "path", ")", "if", "path", ".", "startswith", "(", "'cubbyhole'", ")", ":", "self", ".", "token", "=", "self", ".", "initial_token", ...
Wrap the hvac read call, using the right token for cubbyhole interactions.
[ "Wrap", "the", "hvac", "read", "call", "using", "the", "right", "token", "for", "cubbyhole", "interactions", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L319-L329
train
44,473
Autodesk/aomi
aomi/vault.py
Client.write
def write(self, path, wrap_ttl=None, **kwargs): """Wrap the hvac write call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) val = None if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, self).write(path, wrap_ttl=wrap_ttl, **kwargs) self.token = self.operational_token else: super(Client, self).write(path, wrap_ttl=wrap_ttl, **kwargs) return val
python
def write(self, path, wrap_ttl=None, **kwargs): """Wrap the hvac write call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) val = None if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, self).write(path, wrap_ttl=wrap_ttl, **kwargs) self.token = self.operational_token else: super(Client, self).write(path, wrap_ttl=wrap_ttl, **kwargs) return val
[ "def", "write", "(", "self", ",", "path", ",", "wrap_ttl", "=", "None", ",", "*", "*", "kwargs", ")", ":", "path", "=", "sanitize_mount", "(", "path", ")", "val", "=", "None", "if", "path", ".", "startswith", "(", "'cubbyhole'", ")", ":", "self", "...
Wrap the hvac write call, using the right token for cubbyhole interactions.
[ "Wrap", "the", "hvac", "write", "call", "using", "the", "right", "token", "for", "cubbyhole", "interactions", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L331-L343
train
44,474
Autodesk/aomi
aomi/vault.py
Client.delete
def delete(self, path): """Wrap the hvac delete call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) val = None if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, self).delete(path) self.token = self.operational_token else: super(Client, self).delete(path) return val
python
def delete(self, path): """Wrap the hvac delete call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) val = None if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, self).delete(path) self.token = self.operational_token else: super(Client, self).delete(path) return val
[ "def", "delete", "(", "self", ",", "path", ")", ":", "path", "=", "sanitize_mount", "(", "path", ")", "val", "=", "None", "if", "path", ".", "startswith", "(", "'cubbyhole'", ")", ":", "self", ".", "token", "=", "self", ".", "initial_token", "val", "...
Wrap the hvac delete call, using the right token for cubbyhole interactions.
[ "Wrap", "the", "hvac", "delete", "call", "using", "the", "right", "token", "for", "cubbyhole", "interactions", "." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L345-L357
train
44,475
Autodesk/aomi
aomi/filez.py
from_keybase
def from_keybase(username): """Will attempt to retrieve a GPG public key from Keybase, importing if neccesary""" public_key = key_from_keybase(username) fingerprint = public_key['fingerprint'][-8:].upper().encode('ascii') key = public_key['bundle'].encode('ascii') if not has_gpg_key(fingerprint): LOG.debug("Importing gpg key for %s", username) if not import_gpg_key(key): raise aomi.exceptions.KeybaseAPI("import key for %s" % username) return fingerprint
python
def from_keybase(username): """Will attempt to retrieve a GPG public key from Keybase, importing if neccesary""" public_key = key_from_keybase(username) fingerprint = public_key['fingerprint'][-8:].upper().encode('ascii') key = public_key['bundle'].encode('ascii') if not has_gpg_key(fingerprint): LOG.debug("Importing gpg key for %s", username) if not import_gpg_key(key): raise aomi.exceptions.KeybaseAPI("import key for %s" % username) return fingerprint
[ "def", "from_keybase", "(", "username", ")", ":", "public_key", "=", "key_from_keybase", "(", "username", ")", "fingerprint", "=", "public_key", "[", "'fingerprint'", "]", "[", "-", "8", ":", "]", ".", "upper", "(", ")", ".", "encode", "(", "'ascii'", ")...
Will attempt to retrieve a GPG public key from Keybase, importing if neccesary
[ "Will", "attempt", "to", "retrieve", "a", "GPG", "public", "key", "from", "Keybase", "importing", "if", "neccesary" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/filez.py#L21-L32
train
44,476
Autodesk/aomi
aomi/filez.py
grok_keys
def grok_keys(config): """Will retrieve a GPG key from either Keybase or GPG directly""" key_ids = [] for key in config['pgp_keys']: if key.startswith('keybase:'): key_id = from_keybase(key[8:]) LOG.debug("Encrypting for keybase user %s", key[8:]) else: if not has_gpg_key(key): raise aomi.exceptions.GPG("Do not actually have key %s" % key) LOG.debug("Encrypting for gpg id %s", key) key_id = key validate_gpg_fingerprint(key_id) key_ids.append(key_id) return key_ids
python
def grok_keys(config): """Will retrieve a GPG key from either Keybase or GPG directly""" key_ids = [] for key in config['pgp_keys']: if key.startswith('keybase:'): key_id = from_keybase(key[8:]) LOG.debug("Encrypting for keybase user %s", key[8:]) else: if not has_gpg_key(key): raise aomi.exceptions.GPG("Do not actually have key %s" % key) LOG.debug("Encrypting for gpg id %s", key) key_id = key validate_gpg_fingerprint(key_id) key_ids.append(key_id) return key_ids
[ "def", "grok_keys", "(", "config", ")", ":", "key_ids", "=", "[", "]", "for", "key", "in", "config", "[", "'pgp_keys'", "]", ":", "if", "key", ".", "startswith", "(", "'keybase:'", ")", ":", "key_id", "=", "from_keybase", "(", "key", "[", "8", ":", ...
Will retrieve a GPG key from either Keybase or GPG directly
[ "Will", "retrieve", "a", "GPG", "key", "from", "either", "Keybase", "or", "GPG", "directly" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/filez.py#L35-L52
train
44,477
Autodesk/aomi
aomi/filez.py
freeze_archive
def freeze_archive(tmp_dir, dest_prefix): """Generates a ZIP file of secrets""" zip_filename = "%s/aomi-blah.zip" % tmp_dir archive = zipfile.ZipFile(zip_filename, 'w') for root, _dirnames, filenames in os.walk(dest_prefix): for filename in filenames: relative_path = subdir_path(root, dest_prefix).split(os.sep)[1:] relative_path = os.sep.join(relative_path) archive.write("%s/%s" % (root, filename), "%s/%s" % (relative_path, filename)) archive.close() return zip_filename
python
def freeze_archive(tmp_dir, dest_prefix): """Generates a ZIP file of secrets""" zip_filename = "%s/aomi-blah.zip" % tmp_dir archive = zipfile.ZipFile(zip_filename, 'w') for root, _dirnames, filenames in os.walk(dest_prefix): for filename in filenames: relative_path = subdir_path(root, dest_prefix).split(os.sep)[1:] relative_path = os.sep.join(relative_path) archive.write("%s/%s" % (root, filename), "%s/%s" % (relative_path, filename)) archive.close() return zip_filename
[ "def", "freeze_archive", "(", "tmp_dir", ",", "dest_prefix", ")", ":", "zip_filename", "=", "\"%s/aomi-blah.zip\"", "%", "tmp_dir", "archive", "=", "zipfile", ".", "ZipFile", "(", "zip_filename", ",", "'w'", ")", "for", "root", ",", "_dirnames", ",", "filename...
Generates a ZIP file of secrets
[ "Generates", "a", "ZIP", "file", "of", "secrets" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/filez.py#L55-L67
train
44,478
Autodesk/aomi
aomi/filez.py
freeze_encrypt
def freeze_encrypt(dest_dir, zip_filename, config, opt): """Encrypts the zip file""" pgp_keys = grok_keys(config) icefile_prefix = "aomi-%s" % \ os.path.basename(os.path.dirname(opt.secretfile)) if opt.icefile_prefix: icefile_prefix = opt.icefile_prefix timestamp = time.strftime("%H%M%S-%m-%d-%Y", datetime.datetime.now().timetuple()) ice_file = "%s/%s-%s.ice" % (dest_dir, icefile_prefix, timestamp) if not encrypt(zip_filename, ice_file, pgp_keys): raise aomi.exceptions.GPG("Unable to encrypt zipfile") return ice_file
python
def freeze_encrypt(dest_dir, zip_filename, config, opt): """Encrypts the zip file""" pgp_keys = grok_keys(config) icefile_prefix = "aomi-%s" % \ os.path.basename(os.path.dirname(opt.secretfile)) if opt.icefile_prefix: icefile_prefix = opt.icefile_prefix timestamp = time.strftime("%H%M%S-%m-%d-%Y", datetime.datetime.now().timetuple()) ice_file = "%s/%s-%s.ice" % (dest_dir, icefile_prefix, timestamp) if not encrypt(zip_filename, ice_file, pgp_keys): raise aomi.exceptions.GPG("Unable to encrypt zipfile") return ice_file
[ "def", "freeze_encrypt", "(", "dest_dir", ",", "zip_filename", ",", "config", ",", "opt", ")", ":", "pgp_keys", "=", "grok_keys", "(", "config", ")", "icefile_prefix", "=", "\"aomi-%s\"", "%", "os", ".", "path", ".", "basename", "(", "os", ".", "path", "...
Encrypts the zip file
[ "Encrypts", "the", "zip", "file" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/filez.py#L70-L84
train
44,479
Autodesk/aomi
aomi/filez.py
freeze
def freeze(dest_dir, opt): """Iterates over the Secretfile looking for secrets to freeze""" tmp_dir = ensure_tmpdir() dest_prefix = "%s/dest" % tmp_dir ensure_dir(dest_dir) ensure_dir(dest_prefix) config = get_secretfile(opt) Context.load(config, opt) \ .freeze(dest_prefix) zip_filename = freeze_archive(tmp_dir, dest_prefix) ice_file = freeze_encrypt(dest_dir, zip_filename, config, opt) shutil.rmtree(tmp_dir) LOG.debug("Generated file is %s", ice_file)
python
def freeze(dest_dir, opt): """Iterates over the Secretfile looking for secrets to freeze""" tmp_dir = ensure_tmpdir() dest_prefix = "%s/dest" % tmp_dir ensure_dir(dest_dir) ensure_dir(dest_prefix) config = get_secretfile(opt) Context.load(config, opt) \ .freeze(dest_prefix) zip_filename = freeze_archive(tmp_dir, dest_prefix) ice_file = freeze_encrypt(dest_dir, zip_filename, config, opt) shutil.rmtree(tmp_dir) LOG.debug("Generated file is %s", ice_file)
[ "def", "freeze", "(", "dest_dir", ",", "opt", ")", ":", "tmp_dir", "=", "ensure_tmpdir", "(", ")", "dest_prefix", "=", "\"%s/dest\"", "%", "tmp_dir", "ensure_dir", "(", "dest_dir", ")", "ensure_dir", "(", "dest_prefix", ")", "config", "=", "get_secretfile", ...
Iterates over the Secretfile looking for secrets to freeze
[ "Iterates", "over", "the", "Secretfile", "looking", "for", "secrets", "to", "freeze" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/filez.py#L87-L99
train
44,480
Autodesk/aomi
aomi/filez.py
thaw_decrypt
def thaw_decrypt(vault_client, src_file, tmp_dir, opt): """Decrypts the encrypted ice file""" if not os.path.isdir(opt.secrets): LOG.info("Creating secret directory %s", opt.secrets) os.mkdir(opt.secrets) zip_file = "%s/aomi.zip" % tmp_dir if opt.gpg_pass_path: gpg_path_bits = opt.gpg_pass_path.split('/') gpg_path = '/'.join(gpg_path_bits[0:len(gpg_path_bits) - 1]) gpg_field = gpg_path_bits[len(gpg_path_bits) - 1] resp = vault_client.read(gpg_path) gpg_pass = None if resp and 'data' in resp and gpg_field in resp['data']: gpg_pass = resp['data'][gpg_field] if not gpg_pass: raise aomi.exceptions.GPG("Unable to retrieve GPG password") LOG.debug("Retrieved GPG password from Vault") if not decrypt(src_file, zip_file, passphrase=gpg_pass): raise aomi.exceptions.GPG("Unable to gpg") else: raise aomi.exceptions.VaultData("Unable to retrieve GPG password") else: if not decrypt(src_file, zip_file): raise aomi.exceptions.GPG("Unable to gpg") return zip_file
python
def thaw_decrypt(vault_client, src_file, tmp_dir, opt): """Decrypts the encrypted ice file""" if not os.path.isdir(opt.secrets): LOG.info("Creating secret directory %s", opt.secrets) os.mkdir(opt.secrets) zip_file = "%s/aomi.zip" % tmp_dir if opt.gpg_pass_path: gpg_path_bits = opt.gpg_pass_path.split('/') gpg_path = '/'.join(gpg_path_bits[0:len(gpg_path_bits) - 1]) gpg_field = gpg_path_bits[len(gpg_path_bits) - 1] resp = vault_client.read(gpg_path) gpg_pass = None if resp and 'data' in resp and gpg_field in resp['data']: gpg_pass = resp['data'][gpg_field] if not gpg_pass: raise aomi.exceptions.GPG("Unable to retrieve GPG password") LOG.debug("Retrieved GPG password from Vault") if not decrypt(src_file, zip_file, passphrase=gpg_pass): raise aomi.exceptions.GPG("Unable to gpg") else: raise aomi.exceptions.VaultData("Unable to retrieve GPG password") else: if not decrypt(src_file, zip_file): raise aomi.exceptions.GPG("Unable to gpg") return zip_file
[ "def", "thaw_decrypt", "(", "vault_client", ",", "src_file", ",", "tmp_dir", ",", "opt", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "opt", ".", "secrets", ")", ":", "LOG", ".", "info", "(", "\"Creating secret directory %s\"", ",", "opt"...
Decrypts the encrypted ice file
[ "Decrypts", "the", "encrypted", "ice", "file" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/filez.py#L102-L132
train
44,481
Autodesk/aomi
aomi/filez.py
thaw
def thaw(vault_client, src_file, opt): """Given the combination of a Secretfile and the output of a freeze operation, will restore secrets to usable locations""" if not os.path.exists(src_file): raise aomi.exceptions.AomiFile("%s does not exist" % src_file) tmp_dir = ensure_tmpdir() zip_file = thaw_decrypt(vault_client, src_file, tmp_dir, opt) archive = zipfile.ZipFile(zip_file, 'r') for archive_file in archive.namelist(): archive.extract(archive_file, tmp_dir) os.chmod("%s/%s" % (tmp_dir, archive_file), 0o640) LOG.debug("Extracted %s from archive", archive_file) LOG.info("Thawing secrets into %s", opt.secrets) config = get_secretfile(opt) Context.load(config, opt) \ .thaw(tmp_dir)
python
def thaw(vault_client, src_file, opt): """Given the combination of a Secretfile and the output of a freeze operation, will restore secrets to usable locations""" if not os.path.exists(src_file): raise aomi.exceptions.AomiFile("%s does not exist" % src_file) tmp_dir = ensure_tmpdir() zip_file = thaw_decrypt(vault_client, src_file, tmp_dir, opt) archive = zipfile.ZipFile(zip_file, 'r') for archive_file in archive.namelist(): archive.extract(archive_file, tmp_dir) os.chmod("%s/%s" % (tmp_dir, archive_file), 0o640) LOG.debug("Extracted %s from archive", archive_file) LOG.info("Thawing secrets into %s", opt.secrets) config = get_secretfile(opt) Context.load(config, opt) \ .thaw(tmp_dir)
[ "def", "thaw", "(", "vault_client", ",", "src_file", ",", "opt", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "src_file", ")", ":", "raise", "aomi", ".", "exceptions", ".", "AomiFile", "(", "\"%s does not exist\"", "%", "src_file", ")", ...
Given the combination of a Secretfile and the output of a freeze operation, will restore secrets to usable locations
[ "Given", "the", "combination", "of", "a", "Secretfile", "and", "the", "output", "of", "a", "freeze", "operation", "will", "restore", "secrets", "to", "usable", "locations" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/filez.py#L135-L152
train
44,482
Autodesk/aomi
aomi/model/backend.py
VaultBackend.diff
def diff(self): """Determines if changes are needed for the Vault backend""" if not self.present: if self.existing: return DEL return NOOP is_diff = NOOP if self.present and self.existing: a_obj = self.config.copy() if self.config and diff_dict(a_obj, self.existing, True): is_diff = CHANGED if self.description != self.existing.get('description'): is_diff = CONFLICT elif self.present and not self.existing: is_diff = ADD return is_diff
python
def diff(self): """Determines if changes are needed for the Vault backend""" if not self.present: if self.existing: return DEL return NOOP is_diff = NOOP if self.present and self.existing: a_obj = self.config.copy() if self.config and diff_dict(a_obj, self.existing, True): is_diff = CHANGED if self.description != self.existing.get('description'): is_diff = CONFLICT elif self.present and not self.existing: is_diff = ADD return is_diff
[ "def", "diff", "(", "self", ")", ":", "if", "not", "self", ".", "present", ":", "if", "self", ".", "existing", ":", "return", "DEL", "return", "NOOP", "is_diff", "=", "NOOP", "if", "self", ".", "present", "and", "self", ".", "existing", ":", "a_obj",...
Determines if changes are needed for the Vault backend
[ "Determines", "if", "changes", "are", "needed", "for", "the", "Vault", "backend" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/backend.py#L62-L83
train
44,483
Autodesk/aomi
aomi/model/backend.py
VaultBackend.sync
def sync(self, vault_client): """Synchronizes the local and remote Vault resources. Has the net effect of adding backend if needed""" if self.present: if not self.existing: LOG.info("Mounting %s backend on %s", self.backend, self.path) self.actually_mount(vault_client) else: LOG.info("%s backend already mounted on %s", self.backend, self.path) else: if self.existing: LOG.info("Unmounting %s backend on %s", self.backend, self.path) self.unmount(vault_client) else: LOG.info("%s backend already unmounted on %s", self.backend, self.path) if self.present and vault_client.version: self.sync_tunables(vault_client)
python
def sync(self, vault_client): """Synchronizes the local and remote Vault resources. Has the net effect of adding backend if needed""" if self.present: if not self.existing: LOG.info("Mounting %s backend on %s", self.backend, self.path) self.actually_mount(vault_client) else: LOG.info("%s backend already mounted on %s", self.backend, self.path) else: if self.existing: LOG.info("Unmounting %s backend on %s", self.backend, self.path) self.unmount(vault_client) else: LOG.info("%s backend already unmounted on %s", self.backend, self.path) if self.present and vault_client.version: self.sync_tunables(vault_client)
[ "def", "sync", "(", "self", ",", "vault_client", ")", ":", "if", "self", ".", "present", ":", "if", "not", "self", ".", "existing", ":", "LOG", ".", "info", "(", "\"Mounting %s backend on %s\"", ",", "self", ".", "backend", ",", "self", ".", "path", ")...
Synchronizes the local and remote Vault resources. Has the net effect of adding backend if needed
[ "Synchronizes", "the", "local", "and", "remote", "Vault", "resources", ".", "Has", "the", "net", "effect", "of", "adding", "backend", "if", "needed" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/backend.py#L85-L106
train
44,484
Autodesk/aomi
aomi/model/backend.py
VaultBackend.sync_tunables
def sync_tunables(self, vault_client): """Synchtonizes any tunables we have set""" if not self.config: return a_prefix = self.tune_prefix if self.tune_prefix: a_prefix = "%s/" % self.tune_prefix v_path = "sys/mounts/%s%s/tune" % (a_prefix, self.path) a_obj = self.config.copy() if 'description' in a_obj: del a_obj['description'] t_resp = vault_client.write(v_path, **a_obj) if t_resp and 'errors' in t_resp and t_resp['errors']: e_msg = "Unable to update tuning info for %s" % self raise aomi_excep.VaultData(e_msg)
python
def sync_tunables(self, vault_client): """Synchtonizes any tunables we have set""" if not self.config: return a_prefix = self.tune_prefix if self.tune_prefix: a_prefix = "%s/" % self.tune_prefix v_path = "sys/mounts/%s%s/tune" % (a_prefix, self.path) a_obj = self.config.copy() if 'description' in a_obj: del a_obj['description'] t_resp = vault_client.write(v_path, **a_obj) if t_resp and 'errors' in t_resp and t_resp['errors']: e_msg = "Unable to update tuning info for %s" % self raise aomi_excep.VaultData(e_msg)
[ "def", "sync_tunables", "(", "self", ",", "vault_client", ")", ":", "if", "not", "self", ".", "config", ":", "return", "a_prefix", "=", "self", ".", "tune_prefix", "if", "self", ".", "tune_prefix", ":", "a_prefix", "=", "\"%s/\"", "%", "self", ".", "tune...
Synchtonizes any tunables we have set
[ "Synchtonizes", "any", "tunables", "we", "have", "set" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/backend.py#L108-L125
train
44,485
Autodesk/aomi
aomi/model/backend.py
VaultBackend.fetch
def fetch(self, vault_client, backends): """Updates local resource with context on whether this backend is actually mounted and available""" if not is_mounted(self.backend, self.path, backends) or \ self.tune_prefix is None: return backend_details = get_backend(self.backend, self.path, backends) self.existing = backend_details['config'] if backend_details['description']: self.existing['description'] = backend_details['description'] if vault_client.version is None: return if not self.managed: return a_prefix = self.tune_prefix if self.tune_prefix: a_prefix = "%s/" % self.tune_prefix v_path = "sys/mounts/%s%s/tune" % (a_prefix, self.path) t_resp = vault_client.read(v_path) if 'data' not in t_resp: e_msg = "Unable to retrieve tuning info for %s" % self raise aomi_excep.VaultData(e_msg) e_obj = t_resp['data'] e_obj['description'] = None n_path = normalize_vault_path(self.path) if n_path in backends: a_mount = backends[n_path] if 'description' in a_mount and a_mount['description']: e_obj['description'] = a_mount['description'] self.existing = e_obj
python
def fetch(self, vault_client, backends): """Updates local resource with context on whether this backend is actually mounted and available""" if not is_mounted(self.backend, self.path, backends) or \ self.tune_prefix is None: return backend_details = get_backend(self.backend, self.path, backends) self.existing = backend_details['config'] if backend_details['description']: self.existing['description'] = backend_details['description'] if vault_client.version is None: return if not self.managed: return a_prefix = self.tune_prefix if self.tune_prefix: a_prefix = "%s/" % self.tune_prefix v_path = "sys/mounts/%s%s/tune" % (a_prefix, self.path) t_resp = vault_client.read(v_path) if 'data' not in t_resp: e_msg = "Unable to retrieve tuning info for %s" % self raise aomi_excep.VaultData(e_msg) e_obj = t_resp['data'] e_obj['description'] = None n_path = normalize_vault_path(self.path) if n_path in backends: a_mount = backends[n_path] if 'description' in a_mount and a_mount['description']: e_obj['description'] = a_mount['description'] self.existing = e_obj
[ "def", "fetch", "(", "self", ",", "vault_client", ",", "backends", ")", ":", "if", "not", "is_mounted", "(", "self", ".", "backend", ",", "self", ".", "path", ",", "backends", ")", "or", "self", ".", "tune_prefix", "is", "None", ":", "return", "backend...
Updates local resource with context on whether this backend is actually mounted and available
[ "Updates", "local", "resource", "with", "context", "on", "whether", "this", "backend", "is", "actually", "mounted", "and", "available" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/backend.py#L127-L163
train
44,486
Autodesk/aomi
aomi/model/backend.py
VaultBackend.unmount
def unmount(self, client): """Unmounts a backend within Vault""" getattr(client, self.unmount_fun)(mount_point=self.path)
python
def unmount(self, client): """Unmounts a backend within Vault""" getattr(client, self.unmount_fun)(mount_point=self.path)
[ "def", "unmount", "(", "self", ",", "client", ")", ":", "getattr", "(", "client", ",", "self", ".", "unmount_fun", ")", "(", "mount_point", "=", "self", ".", "path", ")" ]
Unmounts a backend within Vault
[ "Unmounts", "a", "backend", "within", "Vault" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/backend.py#L165-L167
train
44,487
Autodesk/aomi
aomi/model/backend.py
VaultBackend.actually_mount
def actually_mount(self, client): """Actually mount something in Vault""" a_obj = self.config.copy() if 'description' in a_obj: del a_obj['description'] try: m_fun = getattr(client, self.mount_fun) if self.description and a_obj: m_fun(self.backend, mount_point=self.path, description=self.description, config=a_obj) elif self.description: m_fun(self.backend, mount_point=self.path, description=self.description) elif a_obj: m_fun(self.backend, mount_point=self.path, config=a_obj) else: m_fun(self.backend, mount_point=self.path) except hvac.exceptions.InvalidRequest as exception: match = re.match('existing mount at (?P<path>.+)', str(exception)) if match: e_msg = "%s has a mountpoint conflict with %s" % \ (self.path, match.group('path')) raise aomi_excep.VaultConstraint(e_msg) else: raise
python
def actually_mount(self, client): """Actually mount something in Vault""" a_obj = self.config.copy() if 'description' in a_obj: del a_obj['description'] try: m_fun = getattr(client, self.mount_fun) if self.description and a_obj: m_fun(self.backend, mount_point=self.path, description=self.description, config=a_obj) elif self.description: m_fun(self.backend, mount_point=self.path, description=self.description) elif a_obj: m_fun(self.backend, mount_point=self.path, config=a_obj) else: m_fun(self.backend, mount_point=self.path) except hvac.exceptions.InvalidRequest as exception: match = re.match('existing mount at (?P<path>.+)', str(exception)) if match: e_msg = "%s has a mountpoint conflict with %s" % \ (self.path, match.group('path')) raise aomi_excep.VaultConstraint(e_msg) else: raise
[ "def", "actually_mount", "(", "self", ",", "client", ")", ":", "a_obj", "=", "self", ".", "config", ".", "copy", "(", ")", "if", "'description'", "in", "a_obj", ":", "del", "a_obj", "[", "'description'", "]", "try", ":", "m_fun", "=", "getattr", "(", ...
Actually mount something in Vault
[ "Actually", "mount", "something", "in", "Vault" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/backend.py#L169-L200
train
44,488
Autodesk/aomi
aomi/model/resource.py
Resource.thaw
def thaw(self, tmp_dir): """Will perform some validation and copy a decrypted secret to it's final location""" for sfile in self.secrets(): src_file = "%s/%s" % (tmp_dir, sfile) err_msg = "%s secret missing from icefile" % (self) if not os.path.exists(src_file): if hasattr(self.opt, 'ignore_missing') and \ self.opt.ignore_missing: LOG.warning(err_msg) continue else: raise aomi_excep.IceFile(err_msg) dest_file = "%s/%s" % (self.opt.secrets, sfile) dest_dir = os.path.dirname(dest_file) if not os.path.exists(dest_dir): os.mkdir(dest_dir) shutil.copy(src_file, dest_file) LOG.debug("Thawed %s %s", self, sfile)
python
def thaw(self, tmp_dir): """Will perform some validation and copy a decrypted secret to it's final location""" for sfile in self.secrets(): src_file = "%s/%s" % (tmp_dir, sfile) err_msg = "%s secret missing from icefile" % (self) if not os.path.exists(src_file): if hasattr(self.opt, 'ignore_missing') and \ self.opt.ignore_missing: LOG.warning(err_msg) continue else: raise aomi_excep.IceFile(err_msg) dest_file = "%s/%s" % (self.opt.secrets, sfile) dest_dir = os.path.dirname(dest_file) if not os.path.exists(dest_dir): os.mkdir(dest_dir) shutil.copy(src_file, dest_file) LOG.debug("Thawed %s %s", self, sfile)
[ "def", "thaw", "(", "self", ",", "tmp_dir", ")", ":", "for", "sfile", "in", "self", ".", "secrets", "(", ")", ":", "src_file", "=", "\"%s/%s\"", "%", "(", "tmp_dir", ",", "sfile", ")", "err_msg", "=", "\"%s secret missing from icefile\"", "%", "(", "self...
Will perform some validation and copy a decrypted secret to it's final location
[ "Will", "perform", "some", "validation", "and", "copy", "a", "decrypted", "secret", "to", "it", "s", "final", "location" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L31-L51
train
44,489
Autodesk/aomi
aomi/model/resource.py
Resource.tunable
def tunable(self, obj): """A tunable resource maps against a backend...""" self.tune = dict() if 'tune' in obj: for tunable in MOUNT_TUNABLES: tunable_key = tunable[0] map_val(self.tune, obj['tune'], tunable_key) if tunable_key in self.tune and \ is_vault_time(self.tune[tunable_key]): vault_time_s = vault_time_to_s(self.tune[tunable_key]) self.tune[tunable_key] = vault_time_s if 'description'in obj: self.tune['description'] = obj['description']
python
def tunable(self, obj): """A tunable resource maps against a backend...""" self.tune = dict() if 'tune' in obj: for tunable in MOUNT_TUNABLES: tunable_key = tunable[0] map_val(self.tune, obj['tune'], tunable_key) if tunable_key in self.tune and \ is_vault_time(self.tune[tunable_key]): vault_time_s = vault_time_to_s(self.tune[tunable_key]) self.tune[tunable_key] = vault_time_s if 'description'in obj: self.tune['description'] = obj['description']
[ "def", "tunable", "(", "self", ",", "obj", ")", ":", "self", ".", "tune", "=", "dict", "(", ")", "if", "'tune'", "in", "obj", ":", "for", "tunable", "in", "MOUNT_TUNABLES", ":", "tunable_key", "=", "tunable", "[", "0", "]", "map_val", "(", "self", ...
A tunable resource maps against a backend...
[ "A", "tunable", "resource", "maps", "against", "a", "backend", "..." ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L53-L66
train
44,490
Autodesk/aomi
aomi/model/resource.py
Resource.export_handle
def export_handle(self, directory): """Get a filehandle for exporting""" filename = getattr(self, 'filename') dest_file = "%s/%s" % (directory, filename) dest_dir = os.path.dirname(dest_file) if not os.path.isdir(dest_dir): os.mkdir(dest_dir, 0o700) return open(dest_file, 'w')
python
def export_handle(self, directory): """Get a filehandle for exporting""" filename = getattr(self, 'filename') dest_file = "%s/%s" % (directory, filename) dest_dir = os.path.dirname(dest_file) if not os.path.isdir(dest_dir): os.mkdir(dest_dir, 0o700) return open(dest_file, 'w')
[ "def", "export_handle", "(", "self", ",", "directory", ")", ":", "filename", "=", "getattr", "(", "self", ",", "'filename'", ")", "dest_file", "=", "\"%s/%s\"", "%", "(", "directory", ",", "filename", ")", "dest_dir", "=", "os", ".", "path", ".", "dirnam...
Get a filehandle for exporting
[ "Get", "a", "filehandle", "for", "exporting" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L68-L76
train
44,491
Autodesk/aomi
aomi/model/resource.py
Resource.export
def export(self, directory): """Export exportable resources decoding as needed""" if not self.existing or not hasattr(self, 'filename'): return secret_h = self.export_handle(directory) obj = self.existing if isinstance(obj, str): secret_h.write(obj) elif isinstance(obj, dict): secret_h.write(yaml.safe_dump(obj))
python
def export(self, directory): """Export exportable resources decoding as needed""" if not self.existing or not hasattr(self, 'filename'): return secret_h = self.export_handle(directory) obj = self.existing if isinstance(obj, str): secret_h.write(obj) elif isinstance(obj, dict): secret_h.write(yaml.safe_dump(obj))
[ "def", "export", "(", "self", ",", "directory", ")", ":", "if", "not", "self", ".", "existing", "or", "not", "hasattr", "(", "self", ",", "'filename'", ")", ":", "return", "secret_h", "=", "self", ".", "export_handle", "(", "directory", ")", "obj", "="...
Export exportable resources decoding as needed
[ "Export", "exportable", "resources", "decoding", "as", "needed" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L78-L88
train
44,492
Autodesk/aomi
aomi/model/resource.py
Resource.freeze
def freeze(self, tmp_dir): """Copies a secret into a particular location""" for sfile in self.secrets(): src_file = hard_path(sfile, self.opt.secrets) if not os.path.exists(src_file): raise aomi_excep.IceFile("%s secret not found at %s" % (self, src_file)) dest_file = "%s/%s" % (tmp_dir, sfile) dest_dir = os.path.dirname(dest_file) if not os.path.isdir(dest_dir): os.mkdir(dest_dir, 0o700) shutil.copy(src_file, dest_file) LOG.debug("Froze %s %s", self, sfile)
python
def freeze(self, tmp_dir): """Copies a secret into a particular location""" for sfile in self.secrets(): src_file = hard_path(sfile, self.opt.secrets) if not os.path.exists(src_file): raise aomi_excep.IceFile("%s secret not found at %s" % (self, src_file)) dest_file = "%s/%s" % (tmp_dir, sfile) dest_dir = os.path.dirname(dest_file) if not os.path.isdir(dest_dir): os.mkdir(dest_dir, 0o700) shutil.copy(src_file, dest_file) LOG.debug("Froze %s %s", self, sfile)
[ "def", "freeze", "(", "self", ",", "tmp_dir", ")", ":", "for", "sfile", "in", "self", ".", "secrets", "(", ")", ":", "src_file", "=", "hard_path", "(", "sfile", ",", "self", ".", "opt", ".", "secrets", ")", "if", "not", "os", ".", "path", ".", "e...
Copies a secret into a particular location
[ "Copies", "a", "secret", "into", "a", "particular", "location" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L90-L104
train
44,493
Autodesk/aomi
aomi/model/resource.py
Resource.grok_state
def grok_state(self, obj): """Determine the desired state of this resource based on data present""" if 'state' in obj: my_state = obj['state'].lower() if my_state != 'absent' and my_state != 'present': raise aomi_excep \ .Validation('state must be either "absent" or "present"') self.present = obj.get('state', 'present').lower() == 'present'
python
def grok_state(self, obj): """Determine the desired state of this resource based on data present""" if 'state' in obj: my_state = obj['state'].lower() if my_state != 'absent' and my_state != 'present': raise aomi_excep \ .Validation('state must be either "absent" or "present"') self.present = obj.get('state', 'present').lower() == 'present'
[ "def", "grok_state", "(", "self", ",", "obj", ")", ":", "if", "'state'", "in", "obj", ":", "my_state", "=", "obj", "[", "'state'", "]", ".", "lower", "(", ")", "if", "my_state", "!=", "'absent'", "and", "my_state", "!=", "'present'", ":", "raise", "a...
Determine the desired state of this resource based on data present
[ "Determine", "the", "desired", "state", "of", "this", "resource", "based", "on", "data", "present" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L110-L119
train
44,494
Autodesk/aomi
aomi/model/resource.py
Resource.validate
def validate(self, obj): """Base validation method. Will inspect class attributes to dermine just what should be present""" if 'tags' in obj and not isinstance(obj['tags'], list): raise aomi_excep.Validation('tags must be a list') if self.present: check_obj(self.required_fields, self.name(), obj)
python
def validate(self, obj): """Base validation method. Will inspect class attributes to dermine just what should be present""" if 'tags' in obj and not isinstance(obj['tags'], list): raise aomi_excep.Validation('tags must be a list') if self.present: check_obj(self.required_fields, self.name(), obj)
[ "def", "validate", "(", "self", ",", "obj", ")", ":", "if", "'tags'", "in", "obj", "and", "not", "isinstance", "(", "obj", "[", "'tags'", "]", ",", "list", ")", ":", "raise", "aomi_excep", ".", "Validation", "(", "'tags must be a list'", ")", "if", "se...
Base validation method. Will inspect class attributes to dermine just what should be present
[ "Base", "validation", "method", ".", "Will", "inspect", "class", "attributes", "to", "dermine", "just", "what", "should", "be", "present" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L121-L128
train
44,495
Autodesk/aomi
aomi/model/resource.py
Resource.diff
def diff(self, obj=None): """Determine if something has changed or not""" if self.no_resource: return NOOP if not self.present: if self.existing: return DEL return NOOP if not obj: obj = self.obj() is_diff = NOOP if self.present and self.existing: if isinstance(self.existing, dict): current = dict(self.existing) if 'refresh_interval' in current: del current['refresh_interval'] if diff_dict(current, obj): is_diff = CHANGED elif is_unicode(self.existing): if self.existing != obj: is_diff = CHANGED elif self.present and not self.existing: is_diff = ADD return is_diff
python
def diff(self, obj=None): """Determine if something has changed or not""" if self.no_resource: return NOOP if not self.present: if self.existing: return DEL return NOOP if not obj: obj = self.obj() is_diff = NOOP if self.present and self.existing: if isinstance(self.existing, dict): current = dict(self.existing) if 'refresh_interval' in current: del current['refresh_interval'] if diff_dict(current, obj): is_diff = CHANGED elif is_unicode(self.existing): if self.existing != obj: is_diff = CHANGED elif self.present and not self.existing: is_diff = ADD return is_diff
[ "def", "diff", "(", "self", ",", "obj", "=", "None", ")", ":", "if", "self", ".", "no_resource", ":", "return", "NOOP", "if", "not", "self", ".", "present", ":", "if", "self", ".", "existing", ":", "return", "DEL", "return", "NOOP", "if", "not", "o...
Determine if something has changed or not
[ "Determine", "if", "something", "has", "changed", "or", "not" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L158-L188
train
44,496
Autodesk/aomi
aomi/model/resource.py
Resource.fetch
def fetch(self, vault_client): """Populate internal representation of remote Vault resource contents""" result = self.read(vault_client) if result: if isinstance(result, dict) and 'data' in result: self.existing = result['data'] else: self.existing = result else: self.existing = None
python
def fetch(self, vault_client): """Populate internal representation of remote Vault resource contents""" result = self.read(vault_client) if result: if isinstance(result, dict) and 'data' in result: self.existing = result['data'] else: self.existing = result else: self.existing = None
[ "def", "fetch", "(", "self", ",", "vault_client", ")", ":", "result", "=", "self", ".", "read", "(", "vault_client", ")", "if", "result", ":", "if", "isinstance", "(", "result", ",", "dict", ")", "and", "'data'", "in", "result", ":", "self", ".", "ex...
Populate internal representation of remote Vault resource contents
[ "Populate", "internal", "representation", "of", "remote", "Vault", "resource", "contents" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L190-L200
train
44,497
Autodesk/aomi
aomi/model/resource.py
Resource.sync
def sync(self, vault_client): """Update remove Vault resource contents if needed""" if self.present and not self.existing: LOG.info("Writing new %s to %s", self.secret_format, self) self.write(vault_client) elif self.present and self.existing: if self.diff() == CHANGED or self.diff() == OVERWRITE: LOG.info("Updating %s in %s", self.secret_format, self) self.write(vault_client) elif not self.present and not self.existing: LOG.info("No %s to remove from %s", self.secret_format, self) elif not self.present and self.existing: LOG.info("Removing %s from %s", self.secret_format, self) self.delete(vault_client)
python
def sync(self, vault_client): """Update remove Vault resource contents if needed""" if self.present and not self.existing: LOG.info("Writing new %s to %s", self.secret_format, self) self.write(vault_client) elif self.present and self.existing: if self.diff() == CHANGED or self.diff() == OVERWRITE: LOG.info("Updating %s in %s", self.secret_format, self) self.write(vault_client) elif not self.present and not self.existing: LOG.info("No %s to remove from %s", self.secret_format, self) elif not self.present and self.existing: LOG.info("Removing %s from %s", self.secret_format, self) self.delete(vault_client)
[ "def", "sync", "(", "self", ",", "vault_client", ")", ":", "if", "self", ".", "present", "and", "not", "self", ".", "existing", ":", "LOG", ".", "info", "(", "\"Writing new %s to %s\"", ",", "self", ".", "secret_format", ",", "self", ")", "self", ".", ...
Update remove Vault resource contents if needed
[ "Update", "remove", "Vault", "resource", "contents", "if", "needed" ]
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L202-L219
train
44,498
Autodesk/aomi
aomi/model/resource.py
Resource.filtered
def filtered(self): """Determines whether or not resource is filtered. Resources may be filtered if the tags do not match or the user has specified explict paths to include or exclude via command line options""" if not is_tagged(self.tags, self.opt.tags): LOG.info("Skipping %s as it does not have requested tags", self.path) return False if not specific_path_check(self.path, self.opt): LOG.info("Skipping %s as it does not match specified paths", self.path) return False return True
python
def filtered(self): """Determines whether or not resource is filtered. Resources may be filtered if the tags do not match or the user has specified explict paths to include or exclude via command line options""" if not is_tagged(self.tags, self.opt.tags): LOG.info("Skipping %s as it does not have requested tags", self.path) return False if not specific_path_check(self.path, self.opt): LOG.info("Skipping %s as it does not match specified paths", self.path) return False return True
[ "def", "filtered", "(", "self", ")", ":", "if", "not", "is_tagged", "(", "self", ".", "tags", ",", "self", ".", "opt", ".", "tags", ")", ":", "LOG", ".", "info", "(", "\"Skipping %s as it does not have requested tags\"", ",", "self", ".", "path", ")", "r...
Determines whether or not resource is filtered. Resources may be filtered if the tags do not match or the user has specified explict paths to include or exclude via command line options
[ "Determines", "whether", "or", "not", "resource", "is", "filtered", ".", "Resources", "may", "be", "filtered", "if", "the", "tags", "do", "not", "match", "or", "the", "user", "has", "specified", "explict", "paths", "to", "include", "or", "exclude", "via", ...
84da2dfb0424837adf9c4ddc1aa352e942bb7a4a
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L221-L236
train
44,499