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
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
Gandi/gandi.cli | gandi/cli/commands/mail.py | info | def info(gandi, email):
"""Display information about a mailbox."""
login, domain = email
output_keys = ['login', 'aliases', 'fallback', 'quota', 'responder']
mailbox = gandi.mail.info(domain, login)
output_mailbox(gandi, mailbox, output_keys)
return mailbox | python | def info(gandi, email):
"""Display information about a mailbox."""
login, domain = email
output_keys = ['login', 'aliases', 'fallback', 'quota', 'responder']
mailbox = gandi.mail.info(domain, login)
output_mailbox(gandi, mailbox, output_keys)
return mailbox | [
"def",
"info",
"(",
"gandi",
",",
"email",
")",
":",
"login",
",",
"domain",
"=",
"email",
"output_keys",
"=",
"[",
"'login'",
",",
"'aliases'",
",",
"'fallback'",
",",
"'quota'",
",",
"'responder'",
"]",
"mailbox",
"=",
"gandi",
".",
"mail",
".",
"info",
"(",
"domain",
",",
"login",
")",
"output_mailbox",
"(",
"gandi",
",",
"mailbox",
",",
"output_keys",
")",
"return",
"mailbox"
] | Display information about a mailbox. | [
"Display",
"information",
"about",
"a",
"mailbox",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/mail.py#L32-L40 | train |
Gandi/gandi.cli | gandi/cli/commands/mail.py | delete | def delete(gandi, email, force):
"""Delete a mailbox."""
login, domain = email
if not force:
proceed = click.confirm('Are you sure to delete the '
'mailbox %s@%s ?' % (login, domain))
if not proceed:
return
result = gandi.mail.delete(domain, login)
return result | python | def delete(gandi, email, force):
"""Delete a mailbox."""
login, domain = email
if not force:
proceed = click.confirm('Are you sure to delete the '
'mailbox %s@%s ?' % (login, domain))
if not proceed:
return
result = gandi.mail.delete(domain, login)
return result | [
"def",
"delete",
"(",
"gandi",
",",
"email",
",",
"force",
")",
":",
"login",
",",
"domain",
"=",
"email",
"if",
"not",
"force",
":",
"proceed",
"=",
"click",
".",
"confirm",
"(",
"'Are you sure to delete the '",
"'mailbox %s@%s ?'",
"%",
"(",
"login",
",",
"domain",
")",
")",
"if",
"not",
"proceed",
":",
"return",
"result",
"=",
"gandi",
".",
"mail",
".",
"delete",
"(",
"domain",
",",
"login",
")",
"return",
"result"
] | Delete a mailbox. | [
"Delete",
"a",
"mailbox",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/mail.py#L79-L92 | train |
Gandi/gandi.cli | gandi/cli/modules/disk.py | Disk.from_name | def from_name(cls, name):
""" Retrieve a disk id associated to a name. """
disks = cls.list({'name': name})
if len(disks) == 1:
return disks[0]['id']
elif not disks:
return
raise DuplicateResults('disk name %s is ambiguous.' % name) | python | def from_name(cls, name):
""" Retrieve a disk id associated to a name. """
disks = cls.list({'name': name})
if len(disks) == 1:
return disks[0]['id']
elif not disks:
return
raise DuplicateResults('disk name %s is ambiguous.' % name) | [
"def",
"from_name",
"(",
"cls",
",",
"name",
")",
":",
"disks",
"=",
"cls",
".",
"list",
"(",
"{",
"'name'",
":",
"name",
"}",
")",
"if",
"len",
"(",
"disks",
")",
"==",
"1",
":",
"return",
"disks",
"[",
"0",
"]",
"[",
"'id'",
"]",
"elif",
"not",
"disks",
":",
"return",
"raise",
"DuplicateResults",
"(",
"'disk name %s is ambiguous.'",
"%",
"name",
")"
] | Retrieve a disk id associated to a name. | [
"Retrieve",
"a",
"disk",
"id",
"associated",
"to",
"a",
"name",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/disk.py#L26-L34 | train |
Gandi/gandi.cli | gandi/cli/modules/disk.py | Disk.list_create | def list_create(cls, datacenter=None, label=None):
"""List available disks for vm creation."""
options = {
'items_per_page': DISK_MAXLIST
}
if datacenter:
datacenter_id = int(Datacenter.usable_id(datacenter))
options['datacenter_id'] = datacenter_id
# implement a filter by label as API doesn't handle it
images = cls.safe_call('hosting.disk.list', options)
if not label:
return images
return [img for img in images
if label.lower() in img['name'].lower()] | python | def list_create(cls, datacenter=None, label=None):
"""List available disks for vm creation."""
options = {
'items_per_page': DISK_MAXLIST
}
if datacenter:
datacenter_id = int(Datacenter.usable_id(datacenter))
options['datacenter_id'] = datacenter_id
# implement a filter by label as API doesn't handle it
images = cls.safe_call('hosting.disk.list', options)
if not label:
return images
return [img for img in images
if label.lower() in img['name'].lower()] | [
"def",
"list_create",
"(",
"cls",
",",
"datacenter",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"options",
"=",
"{",
"'items_per_page'",
":",
"DISK_MAXLIST",
"}",
"if",
"datacenter",
":",
"datacenter_id",
"=",
"int",
"(",
"Datacenter",
".",
"usable_id",
"(",
"datacenter",
")",
")",
"options",
"[",
"'datacenter_id'",
"]",
"=",
"datacenter_id",
"# implement a filter by label as API doesn't handle it",
"images",
"=",
"cls",
".",
"safe_call",
"(",
"'hosting.disk.list'",
",",
"options",
")",
"if",
"not",
"label",
":",
"return",
"images",
"return",
"[",
"img",
"for",
"img",
"in",
"images",
"if",
"label",
".",
"lower",
"(",
")",
"in",
"img",
"[",
"'name'",
"]",
".",
"lower",
"(",
")",
"]"
] | List available disks for vm creation. | [
"List",
"available",
"disks",
"for",
"vm",
"creation",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/disk.py#L61-L75 | train |
Gandi/gandi.cli | gandi/cli/modules/disk.py | Disk.disk_param | def disk_param(name, size, snapshot_profile, cmdline=None, kernel=None):
""" Return disk parameter structure. """
disk_params = {}
if cmdline:
disk_params['cmdline'] = cmdline
if kernel:
disk_params['kernel'] = kernel
if name:
disk_params['name'] = name
if snapshot_profile is not None:
disk_params['snapshot_profile'] = snapshot_profile
if size:
disk_params['size'] = size
return disk_params | python | def disk_param(name, size, snapshot_profile, cmdline=None, kernel=None):
""" Return disk parameter structure. """
disk_params = {}
if cmdline:
disk_params['cmdline'] = cmdline
if kernel:
disk_params['kernel'] = kernel
if name:
disk_params['name'] = name
if snapshot_profile is not None:
disk_params['snapshot_profile'] = snapshot_profile
if size:
disk_params['size'] = size
return disk_params | [
"def",
"disk_param",
"(",
"name",
",",
"size",
",",
"snapshot_profile",
",",
"cmdline",
"=",
"None",
",",
"kernel",
"=",
"None",
")",
":",
"disk_params",
"=",
"{",
"}",
"if",
"cmdline",
":",
"disk_params",
"[",
"'cmdline'",
"]",
"=",
"cmdline",
"if",
"kernel",
":",
"disk_params",
"[",
"'kernel'",
"]",
"=",
"kernel",
"if",
"name",
":",
"disk_params",
"[",
"'name'",
"]",
"=",
"name",
"if",
"snapshot_profile",
"is",
"not",
"None",
":",
"disk_params",
"[",
"'snapshot_profile'",
"]",
"=",
"snapshot_profile",
"if",
"size",
":",
"disk_params",
"[",
"'size'",
"]",
"=",
"size",
"return",
"disk_params"
] | Return disk parameter structure. | [
"Return",
"disk",
"parameter",
"structure",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/disk.py#L88-L107 | train |
Gandi/gandi.cli | gandi/cli/modules/disk.py | Disk.update | def update(cls, resource, name, size, snapshot_profile,
background, cmdline=None, kernel=None):
""" Update this disk. """
if isinstance(size, tuple):
prefix, size = size
if prefix == '+':
disk_info = cls.info(resource)
current_size = disk_info['size']
size = current_size + size
disk_params = cls.disk_param(name, size, snapshot_profile,
cmdline, kernel)
result = cls.call('hosting.disk.update',
cls.usable_id(resource),
disk_params)
if background:
return result
# interactive mode, run a progress bar
cls.echo('Updating your disk.')
cls.display_progress(result) | python | def update(cls, resource, name, size, snapshot_profile,
background, cmdline=None, kernel=None):
""" Update this disk. """
if isinstance(size, tuple):
prefix, size = size
if prefix == '+':
disk_info = cls.info(resource)
current_size = disk_info['size']
size = current_size + size
disk_params = cls.disk_param(name, size, snapshot_profile,
cmdline, kernel)
result = cls.call('hosting.disk.update',
cls.usable_id(resource),
disk_params)
if background:
return result
# interactive mode, run a progress bar
cls.echo('Updating your disk.')
cls.display_progress(result) | [
"def",
"update",
"(",
"cls",
",",
"resource",
",",
"name",
",",
"size",
",",
"snapshot_profile",
",",
"background",
",",
"cmdline",
"=",
"None",
",",
"kernel",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"size",
",",
"tuple",
")",
":",
"prefix",
",",
"size",
"=",
"size",
"if",
"prefix",
"==",
"'+'",
":",
"disk_info",
"=",
"cls",
".",
"info",
"(",
"resource",
")",
"current_size",
"=",
"disk_info",
"[",
"'size'",
"]",
"size",
"=",
"current_size",
"+",
"size",
"disk_params",
"=",
"cls",
".",
"disk_param",
"(",
"name",
",",
"size",
",",
"snapshot_profile",
",",
"cmdline",
",",
"kernel",
")",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.disk.update'",
",",
"cls",
".",
"usable_id",
"(",
"resource",
")",
",",
"disk_params",
")",
"if",
"background",
":",
"return",
"result",
"# interactive mode, run a progress bar",
"cls",
".",
"echo",
"(",
"'Updating your disk.'",
")",
"cls",
".",
"display_progress",
"(",
"result",
")"
] | Update this disk. | [
"Update",
"this",
"disk",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/disk.py#L110-L131 | train |
Gandi/gandi.cli | gandi/cli/modules/disk.py | Disk._detach | def _detach(cls, disk_id):
""" Detach a disk from a vm. """
disk = cls._info(disk_id)
opers = []
if disk.get('vms_id'):
for vm_id in disk['vms_id']:
cls.echo('The disk is still attached to the vm %s.' % vm_id)
cls.echo('Will detach it.')
opers.append(cls.call('hosting.vm.disk_detach',
vm_id, disk_id))
return opers | python | def _detach(cls, disk_id):
""" Detach a disk from a vm. """
disk = cls._info(disk_id)
opers = []
if disk.get('vms_id'):
for vm_id in disk['vms_id']:
cls.echo('The disk is still attached to the vm %s.' % vm_id)
cls.echo('Will detach it.')
opers.append(cls.call('hosting.vm.disk_detach',
vm_id, disk_id))
return opers | [
"def",
"_detach",
"(",
"cls",
",",
"disk_id",
")",
":",
"disk",
"=",
"cls",
".",
"_info",
"(",
"disk_id",
")",
"opers",
"=",
"[",
"]",
"if",
"disk",
".",
"get",
"(",
"'vms_id'",
")",
":",
"for",
"vm_id",
"in",
"disk",
"[",
"'vms_id'",
"]",
":",
"cls",
".",
"echo",
"(",
"'The disk is still attached to the vm %s.'",
"%",
"vm_id",
")",
"cls",
".",
"echo",
"(",
"'Will detach it.'",
")",
"opers",
".",
"append",
"(",
"cls",
".",
"call",
"(",
"'hosting.vm.disk_detach'",
",",
"vm_id",
",",
"disk_id",
")",
")",
"return",
"opers"
] | Detach a disk from a vm. | [
"Detach",
"a",
"disk",
"from",
"a",
"vm",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/disk.py#L134-L144 | train |
Gandi/gandi.cli | gandi/cli/modules/disk.py | Disk.delete | def delete(cls, resources, background=False):
""" Delete this disk."""
if not isinstance(resources, (list, tuple)):
resources = [resources]
resources = [cls.usable_id(item) for item in resources]
opers = []
for disk_id in resources:
opers.extend(cls._detach(disk_id))
if opers:
cls.echo('Detaching your disk(s).')
cls.display_progress(opers)
opers = []
for disk_id in resources:
oper = cls.call('hosting.disk.delete', disk_id)
opers.append(oper)
if background:
return opers
cls.echo('Deleting your disk.')
cls.display_progress(opers)
return opers | python | def delete(cls, resources, background=False):
""" Delete this disk."""
if not isinstance(resources, (list, tuple)):
resources = [resources]
resources = [cls.usable_id(item) for item in resources]
opers = []
for disk_id in resources:
opers.extend(cls._detach(disk_id))
if opers:
cls.echo('Detaching your disk(s).')
cls.display_progress(opers)
opers = []
for disk_id in resources:
oper = cls.call('hosting.disk.delete', disk_id)
opers.append(oper)
if background:
return opers
cls.echo('Deleting your disk.')
cls.display_progress(opers)
return opers | [
"def",
"delete",
"(",
"cls",
",",
"resources",
",",
"background",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"resources",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"resources",
"=",
"[",
"resources",
"]",
"resources",
"=",
"[",
"cls",
".",
"usable_id",
"(",
"item",
")",
"for",
"item",
"in",
"resources",
"]",
"opers",
"=",
"[",
"]",
"for",
"disk_id",
"in",
"resources",
":",
"opers",
".",
"extend",
"(",
"cls",
".",
"_detach",
"(",
"disk_id",
")",
")",
"if",
"opers",
":",
"cls",
".",
"echo",
"(",
"'Detaching your disk(s).'",
")",
"cls",
".",
"display_progress",
"(",
"opers",
")",
"opers",
"=",
"[",
"]",
"for",
"disk_id",
"in",
"resources",
":",
"oper",
"=",
"cls",
".",
"call",
"(",
"'hosting.disk.delete'",
",",
"disk_id",
")",
"opers",
".",
"append",
"(",
"oper",
")",
"if",
"background",
":",
"return",
"opers",
"cls",
".",
"echo",
"(",
"'Deleting your disk.'",
")",
"cls",
".",
"display_progress",
"(",
"opers",
")",
"return",
"opers"
] | Delete this disk. | [
"Delete",
"this",
"disk",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/disk.py#L164-L190 | train |
Gandi/gandi.cli | gandi/cli/modules/disk.py | Disk._attach | def _attach(cls, disk_id, vm_id, options=None):
""" Attach a disk to a vm. """
options = options or {}
oper = cls.call('hosting.vm.disk_attach', vm_id, disk_id, options)
return oper | python | def _attach(cls, disk_id, vm_id, options=None):
""" Attach a disk to a vm. """
options = options or {}
oper = cls.call('hosting.vm.disk_attach', vm_id, disk_id, options)
return oper | [
"def",
"_attach",
"(",
"cls",
",",
"disk_id",
",",
"vm_id",
",",
"options",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"oper",
"=",
"cls",
".",
"call",
"(",
"'hosting.vm.disk_attach'",
",",
"vm_id",
",",
"disk_id",
",",
"options",
")",
"return",
"oper"
] | Attach a disk to a vm. | [
"Attach",
"a",
"disk",
"to",
"a",
"vm",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/disk.py#L193-L197 | train |
Gandi/gandi.cli | gandi/cli/modules/disk.py | Disk.create | def create(cls, name, vm, size, snapshotprofile, datacenter,
source, disk_type='data', background=False):
""" Create a disk and attach it to a vm. """
if isinstance(size, tuple):
prefix, size = size
if source:
size = None
disk_params = cls.disk_param(name, size, snapshotprofile)
disk_params['datacenter_id'] = int(Datacenter.usable_id(datacenter))
disk_params['type'] = disk_type
if source:
disk_id = int(Image.usable_id(source,
disk_params['datacenter_id']))
result = cls.call('hosting.disk.create_from', disk_params, disk_id)
else:
result = cls.call('hosting.disk.create', disk_params)
if background and not vm:
return result
# interactive mode, run a progress bar
cls.echo('Creating your disk.')
cls.display_progress(result)
if not vm:
return
vm_id = Iaas.usable_id(vm)
result = cls._attach(result['disk_id'], vm_id)
if background:
return result
cls.echo('Attaching your disk.')
cls.display_progress(result) | python | def create(cls, name, vm, size, snapshotprofile, datacenter,
source, disk_type='data', background=False):
""" Create a disk and attach it to a vm. """
if isinstance(size, tuple):
prefix, size = size
if source:
size = None
disk_params = cls.disk_param(name, size, snapshotprofile)
disk_params['datacenter_id'] = int(Datacenter.usable_id(datacenter))
disk_params['type'] = disk_type
if source:
disk_id = int(Image.usable_id(source,
disk_params['datacenter_id']))
result = cls.call('hosting.disk.create_from', disk_params, disk_id)
else:
result = cls.call('hosting.disk.create', disk_params)
if background and not vm:
return result
# interactive mode, run a progress bar
cls.echo('Creating your disk.')
cls.display_progress(result)
if not vm:
return
vm_id = Iaas.usable_id(vm)
result = cls._attach(result['disk_id'], vm_id)
if background:
return result
cls.echo('Attaching your disk.')
cls.display_progress(result) | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"vm",
",",
"size",
",",
"snapshotprofile",
",",
"datacenter",
",",
"source",
",",
"disk_type",
"=",
"'data'",
",",
"background",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"size",
",",
"tuple",
")",
":",
"prefix",
",",
"size",
"=",
"size",
"if",
"source",
":",
"size",
"=",
"None",
"disk_params",
"=",
"cls",
".",
"disk_param",
"(",
"name",
",",
"size",
",",
"snapshotprofile",
")",
"disk_params",
"[",
"'datacenter_id'",
"]",
"=",
"int",
"(",
"Datacenter",
".",
"usable_id",
"(",
"datacenter",
")",
")",
"disk_params",
"[",
"'type'",
"]",
"=",
"disk_type",
"if",
"source",
":",
"disk_id",
"=",
"int",
"(",
"Image",
".",
"usable_id",
"(",
"source",
",",
"disk_params",
"[",
"'datacenter_id'",
"]",
")",
")",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.disk.create_from'",
",",
"disk_params",
",",
"disk_id",
")",
"else",
":",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.disk.create'",
",",
"disk_params",
")",
"if",
"background",
"and",
"not",
"vm",
":",
"return",
"result",
"# interactive mode, run a progress bar",
"cls",
".",
"echo",
"(",
"'Creating your disk.'",
")",
"cls",
".",
"display_progress",
"(",
"result",
")",
"if",
"not",
"vm",
":",
"return",
"vm_id",
"=",
"Iaas",
".",
"usable_id",
"(",
"vm",
")",
"result",
"=",
"cls",
".",
"_attach",
"(",
"result",
"[",
"'disk_id'",
"]",
",",
"vm_id",
")",
"if",
"background",
":",
"return",
"result",
"cls",
".",
"echo",
"(",
"'Attaching your disk.'",
")",
"cls",
".",
"display_progress",
"(",
"result",
")"
] | Create a disk and attach it to a vm. | [
"Create",
"a",
"disk",
"and",
"attach",
"it",
"to",
"a",
"vm",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/disk.py#L236-L272 | train |
Gandi/gandi.cli | gandi/cli/core/cli.py | compatcallback | def compatcallback(f):
""" Compatibility callback decorator for older click version.
Click 1.0 does not have a version string stored, so we need to
use getattr here to be safe.
"""
if getattr(click, '__version__', '0.0') >= '2.0':
return f
return update_wrapper(lambda ctx, value: f(ctx, None, value), f) | python | def compatcallback(f):
""" Compatibility callback decorator for older click version.
Click 1.0 does not have a version string stored, so we need to
use getattr here to be safe.
"""
if getattr(click, '__version__', '0.0') >= '2.0':
return f
return update_wrapper(lambda ctx, value: f(ctx, None, value), f) | [
"def",
"compatcallback",
"(",
"f",
")",
":",
"if",
"getattr",
"(",
"click",
",",
"'__version__'",
",",
"'0.0'",
")",
">=",
"'2.0'",
":",
"return",
"f",
"return",
"update_wrapper",
"(",
"lambda",
"ctx",
",",
"value",
":",
"f",
"(",
"ctx",
",",
"None",
",",
"value",
")",
",",
"f",
")"
] | Compatibility callback decorator for older click version.
Click 1.0 does not have a version string stored, so we need to
use getattr here to be safe. | [
"Compatibility",
"callback",
"decorator",
"for",
"older",
"click",
"version",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/cli.py#L40-L48 | train |
Gandi/gandi.cli | gandi/cli/core/cli.py | GandiCLI.list_sub_commmands | def list_sub_commmands(self, cmd_name, cmd):
"""Return all commands for a group"""
ret = {}
if isinstance(cmd, click.core.Group):
for sub_cmd_name in cmd.commands:
sub_cmd = cmd.commands[sub_cmd_name]
sub = self.list_sub_commmands(sub_cmd_name, sub_cmd)
if sub:
if isinstance(sub, dict):
for n, c in sub.items():
ret['%s %s' % (cmd_name, n)] = c
else:
ret['%s %s' % (cmd_name, sub[0])] = sub[1]
elif isinstance(cmd, click.core.Command):
return (cmd.name, cmd)
return ret | python | def list_sub_commmands(self, cmd_name, cmd):
"""Return all commands for a group"""
ret = {}
if isinstance(cmd, click.core.Group):
for sub_cmd_name in cmd.commands:
sub_cmd = cmd.commands[sub_cmd_name]
sub = self.list_sub_commmands(sub_cmd_name, sub_cmd)
if sub:
if isinstance(sub, dict):
for n, c in sub.items():
ret['%s %s' % (cmd_name, n)] = c
else:
ret['%s %s' % (cmd_name, sub[0])] = sub[1]
elif isinstance(cmd, click.core.Command):
return (cmd.name, cmd)
return ret | [
"def",
"list_sub_commmands",
"(",
"self",
",",
"cmd_name",
",",
"cmd",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"cmd",
",",
"click",
".",
"core",
".",
"Group",
")",
":",
"for",
"sub_cmd_name",
"in",
"cmd",
".",
"commands",
":",
"sub_cmd",
"=",
"cmd",
".",
"commands",
"[",
"sub_cmd_name",
"]",
"sub",
"=",
"self",
".",
"list_sub_commmands",
"(",
"sub_cmd_name",
",",
"sub_cmd",
")",
"if",
"sub",
":",
"if",
"isinstance",
"(",
"sub",
",",
"dict",
")",
":",
"for",
"n",
",",
"c",
"in",
"sub",
".",
"items",
"(",
")",
":",
"ret",
"[",
"'%s %s'",
"%",
"(",
"cmd_name",
",",
"n",
")",
"]",
"=",
"c",
"else",
":",
"ret",
"[",
"'%s %s'",
"%",
"(",
"cmd_name",
",",
"sub",
"[",
"0",
"]",
")",
"]",
"=",
"sub",
"[",
"1",
"]",
"elif",
"isinstance",
"(",
"cmd",
",",
"click",
".",
"core",
".",
"Command",
")",
":",
"return",
"(",
"cmd",
".",
"name",
",",
"cmd",
")",
"return",
"ret"
] | Return all commands for a group | [
"Return",
"all",
"commands",
"for",
"a",
"group"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/cli.py#L109-L124 | train |
Gandi/gandi.cli | gandi/cli/core/cli.py | GandiCLI.load_commands | def load_commands(self):
""" Load cli commands from submodules. """
command_folder = os.path.join(os.path.dirname(__file__),
'..', 'commands')
command_dirs = {
'gandi.cli': command_folder
}
if 'GANDICLI_PATH' in os.environ:
for _path in os.environ.get('GANDICLI_PATH').split(':'):
# remove trailing separator if any
path = _path.rstrip(os.sep)
command_dirs[os.path.basename(path)] = os.path.join(path,
'commands')
for module_basename, dir in list(command_dirs.items()):
for filename in sorted(os.listdir(dir)):
if filename.endswith('.py') and '__init__' not in filename:
submod = filename[:-3]
module_name = module_basename + '.commands.' + submod
__import__(module_name, fromlist=[module_name]) | python | def load_commands(self):
""" Load cli commands from submodules. """
command_folder = os.path.join(os.path.dirname(__file__),
'..', 'commands')
command_dirs = {
'gandi.cli': command_folder
}
if 'GANDICLI_PATH' in os.environ:
for _path in os.environ.get('GANDICLI_PATH').split(':'):
# remove trailing separator if any
path = _path.rstrip(os.sep)
command_dirs[os.path.basename(path)] = os.path.join(path,
'commands')
for module_basename, dir in list(command_dirs.items()):
for filename in sorted(os.listdir(dir)):
if filename.endswith('.py') and '__init__' not in filename:
submod = filename[:-3]
module_name = module_basename + '.commands.' + submod
__import__(module_name, fromlist=[module_name]) | [
"def",
"load_commands",
"(",
"self",
")",
":",
"command_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'..'",
",",
"'commands'",
")",
"command_dirs",
"=",
"{",
"'gandi.cli'",
":",
"command_folder",
"}",
"if",
"'GANDICLI_PATH'",
"in",
"os",
".",
"environ",
":",
"for",
"_path",
"in",
"os",
".",
"environ",
".",
"get",
"(",
"'GANDICLI_PATH'",
")",
".",
"split",
"(",
"':'",
")",
":",
"# remove trailing separator if any",
"path",
"=",
"_path",
".",
"rstrip",
"(",
"os",
".",
"sep",
")",
"command_dirs",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'commands'",
")",
"for",
"module_basename",
",",
"dir",
"in",
"list",
"(",
"command_dirs",
".",
"items",
"(",
")",
")",
":",
"for",
"filename",
"in",
"sorted",
"(",
"os",
".",
"listdir",
"(",
"dir",
")",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.py'",
")",
"and",
"'__init__'",
"not",
"in",
"filename",
":",
"submod",
"=",
"filename",
"[",
":",
"-",
"3",
"]",
"module_name",
"=",
"module_basename",
"+",
"'.commands.'",
"+",
"submod",
"__import__",
"(",
"module_name",
",",
"fromlist",
"=",
"[",
"module_name",
"]",
")"
] | Load cli commands from submodules. | [
"Load",
"cli",
"commands",
"from",
"submodules",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/cli.py#L138-L158 | train |
Gandi/gandi.cli | gandi/cli/core/cli.py | GandiCLI.invoke | def invoke(self, ctx):
""" Invoke command in context. """
ctx.obj = GandiContextHelper(verbose=ctx.obj['verbose'])
click.Group.invoke(self, ctx) | python | def invoke(self, ctx):
""" Invoke command in context. """
ctx.obj = GandiContextHelper(verbose=ctx.obj['verbose'])
click.Group.invoke(self, ctx) | [
"def",
"invoke",
"(",
"self",
",",
"ctx",
")",
":",
"ctx",
".",
"obj",
"=",
"GandiContextHelper",
"(",
"verbose",
"=",
"ctx",
".",
"obj",
"[",
"'verbose'",
"]",
")",
"click",
".",
"Group",
".",
"invoke",
"(",
"self",
",",
"ctx",
")"
] | Invoke command in context. | [
"Invoke",
"command",
"in",
"context",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/cli.py#L160-L163 | train |
Gandi/gandi.cli | gandi/cli/modules/sshkey.py | Sshkey.from_name | def from_name(cls, name):
"""Retrieve a sshkey id associated to a name."""
sshkeys = cls.list({'name': name})
if len(sshkeys) == 1:
return sshkeys[0]['id']
elif not sshkeys:
return
raise DuplicateResults('sshkey name %s is ambiguous.' % name) | python | def from_name(cls, name):
"""Retrieve a sshkey id associated to a name."""
sshkeys = cls.list({'name': name})
if len(sshkeys) == 1:
return sshkeys[0]['id']
elif not sshkeys:
return
raise DuplicateResults('sshkey name %s is ambiguous.' % name) | [
"def",
"from_name",
"(",
"cls",
",",
"name",
")",
":",
"sshkeys",
"=",
"cls",
".",
"list",
"(",
"{",
"'name'",
":",
"name",
"}",
")",
"if",
"len",
"(",
"sshkeys",
")",
"==",
"1",
":",
"return",
"sshkeys",
"[",
"0",
"]",
"[",
"'id'",
"]",
"elif",
"not",
"sshkeys",
":",
"return",
"raise",
"DuplicateResults",
"(",
"'sshkey name %s is ambiguous.'",
"%",
"name",
")"
] | Retrieve a sshkey id associated to a name. | [
"Retrieve",
"a",
"sshkey",
"id",
"associated",
"to",
"a",
"name",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/sshkey.py#L20-L28 | train |
Gandi/gandi.cli | gandi/cli/modules/sshkey.py | Sshkey.usable_id | def usable_id(cls, id):
""" Retrieve id from input which can be name or id."""
try:
# id is maybe a sshkey name
qry_id = cls.from_name(id)
if not qry_id:
qry_id = int(id)
except DuplicateResults as exc:
cls.error(exc.errors)
except Exception:
qry_id = None
if not qry_id:
msg = 'unknown identifier %s' % id
cls.error(msg)
return qry_id | python | def usable_id(cls, id):
""" Retrieve id from input which can be name or id."""
try:
# id is maybe a sshkey name
qry_id = cls.from_name(id)
if not qry_id:
qry_id = int(id)
except DuplicateResults as exc:
cls.error(exc.errors)
except Exception:
qry_id = None
if not qry_id:
msg = 'unknown identifier %s' % id
cls.error(msg)
return qry_id | [
"def",
"usable_id",
"(",
"cls",
",",
"id",
")",
":",
"try",
":",
"# id is maybe a sshkey name",
"qry_id",
"=",
"cls",
".",
"from_name",
"(",
"id",
")",
"if",
"not",
"qry_id",
":",
"qry_id",
"=",
"int",
"(",
"id",
")",
"except",
"DuplicateResults",
"as",
"exc",
":",
"cls",
".",
"error",
"(",
"exc",
".",
"errors",
")",
"except",
"Exception",
":",
"qry_id",
"=",
"None",
"if",
"not",
"qry_id",
":",
"msg",
"=",
"'unknown identifier %s'",
"%",
"id",
"cls",
".",
"error",
"(",
"msg",
")",
"return",
"qry_id"
] | Retrieve id from input which can be name or id. | [
"Retrieve",
"id",
"from",
"input",
"which",
"can",
"be",
"name",
"or",
"id",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/sshkey.py#L31-L47 | train |
Gandi/gandi.cli | gandi/cli/modules/sshkey.py | Sshkey.create | def create(cls, name, value):
""" Create a new ssh key."""
sshkey_params = {
'name': name,
'value': value,
}
result = cls.call('hosting.ssh.create', sshkey_params)
return result | python | def create(cls, name, value):
""" Create a new ssh key."""
sshkey_params = {
'name': name,
'value': value,
}
result = cls.call('hosting.ssh.create', sshkey_params)
return result | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"value",
")",
":",
"sshkey_params",
"=",
"{",
"'name'",
":",
"name",
",",
"'value'",
":",
"value",
",",
"}",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.ssh.create'",
",",
"sshkey_params",
")",
"return",
"result"
] | Create a new ssh key. | [
"Create",
"a",
"new",
"ssh",
"key",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/sshkey.py#L61-L69 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.get_api_connector | def get_api_connector(cls):
""" Initialize an api connector for future use."""
if cls._api is None: # pragma: no cover
cls.load_config()
cls.debug('initialize connection to remote server')
apihost = cls.get('api.host')
if not apihost:
raise MissingConfiguration()
apienv = cls.get('api.env')
if apienv and apienv in cls.apienvs:
apihost = cls.apienvs[apienv]
cls._api = XMLRPCClient(host=apihost, debug=cls.verbose)
return cls._api | python | def get_api_connector(cls):
""" Initialize an api connector for future use."""
if cls._api is None: # pragma: no cover
cls.load_config()
cls.debug('initialize connection to remote server')
apihost = cls.get('api.host')
if not apihost:
raise MissingConfiguration()
apienv = cls.get('api.env')
if apienv and apienv in cls.apienvs:
apihost = cls.apienvs[apienv]
cls._api = XMLRPCClient(host=apihost, debug=cls.verbose)
return cls._api | [
"def",
"get_api_connector",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_api",
"is",
"None",
":",
"# pragma: no cover",
"cls",
".",
"load_config",
"(",
")",
"cls",
".",
"debug",
"(",
"'initialize connection to remote server'",
")",
"apihost",
"=",
"cls",
".",
"get",
"(",
"'api.host'",
")",
"if",
"not",
"apihost",
":",
"raise",
"MissingConfiguration",
"(",
")",
"apienv",
"=",
"cls",
".",
"get",
"(",
"'api.env'",
")",
"if",
"apienv",
"and",
"apienv",
"in",
"cls",
".",
"apienvs",
":",
"apihost",
"=",
"cls",
".",
"apienvs",
"[",
"apienv",
"]",
"cls",
".",
"_api",
"=",
"XMLRPCClient",
"(",
"host",
"=",
"apihost",
",",
"debug",
"=",
"cls",
".",
"verbose",
")",
"return",
"cls",
".",
"_api"
] | Initialize an api connector for future use. | [
"Initialize",
"an",
"api",
"connector",
"for",
"future",
"use",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L45-L60 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.call | def call(cls, method, *args, **kwargs):
""" Call a remote api method and return the result."""
api = None
empty_key = kwargs.pop('empty_key', False)
try:
api = cls.get_api_connector()
apikey = cls.get('api.key')
if not apikey and not empty_key:
cls.echo("No apikey found, please use 'gandi setup' "
"command")
sys.exit(1)
except MissingConfiguration:
if api and empty_key:
apikey = ''
elif not kwargs.get('safe'):
cls.echo("No configuration found, please use 'gandi setup' "
"command")
sys.exit(1)
else:
return []
# make the call
cls.debug('calling method: %s' % method)
for arg in args:
cls.debug('with params: %r' % arg)
try:
resp = api.request(method, apikey, *args,
**{'dry_run': kwargs.get('dry_run', False),
'return_dry_run':
kwargs.get('return_dry_run', False)})
cls.dump('responded: %r' % resp)
return resp
except APICallFailed as err:
if kwargs.get('safe'):
return []
if err.code == 530040:
cls.echo("Error: It appears you haven't purchased any credits "
"yet.\n"
"Please visit https://www.gandi.net/credit/buy to "
"learn more and buy credits.")
sys.exit(1)
if err.code == 510150:
cls.echo("Invalid API key, please use 'gandi setup' command.")
sys.exit(1)
if isinstance(err, DryRunException):
if kwargs.get('return_dry_run', False):
return err.dry_run
else:
for msg in err.dry_run:
# TODO use trads with %s
cls.echo(msg['reason'])
cls.echo('\t' + ' '.join(msg['attr']))
sys.exit(1)
error = UsageError(err.errors)
setattr(error, 'code', err.code)
raise error | python | def call(cls, method, *args, **kwargs):
""" Call a remote api method and return the result."""
api = None
empty_key = kwargs.pop('empty_key', False)
try:
api = cls.get_api_connector()
apikey = cls.get('api.key')
if not apikey and not empty_key:
cls.echo("No apikey found, please use 'gandi setup' "
"command")
sys.exit(1)
except MissingConfiguration:
if api and empty_key:
apikey = ''
elif not kwargs.get('safe'):
cls.echo("No configuration found, please use 'gandi setup' "
"command")
sys.exit(1)
else:
return []
# make the call
cls.debug('calling method: %s' % method)
for arg in args:
cls.debug('with params: %r' % arg)
try:
resp = api.request(method, apikey, *args,
**{'dry_run': kwargs.get('dry_run', False),
'return_dry_run':
kwargs.get('return_dry_run', False)})
cls.dump('responded: %r' % resp)
return resp
except APICallFailed as err:
if kwargs.get('safe'):
return []
if err.code == 530040:
cls.echo("Error: It appears you haven't purchased any credits "
"yet.\n"
"Please visit https://www.gandi.net/credit/buy to "
"learn more and buy credits.")
sys.exit(1)
if err.code == 510150:
cls.echo("Invalid API key, please use 'gandi setup' command.")
sys.exit(1)
if isinstance(err, DryRunException):
if kwargs.get('return_dry_run', False):
return err.dry_run
else:
for msg in err.dry_run:
# TODO use trads with %s
cls.echo(msg['reason'])
cls.echo('\t' + ' '.join(msg['attr']))
sys.exit(1)
error = UsageError(err.errors)
setattr(error, 'code', err.code)
raise error | [
"def",
"call",
"(",
"cls",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"api",
"=",
"None",
"empty_key",
"=",
"kwargs",
".",
"pop",
"(",
"'empty_key'",
",",
"False",
")",
"try",
":",
"api",
"=",
"cls",
".",
"get_api_connector",
"(",
")",
"apikey",
"=",
"cls",
".",
"get",
"(",
"'api.key'",
")",
"if",
"not",
"apikey",
"and",
"not",
"empty_key",
":",
"cls",
".",
"echo",
"(",
"\"No apikey found, please use 'gandi setup' \"",
"\"command\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"except",
"MissingConfiguration",
":",
"if",
"api",
"and",
"empty_key",
":",
"apikey",
"=",
"''",
"elif",
"not",
"kwargs",
".",
"get",
"(",
"'safe'",
")",
":",
"cls",
".",
"echo",
"(",
"\"No configuration found, please use 'gandi setup' \"",
"\"command\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"else",
":",
"return",
"[",
"]",
"# make the call",
"cls",
".",
"debug",
"(",
"'calling method: %s'",
"%",
"method",
")",
"for",
"arg",
"in",
"args",
":",
"cls",
".",
"debug",
"(",
"'with params: %r'",
"%",
"arg",
")",
"try",
":",
"resp",
"=",
"api",
".",
"request",
"(",
"method",
",",
"apikey",
",",
"*",
"args",
",",
"*",
"*",
"{",
"'dry_run'",
":",
"kwargs",
".",
"get",
"(",
"'dry_run'",
",",
"False",
")",
",",
"'return_dry_run'",
":",
"kwargs",
".",
"get",
"(",
"'return_dry_run'",
",",
"False",
")",
"}",
")",
"cls",
".",
"dump",
"(",
"'responded: %r'",
"%",
"resp",
")",
"return",
"resp",
"except",
"APICallFailed",
"as",
"err",
":",
"if",
"kwargs",
".",
"get",
"(",
"'safe'",
")",
":",
"return",
"[",
"]",
"if",
"err",
".",
"code",
"==",
"530040",
":",
"cls",
".",
"echo",
"(",
"\"Error: It appears you haven't purchased any credits \"",
"\"yet.\\n\"",
"\"Please visit https://www.gandi.net/credit/buy to \"",
"\"learn more and buy credits.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"err",
".",
"code",
"==",
"510150",
":",
"cls",
".",
"echo",
"(",
"\"Invalid API key, please use 'gandi setup' command.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"isinstance",
"(",
"err",
",",
"DryRunException",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'return_dry_run'",
",",
"False",
")",
":",
"return",
"err",
".",
"dry_run",
"else",
":",
"for",
"msg",
"in",
"err",
".",
"dry_run",
":",
"# TODO use trads with %s",
"cls",
".",
"echo",
"(",
"msg",
"[",
"'reason'",
"]",
")",
"cls",
".",
"echo",
"(",
"'\\t'",
"+",
"' '",
".",
"join",
"(",
"msg",
"[",
"'attr'",
"]",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"error",
"=",
"UsageError",
"(",
"err",
".",
"errors",
")",
"setattr",
"(",
"error",
",",
"'code'",
",",
"err",
".",
"code",
")",
"raise",
"error"
] | Call a remote api method and return the result. | [
"Call",
"a",
"remote",
"api",
"method",
"and",
"return",
"the",
"result",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L63-L118 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.safe_call | def safe_call(cls, method, *args):
""" Call a remote api method but don't raise if an error occurred."""
return cls.call(method, *args, safe=True) | python | def safe_call(cls, method, *args):
""" Call a remote api method but don't raise if an error occurred."""
return cls.call(method, *args, safe=True) | [
"def",
"safe_call",
"(",
"cls",
",",
"method",
",",
"*",
"args",
")",
":",
"return",
"cls",
".",
"call",
"(",
"method",
",",
"*",
"args",
",",
"safe",
"=",
"True",
")"
] | Call a remote api method but don't raise if an error occurred. | [
"Call",
"a",
"remote",
"api",
"method",
"but",
"don",
"t",
"raise",
"if",
"an",
"error",
"occurred",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L121-L123 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.json_call | def json_call(cls, method, url, **kwargs):
""" Call a remote api using json format """
# retrieve api key if needed
empty_key = kwargs.pop('empty_key', False)
send_key = kwargs.pop('send_key', True)
return_header = kwargs.pop('return_header', False)
try:
apikey = cls.get('apirest.key')
if not apikey and not empty_key:
cls.echo("No apikey found for REST API, please use "
"'gandi setup' command")
sys.exit(1)
if send_key:
if 'headers' in kwargs:
kwargs['headers'].update({'X-Api-Key': apikey})
else:
kwargs['headers'] = {'X-Api-Key': apikey}
except MissingConfiguration:
if not empty_key:
return []
# make the call
cls.debug('calling url: %s %s' % (method, url))
cls.debug('with params: %r' % kwargs)
try:
resp, resp_headers = JsonClient.request(method, url, **kwargs)
cls.dump('responded: %r' % resp)
if return_header:
return resp, resp_headers
return resp
except APICallFailed as err:
cls.echo('An error occured during call: %s' % err.errors)
sys.exit(1) | python | def json_call(cls, method, url, **kwargs):
""" Call a remote api using json format """
# retrieve api key if needed
empty_key = kwargs.pop('empty_key', False)
send_key = kwargs.pop('send_key', True)
return_header = kwargs.pop('return_header', False)
try:
apikey = cls.get('apirest.key')
if not apikey and not empty_key:
cls.echo("No apikey found for REST API, please use "
"'gandi setup' command")
sys.exit(1)
if send_key:
if 'headers' in kwargs:
kwargs['headers'].update({'X-Api-Key': apikey})
else:
kwargs['headers'] = {'X-Api-Key': apikey}
except MissingConfiguration:
if not empty_key:
return []
# make the call
cls.debug('calling url: %s %s' % (method, url))
cls.debug('with params: %r' % kwargs)
try:
resp, resp_headers = JsonClient.request(method, url, **kwargs)
cls.dump('responded: %r' % resp)
if return_header:
return resp, resp_headers
return resp
except APICallFailed as err:
cls.echo('An error occured during call: %s' % err.errors)
sys.exit(1) | [
"def",
"json_call",
"(",
"cls",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"# retrieve api key if needed",
"empty_key",
"=",
"kwargs",
".",
"pop",
"(",
"'empty_key'",
",",
"False",
")",
"send_key",
"=",
"kwargs",
".",
"pop",
"(",
"'send_key'",
",",
"True",
")",
"return_header",
"=",
"kwargs",
".",
"pop",
"(",
"'return_header'",
",",
"False",
")",
"try",
":",
"apikey",
"=",
"cls",
".",
"get",
"(",
"'apirest.key'",
")",
"if",
"not",
"apikey",
"and",
"not",
"empty_key",
":",
"cls",
".",
"echo",
"(",
"\"No apikey found for REST API, please use \"",
"\"'gandi setup' command\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"send_key",
":",
"if",
"'headers'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'headers'",
"]",
".",
"update",
"(",
"{",
"'X-Api-Key'",
":",
"apikey",
"}",
")",
"else",
":",
"kwargs",
"[",
"'headers'",
"]",
"=",
"{",
"'X-Api-Key'",
":",
"apikey",
"}",
"except",
"MissingConfiguration",
":",
"if",
"not",
"empty_key",
":",
"return",
"[",
"]",
"# make the call",
"cls",
".",
"debug",
"(",
"'calling url: %s %s'",
"%",
"(",
"method",
",",
"url",
")",
")",
"cls",
".",
"debug",
"(",
"'with params: %r'",
"%",
"kwargs",
")",
"try",
":",
"resp",
",",
"resp_headers",
"=",
"JsonClient",
".",
"request",
"(",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
"cls",
".",
"dump",
"(",
"'responded: %r'",
"%",
"resp",
")",
"if",
"return_header",
":",
"return",
"resp",
",",
"resp_headers",
"return",
"resp",
"except",
"APICallFailed",
"as",
"err",
":",
"cls",
".",
"echo",
"(",
"'An error occured during call: %s'",
"%",
"err",
".",
"errors",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Call a remote api using json format | [
"Call",
"a",
"remote",
"api",
"using",
"json",
"format"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L126-L157 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.intty | def intty(cls):
""" Check if we are in a tty. """
# XXX: temporary hack until we can detect if we are in a pipe or not
return True
if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
return True
return False | python | def intty(cls):
""" Check if we are in a tty. """
# XXX: temporary hack until we can detect if we are in a pipe or not
return True
if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
return True
return False | [
"def",
"intty",
"(",
"cls",
")",
":",
"# XXX: temporary hack until we can detect if we are in a pipe or not",
"return",
"True",
"if",
"hasattr",
"(",
"sys",
".",
"stdout",
",",
"'isatty'",
")",
"and",
"sys",
".",
"stdout",
".",
"isatty",
"(",
")",
":",
"return",
"True",
"return",
"False"
] | Check if we are in a tty. | [
"Check",
"if",
"we",
"are",
"in",
"a",
"tty",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L180-L188 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.pretty_echo | def pretty_echo(cls, message):
""" Display message using pretty print formatting. """
if cls.intty():
if message:
from pprint import pprint
pprint(message) | python | def pretty_echo(cls, message):
""" Display message using pretty print formatting. """
if cls.intty():
if message:
from pprint import pprint
pprint(message) | [
"def",
"pretty_echo",
"(",
"cls",
",",
"message",
")",
":",
"if",
"cls",
".",
"intty",
"(",
")",
":",
"if",
"message",
":",
"from",
"pprint",
"import",
"pprint",
"pprint",
"(",
"message",
")"
] | Display message using pretty print formatting. | [
"Display",
"message",
"using",
"pretty",
"print",
"formatting",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L198-L203 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.dump | def dump(cls, message):
""" Display dump message if verbose level allows it. """
if cls.verbose > 2:
msg = '[DUMP] %s' % message
cls.echo(msg) | python | def dump(cls, message):
""" Display dump message if verbose level allows it. """
if cls.verbose > 2:
msg = '[DUMP] %s' % message
cls.echo(msg) | [
"def",
"dump",
"(",
"cls",
",",
"message",
")",
":",
"if",
"cls",
".",
"verbose",
">",
"2",
":",
"msg",
"=",
"'[DUMP] %s'",
"%",
"message",
"cls",
".",
"echo",
"(",
"msg",
")"
] | Display dump message if verbose level allows it. | [
"Display",
"dump",
"message",
"if",
"verbose",
"level",
"allows",
"it",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L218-L222 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.debug | def debug(cls, message):
""" Display debug message if verbose level allows it. """
if cls.verbose > 1:
msg = '[DEBUG] %s' % message
cls.echo(msg) | python | def debug(cls, message):
""" Display debug message if verbose level allows it. """
if cls.verbose > 1:
msg = '[DEBUG] %s' % message
cls.echo(msg) | [
"def",
"debug",
"(",
"cls",
",",
"message",
")",
":",
"if",
"cls",
".",
"verbose",
">",
"1",
":",
"msg",
"=",
"'[DEBUG] %s'",
"%",
"message",
"cls",
".",
"echo",
"(",
"msg",
")"
] | Display debug message if verbose level allows it. | [
"Display",
"debug",
"message",
"if",
"verbose",
"level",
"allows",
"it",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L225-L229 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.log | def log(cls, message):
""" Display info message if verbose level allows it. """
if cls.verbose > 0:
msg = '[INFO] %s' % message
cls.echo(msg) | python | def log(cls, message):
""" Display info message if verbose level allows it. """
if cls.verbose > 0:
msg = '[INFO] %s' % message
cls.echo(msg) | [
"def",
"log",
"(",
"cls",
",",
"message",
")",
":",
"if",
"cls",
".",
"verbose",
">",
"0",
":",
"msg",
"=",
"'[INFO] %s'",
"%",
"message",
"cls",
".",
"echo",
"(",
"msg",
")"
] | Display info message if verbose level allows it. | [
"Display",
"info",
"message",
"if",
"verbose",
"level",
"allows",
"it",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L232-L236 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.exec_output | def exec_output(cls, command, shell=True, encoding='utf-8'):
""" Return execution output
:param encoding: charset used to decode the stdout
:type encoding: str
:return: the return of the command
:rtype: unicode string
"""
proc = Popen(command, shell=shell, stdout=PIPE)
stdout, _stderr = proc.communicate()
if proc.returncode == 0:
return stdout.decode(encoding)
return '' | python | def exec_output(cls, command, shell=True, encoding='utf-8'):
""" Return execution output
:param encoding: charset used to decode the stdout
:type encoding: str
:return: the return of the command
:rtype: unicode string
"""
proc = Popen(command, shell=shell, stdout=PIPE)
stdout, _stderr = proc.communicate()
if proc.returncode == 0:
return stdout.decode(encoding)
return '' | [
"def",
"exec_output",
"(",
"cls",
",",
"command",
",",
"shell",
"=",
"True",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"proc",
"=",
"Popen",
"(",
"command",
",",
"shell",
"=",
"shell",
",",
"stdout",
"=",
"PIPE",
")",
"stdout",
",",
"_stderr",
"=",
"proc",
".",
"communicate",
"(",
")",
"if",
"proc",
".",
"returncode",
"==",
"0",
":",
"return",
"stdout",
".",
"decode",
"(",
"encoding",
")",
"return",
"''"
] | Return execution output
:param encoding: charset used to decode the stdout
:type encoding: str
:return: the return of the command
:rtype: unicode string | [
"Return",
"execution",
"output"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L258-L272 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.update_progress | def update_progress(cls, progress, starttime):
""" Display an ascii progress bar while processing operation. """
width, _height = click.get_terminal_size()
if not width:
return
duration = datetime.utcnow() - starttime
hours, remainder = divmod(duration.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
size = int(width * .6)
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = 'error: progress var must be float\n'
cls.echo(type(progress))
if progress < 0:
progress = 0
status = 'Halt...\n'
if progress >= 1:
progress = 1
# status = 'Done...\n'
block = int(round(size * progress))
text = ('\rProgress: [{0}] {1:.2%} {2} {3:0>2}:{4:0>2}:{5:0>2} '
''.format('#' * block + '-' * (size - block), progress,
status, hours, minutes, seconds))
sys.stdout.write(text)
sys.stdout.flush() | python | def update_progress(cls, progress, starttime):
""" Display an ascii progress bar while processing operation. """
width, _height = click.get_terminal_size()
if not width:
return
duration = datetime.utcnow() - starttime
hours, remainder = divmod(duration.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
size = int(width * .6)
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = 'error: progress var must be float\n'
cls.echo(type(progress))
if progress < 0:
progress = 0
status = 'Halt...\n'
if progress >= 1:
progress = 1
# status = 'Done...\n'
block = int(round(size * progress))
text = ('\rProgress: [{0}] {1:.2%} {2} {3:0>2}:{4:0>2}:{5:0>2} '
''.format('#' * block + '-' * (size - block), progress,
status, hours, minutes, seconds))
sys.stdout.write(text)
sys.stdout.flush() | [
"def",
"update_progress",
"(",
"cls",
",",
"progress",
",",
"starttime",
")",
":",
"width",
",",
"_height",
"=",
"click",
".",
"get_terminal_size",
"(",
")",
"if",
"not",
"width",
":",
"return",
"duration",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"-",
"starttime",
"hours",
",",
"remainder",
"=",
"divmod",
"(",
"duration",
".",
"seconds",
",",
"3600",
")",
"minutes",
",",
"seconds",
"=",
"divmod",
"(",
"remainder",
",",
"60",
")",
"size",
"=",
"int",
"(",
"width",
"*",
".6",
")",
"status",
"=",
"\"\"",
"if",
"isinstance",
"(",
"progress",
",",
"int",
")",
":",
"progress",
"=",
"float",
"(",
"progress",
")",
"if",
"not",
"isinstance",
"(",
"progress",
",",
"float",
")",
":",
"progress",
"=",
"0",
"status",
"=",
"'error: progress var must be float\\n'",
"cls",
".",
"echo",
"(",
"type",
"(",
"progress",
")",
")",
"if",
"progress",
"<",
"0",
":",
"progress",
"=",
"0",
"status",
"=",
"'Halt...\\n'",
"if",
"progress",
">=",
"1",
":",
"progress",
"=",
"1",
"# status = 'Done...\\n'",
"block",
"=",
"int",
"(",
"round",
"(",
"size",
"*",
"progress",
")",
")",
"text",
"=",
"(",
"'\\rProgress: [{0}] {1:.2%} {2} {3:0>2}:{4:0>2}:{5:0>2} '",
"''",
".",
"format",
"(",
"'#'",
"*",
"block",
"+",
"'-'",
"*",
"(",
"size",
"-",
"block",
")",
",",
"progress",
",",
"status",
",",
"hours",
",",
"minutes",
",",
"seconds",
")",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"text",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] | Display an ascii progress bar while processing operation. | [
"Display",
"an",
"ascii",
"progress",
"bar",
"while",
"processing",
"operation",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L275-L304 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiModule.display_progress | def display_progress(cls, operations):
""" Display progress of Gandi operations.
polls API every 1 seconds to retrieve status.
"""
start_crea = datetime.utcnow()
# count number of operations, 3 steps per operation
if not isinstance(operations, (list, tuple)):
operations = [operations]
count_operations = len(operations) * 3
updating_done = False
while not updating_done:
op_score = 0
for oper in operations:
op_ret = cls.call('operation.info', oper['id'])
op_step = op_ret['step']
if op_step in cls._op_scores:
op_score += cls._op_scores[op_step]
else:
cls.echo('')
msg = 'step %s unknown, exiting' % op_step
if op_step == 'ERROR':
msg = ('An error has occured during operation '
'processing: %s' % op_ret['last_error'])
elif op_step == 'SUPPORT':
msg = ('An error has occured during operation '
'processing, you must contact Gandi support.')
cls.echo(msg)
sys.exit(1)
cls.update_progress(float(op_score) / count_operations,
start_crea)
if op_score == count_operations:
updating_done = True
time.sleep(cls._poll_freq)
cls.echo('\r') | python | def display_progress(cls, operations):
""" Display progress of Gandi operations.
polls API every 1 seconds to retrieve status.
"""
start_crea = datetime.utcnow()
# count number of operations, 3 steps per operation
if not isinstance(operations, (list, tuple)):
operations = [operations]
count_operations = len(operations) * 3
updating_done = False
while not updating_done:
op_score = 0
for oper in operations:
op_ret = cls.call('operation.info', oper['id'])
op_step = op_ret['step']
if op_step in cls._op_scores:
op_score += cls._op_scores[op_step]
else:
cls.echo('')
msg = 'step %s unknown, exiting' % op_step
if op_step == 'ERROR':
msg = ('An error has occured during operation '
'processing: %s' % op_ret['last_error'])
elif op_step == 'SUPPORT':
msg = ('An error has occured during operation '
'processing, you must contact Gandi support.')
cls.echo(msg)
sys.exit(1)
cls.update_progress(float(op_score) / count_operations,
start_crea)
if op_score == count_operations:
updating_done = True
time.sleep(cls._poll_freq)
cls.echo('\r') | [
"def",
"display_progress",
"(",
"cls",
",",
"operations",
")",
":",
"start_crea",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"# count number of operations, 3 steps per operation",
"if",
"not",
"isinstance",
"(",
"operations",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"operations",
"=",
"[",
"operations",
"]",
"count_operations",
"=",
"len",
"(",
"operations",
")",
"*",
"3",
"updating_done",
"=",
"False",
"while",
"not",
"updating_done",
":",
"op_score",
"=",
"0",
"for",
"oper",
"in",
"operations",
":",
"op_ret",
"=",
"cls",
".",
"call",
"(",
"'operation.info'",
",",
"oper",
"[",
"'id'",
"]",
")",
"op_step",
"=",
"op_ret",
"[",
"'step'",
"]",
"if",
"op_step",
"in",
"cls",
".",
"_op_scores",
":",
"op_score",
"+=",
"cls",
".",
"_op_scores",
"[",
"op_step",
"]",
"else",
":",
"cls",
".",
"echo",
"(",
"''",
")",
"msg",
"=",
"'step %s unknown, exiting'",
"%",
"op_step",
"if",
"op_step",
"==",
"'ERROR'",
":",
"msg",
"=",
"(",
"'An error has occured during operation '",
"'processing: %s'",
"%",
"op_ret",
"[",
"'last_error'",
"]",
")",
"elif",
"op_step",
"==",
"'SUPPORT'",
":",
"msg",
"=",
"(",
"'An error has occured during operation '",
"'processing, you must contact Gandi support.'",
")",
"cls",
".",
"echo",
"(",
"msg",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"cls",
".",
"update_progress",
"(",
"float",
"(",
"op_score",
")",
"/",
"count_operations",
",",
"start_crea",
")",
"if",
"op_score",
"==",
"count_operations",
":",
"updating_done",
"=",
"True",
"time",
".",
"sleep",
"(",
"cls",
".",
"_poll_freq",
")",
"cls",
".",
"echo",
"(",
"'\\r'",
")"
] | Display progress of Gandi operations.
polls API every 1 seconds to retrieve status. | [
"Display",
"progress",
"of",
"Gandi",
"operations",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L307-L346 | train |
Gandi/gandi.cli | gandi/cli/core/base.py | GandiContextHelper.load_modules | def load_modules(self):
""" Import CLI commands modules. """
module_folder = os.path.join(os.path.dirname(__file__),
'..', 'modules')
module_dirs = {
'gandi.cli': module_folder
}
if 'GANDICLI_PATH' in os.environ:
for _path in os.environ.get('GANDICLI_PATH').split(':'):
# remove trailing separator if any
path = _path.rstrip(os.sep)
module_dirs[os.path.basename(path)] = os.path.join(path,
'modules')
for module_basename, dir in list(module_dirs.items()):
for filename in sorted(os.listdir(dir)):
if filename.endswith('.py') and '__init__' not in filename:
submod = filename[:-3]
module_name = module_basename + '.modules.' + submod
__import__(module_name, fromlist=[module_name])
# save internal map of loaded module classes
for subclass in GandiModule.__subclasses__():
self._modules[subclass.__name__.lower()] = subclass | python | def load_modules(self):
""" Import CLI commands modules. """
module_folder = os.path.join(os.path.dirname(__file__),
'..', 'modules')
module_dirs = {
'gandi.cli': module_folder
}
if 'GANDICLI_PATH' in os.environ:
for _path in os.environ.get('GANDICLI_PATH').split(':'):
# remove trailing separator if any
path = _path.rstrip(os.sep)
module_dirs[os.path.basename(path)] = os.path.join(path,
'modules')
for module_basename, dir in list(module_dirs.items()):
for filename in sorted(os.listdir(dir)):
if filename.endswith('.py') and '__init__' not in filename:
submod = filename[:-3]
module_name = module_basename + '.modules.' + submod
__import__(module_name, fromlist=[module_name])
# save internal map of loaded module classes
for subclass in GandiModule.__subclasses__():
self._modules[subclass.__name__.lower()] = subclass | [
"def",
"load_modules",
"(",
"self",
")",
":",
"module_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'..'",
",",
"'modules'",
")",
"module_dirs",
"=",
"{",
"'gandi.cli'",
":",
"module_folder",
"}",
"if",
"'GANDICLI_PATH'",
"in",
"os",
".",
"environ",
":",
"for",
"_path",
"in",
"os",
".",
"environ",
".",
"get",
"(",
"'GANDICLI_PATH'",
")",
".",
"split",
"(",
"':'",
")",
":",
"# remove trailing separator if any",
"path",
"=",
"_path",
".",
"rstrip",
"(",
"os",
".",
"sep",
")",
"module_dirs",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'modules'",
")",
"for",
"module_basename",
",",
"dir",
"in",
"list",
"(",
"module_dirs",
".",
"items",
"(",
")",
")",
":",
"for",
"filename",
"in",
"sorted",
"(",
"os",
".",
"listdir",
"(",
"dir",
")",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.py'",
")",
"and",
"'__init__'",
"not",
"in",
"filename",
":",
"submod",
"=",
"filename",
"[",
":",
"-",
"3",
"]",
"module_name",
"=",
"module_basename",
"+",
"'.modules.'",
"+",
"submod",
"__import__",
"(",
"module_name",
",",
"fromlist",
"=",
"[",
"module_name",
"]",
")",
"# save internal map of loaded module classes",
"for",
"subclass",
"in",
"GandiModule",
".",
"__subclasses__",
"(",
")",
":",
"self",
".",
"_modules",
"[",
"subclass",
".",
"__name__",
".",
"lower",
"(",
")",
"]",
"=",
"subclass"
] | Import CLI commands modules. | [
"Import",
"CLI",
"commands",
"modules",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/base.py#L372-L396 | train |
Gandi/gandi.cli | gandi/cli/core/client.py | XMLRPCClient.request | def request(self, method, apikey, *args, **kwargs):
""" Make a xml-rpc call to remote API. """
dry_run = kwargs.get('dry_run', False)
return_dry_run = kwargs.get('return_dry_run', False)
if return_dry_run:
args[-1]['--dry-run'] = True
try:
func = getattr(self.endpoint, method)
return func(apikey, *args)
except (socket.error, requests.exceptions.ConnectionError):
msg = 'Gandi API service is unreachable'
raise APICallFailed(msg)
except xmlrpclib.Fault as err:
msg = 'Gandi API has returned an error: %s' % err
if dry_run:
args[-1]['--dry-run'] = True
ret = func(apikey, *args)
raise DryRunException(msg, err.faultCode, ret)
raise APICallFailed(msg, err.faultCode)
except TypeError as err:
msg = 'An unknown error has occurred: %s' % err
raise APICallFailed(msg) | python | def request(self, method, apikey, *args, **kwargs):
""" Make a xml-rpc call to remote API. """
dry_run = kwargs.get('dry_run', False)
return_dry_run = kwargs.get('return_dry_run', False)
if return_dry_run:
args[-1]['--dry-run'] = True
try:
func = getattr(self.endpoint, method)
return func(apikey, *args)
except (socket.error, requests.exceptions.ConnectionError):
msg = 'Gandi API service is unreachable'
raise APICallFailed(msg)
except xmlrpclib.Fault as err:
msg = 'Gandi API has returned an error: %s' % err
if dry_run:
args[-1]['--dry-run'] = True
ret = func(apikey, *args)
raise DryRunException(msg, err.faultCode, ret)
raise APICallFailed(msg, err.faultCode)
except TypeError as err:
msg = 'An unknown error has occurred: %s' % err
raise APICallFailed(msg) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"apikey",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dry_run",
"=",
"kwargs",
".",
"get",
"(",
"'dry_run'",
",",
"False",
")",
"return_dry_run",
"=",
"kwargs",
".",
"get",
"(",
"'return_dry_run'",
",",
"False",
")",
"if",
"return_dry_run",
":",
"args",
"[",
"-",
"1",
"]",
"[",
"'--dry-run'",
"]",
"=",
"True",
"try",
":",
"func",
"=",
"getattr",
"(",
"self",
".",
"endpoint",
",",
"method",
")",
"return",
"func",
"(",
"apikey",
",",
"*",
"args",
")",
"except",
"(",
"socket",
".",
"error",
",",
"requests",
".",
"exceptions",
".",
"ConnectionError",
")",
":",
"msg",
"=",
"'Gandi API service is unreachable'",
"raise",
"APICallFailed",
"(",
"msg",
")",
"except",
"xmlrpclib",
".",
"Fault",
"as",
"err",
":",
"msg",
"=",
"'Gandi API has returned an error: %s'",
"%",
"err",
"if",
"dry_run",
":",
"args",
"[",
"-",
"1",
"]",
"[",
"'--dry-run'",
"]",
"=",
"True",
"ret",
"=",
"func",
"(",
"apikey",
",",
"*",
"args",
")",
"raise",
"DryRunException",
"(",
"msg",
",",
"err",
".",
"faultCode",
",",
"ret",
")",
"raise",
"APICallFailed",
"(",
"msg",
",",
"err",
".",
"faultCode",
")",
"except",
"TypeError",
"as",
"err",
":",
"msg",
"=",
"'An unknown error has occurred: %s'",
"%",
"err",
"raise",
"APICallFailed",
"(",
"msg",
")"
] | Make a xml-rpc call to remote API. | [
"Make",
"a",
"xml",
"-",
"rpc",
"call",
"to",
"remote",
"API",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/client.py#L61-L83 | train |
Gandi/gandi.cli | gandi/cli/core/client.py | JsonClient.request | def request(cls, method, url, **kwargs):
"""Make a http call to a remote API and return a json response."""
user_agent = 'gandi.cli/%s' % __version__
headers = {'User-Agent': user_agent,
'Content-Type': 'application/json; charset=utf-8'}
if kwargs.get('headers'):
headers.update(kwargs.pop('headers'))
try:
response = requests.request(method, url, headers=headers,
**kwargs)
response.raise_for_status()
try:
return response.json(), response.headers
except ValueError as err:
return response.text, response.headers
except (socket.error, requests.exceptions.ConnectionError):
msg = 'Remote API service is unreachable'
raise APICallFailed(msg)
except Exception as err:
if isinstance(err, requests.HTTPError):
try:
resp = response.json()
except Exception:
msg = 'An unknown error has occurred: %s' % err
raise APICallFailed(msg)
if resp.get('message'):
error = resp.get('message')
if resp.get('errors'):
error = cls.format_errors(resp.get('errors'))
msg = '%s: %s' % (err, error)
else:
msg = 'An unknown error has occurred: %s' % err
raise APICallFailed(msg) | python | def request(cls, method, url, **kwargs):
"""Make a http call to a remote API and return a json response."""
user_agent = 'gandi.cli/%s' % __version__
headers = {'User-Agent': user_agent,
'Content-Type': 'application/json; charset=utf-8'}
if kwargs.get('headers'):
headers.update(kwargs.pop('headers'))
try:
response = requests.request(method, url, headers=headers,
**kwargs)
response.raise_for_status()
try:
return response.json(), response.headers
except ValueError as err:
return response.text, response.headers
except (socket.error, requests.exceptions.ConnectionError):
msg = 'Remote API service is unreachable'
raise APICallFailed(msg)
except Exception as err:
if isinstance(err, requests.HTTPError):
try:
resp = response.json()
except Exception:
msg = 'An unknown error has occurred: %s' % err
raise APICallFailed(msg)
if resp.get('message'):
error = resp.get('message')
if resp.get('errors'):
error = cls.format_errors(resp.get('errors'))
msg = '%s: %s' % (err, error)
else:
msg = 'An unknown error has occurred: %s' % err
raise APICallFailed(msg) | [
"def",
"request",
"(",
"cls",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"user_agent",
"=",
"'gandi.cli/%s'",
"%",
"__version__",
"headers",
"=",
"{",
"'User-Agent'",
":",
"user_agent",
",",
"'Content-Type'",
":",
"'application/json; charset=utf-8'",
"}",
"if",
"kwargs",
".",
"get",
"(",
"'headers'",
")",
":",
"headers",
".",
"update",
"(",
"kwargs",
".",
"pop",
"(",
"'headers'",
")",
")",
"try",
":",
"response",
"=",
"requests",
".",
"request",
"(",
"method",
",",
"url",
",",
"headers",
"=",
"headers",
",",
"*",
"*",
"kwargs",
")",
"response",
".",
"raise_for_status",
"(",
")",
"try",
":",
"return",
"response",
".",
"json",
"(",
")",
",",
"response",
".",
"headers",
"except",
"ValueError",
"as",
"err",
":",
"return",
"response",
".",
"text",
",",
"response",
".",
"headers",
"except",
"(",
"socket",
".",
"error",
",",
"requests",
".",
"exceptions",
".",
"ConnectionError",
")",
":",
"msg",
"=",
"'Remote API service is unreachable'",
"raise",
"APICallFailed",
"(",
"msg",
")",
"except",
"Exception",
"as",
"err",
":",
"if",
"isinstance",
"(",
"err",
",",
"requests",
".",
"HTTPError",
")",
":",
"try",
":",
"resp",
"=",
"response",
".",
"json",
"(",
")",
"except",
"Exception",
":",
"msg",
"=",
"'An unknown error has occurred: %s'",
"%",
"err",
"raise",
"APICallFailed",
"(",
"msg",
")",
"if",
"resp",
".",
"get",
"(",
"'message'",
")",
":",
"error",
"=",
"resp",
".",
"get",
"(",
"'message'",
")",
"if",
"resp",
".",
"get",
"(",
"'errors'",
")",
":",
"error",
"=",
"cls",
".",
"format_errors",
"(",
"resp",
".",
"get",
"(",
"'errors'",
")",
")",
"msg",
"=",
"'%s: %s'",
"%",
"(",
"err",
",",
"error",
")",
"else",
":",
"msg",
"=",
"'An unknown error has occurred: %s'",
"%",
"err",
"raise",
"APICallFailed",
"(",
"msg",
")"
] | Make a http call to a remote API and return a json response. | [
"Make",
"a",
"http",
"call",
"to",
"a",
"remote",
"API",
"and",
"return",
"a",
"json",
"response",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/client.py#L95-L129 | train |
Gandi/gandi.cli | gandi/cli/commands/docker.py | docker | def docker(gandi, vm, args):
"""
Manage docker instance
"""
if not [basedir for basedir in os.getenv('PATH', '.:/usr/bin').split(':')
if os.path.exists('%s/docker' % basedir)]:
gandi.echo("""'docker' not found in $PATH, required for this command \
to work
See https://docs.docker.com/installation/#installation to install, or use:
# curl https://get.docker.io/ | sh""")
return
if vm:
gandi.configure(True, 'dockervm', vm)
else:
vm = gandi.get('dockervm')
if not vm:
gandi.echo("""
No docker vm specified. You can create one:
$ gandi vm create --hostname docker --image "Ubuntu 14.04 64 bits LTS (HVM)" \\
--run 'wget -O - https://get.docker.io/ | sh'
Then configure it using:
$ gandi docker --vm docker ps
Or to both change target vm and spawn a process (note the -- separator):
$ gandi docker --vm myvm -- run -i -t debian bash
""") # noqa
return
return gandi.docker.handle(vm, args) | python | def docker(gandi, vm, args):
"""
Manage docker instance
"""
if not [basedir for basedir in os.getenv('PATH', '.:/usr/bin').split(':')
if os.path.exists('%s/docker' % basedir)]:
gandi.echo("""'docker' not found in $PATH, required for this command \
to work
See https://docs.docker.com/installation/#installation to install, or use:
# curl https://get.docker.io/ | sh""")
return
if vm:
gandi.configure(True, 'dockervm', vm)
else:
vm = gandi.get('dockervm')
if not vm:
gandi.echo("""
No docker vm specified. You can create one:
$ gandi vm create --hostname docker --image "Ubuntu 14.04 64 bits LTS (HVM)" \\
--run 'wget -O - https://get.docker.io/ | sh'
Then configure it using:
$ gandi docker --vm docker ps
Or to both change target vm and spawn a process (note the -- separator):
$ gandi docker --vm myvm -- run -i -t debian bash
""") # noqa
return
return gandi.docker.handle(vm, args) | [
"def",
"docker",
"(",
"gandi",
",",
"vm",
",",
"args",
")",
":",
"if",
"not",
"[",
"basedir",
"for",
"basedir",
"in",
"os",
".",
"getenv",
"(",
"'PATH'",
",",
"'.:/usr/bin'",
")",
".",
"split",
"(",
"':'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'%s/docker'",
"%",
"basedir",
")",
"]",
":",
"gandi",
".",
"echo",
"(",
"\"\"\"'docker' not found in $PATH, required for this command \\\nto work\nSee https://docs.docker.com/installation/#installation to install, or use:\n # curl https://get.docker.io/ | sh\"\"\"",
")",
"return",
"if",
"vm",
":",
"gandi",
".",
"configure",
"(",
"True",
",",
"'dockervm'",
",",
"vm",
")",
"else",
":",
"vm",
"=",
"gandi",
".",
"get",
"(",
"'dockervm'",
")",
"if",
"not",
"vm",
":",
"gandi",
".",
"echo",
"(",
"\"\"\"\nNo docker vm specified. You can create one:\n $ gandi vm create --hostname docker --image \"Ubuntu 14.04 64 bits LTS (HVM)\" \\\\\n --run 'wget -O - https://get.docker.io/ | sh'\n\nThen configure it using:\n $ gandi docker --vm docker ps\n\nOr to both change target vm and spawn a process (note the -- separator):\n $ gandi docker --vm myvm -- run -i -t debian bash\n\"\"\"",
")",
"# noqa",
"return",
"return",
"gandi",
".",
"docker",
".",
"handle",
"(",
"vm",
",",
"args",
")"
] | Manage docker instance | [
"Manage",
"docker",
"instance"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/docker.py#L15-L46 | train |
Gandi/gandi.cli | gandi/cli/modules/metric.py | Metric.query | def query(cls, resources, time_range, query, resource_type, sampler):
"""Query statistics for given resources."""
if not isinstance(resources, (list, tuple)):
resources = [resources]
now = time.time()
start_utc = datetime.utcfromtimestamp(now - time_range)
end_utc = datetime.utcfromtimestamp(now)
date_format = '%Y-%m-%d %H:%M:%S'
start = start_utc.strftime(date_format)
end = end_utc.strftime(date_format)
query = {'start': start,
'end': end,
'query': query,
'resource_id': resources,
'resource_type': resource_type,
'sampler': sampler}
return cls.call('hosting.metric.query', query) | python | def query(cls, resources, time_range, query, resource_type, sampler):
"""Query statistics for given resources."""
if not isinstance(resources, (list, tuple)):
resources = [resources]
now = time.time()
start_utc = datetime.utcfromtimestamp(now - time_range)
end_utc = datetime.utcfromtimestamp(now)
date_format = '%Y-%m-%d %H:%M:%S'
start = start_utc.strftime(date_format)
end = end_utc.strftime(date_format)
query = {'start': start,
'end': end,
'query': query,
'resource_id': resources,
'resource_type': resource_type,
'sampler': sampler}
return cls.call('hosting.metric.query', query) | [
"def",
"query",
"(",
"cls",
",",
"resources",
",",
"time_range",
",",
"query",
",",
"resource_type",
",",
"sampler",
")",
":",
"if",
"not",
"isinstance",
"(",
"resources",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"resources",
"=",
"[",
"resources",
"]",
"now",
"=",
"time",
".",
"time",
"(",
")",
"start_utc",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"now",
"-",
"time_range",
")",
"end_utc",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"now",
")",
"date_format",
"=",
"'%Y-%m-%d %H:%M:%S'",
"start",
"=",
"start_utc",
".",
"strftime",
"(",
"date_format",
")",
"end",
"=",
"end_utc",
".",
"strftime",
"(",
"date_format",
")",
"query",
"=",
"{",
"'start'",
":",
"start",
",",
"'end'",
":",
"end",
",",
"'query'",
":",
"query",
",",
"'resource_id'",
":",
"resources",
",",
"'resource_type'",
":",
"resource_type",
",",
"'sampler'",
":",
"sampler",
"}",
"return",
"cls",
".",
"call",
"(",
"'hosting.metric.query'",
",",
"query",
")"
] | Query statistics for given resources. | [
"Query",
"statistics",
"for",
"given",
"resources",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/metric.py#L16-L33 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Iaas.required_max_memory | def required_max_memory(cls, id, memory):
"""
Recommend a max_memory setting for this vm given memory. If the
VM already has a nice setting, return None. The max_memory
param cannot be fixed too high, because page table allocation
would cost too much for small memory profile. Use a range as below.
"""
best = int(max(2 ** math.ceil(math.log(memory, 2)), 2048))
actual_vm = cls.info(id)
if (actual_vm['state'] == 'running'
and actual_vm['vm_max_memory'] != best):
return best | python | def required_max_memory(cls, id, memory):
"""
Recommend a max_memory setting for this vm given memory. If the
VM already has a nice setting, return None. The max_memory
param cannot be fixed too high, because page table allocation
would cost too much for small memory profile. Use a range as below.
"""
best = int(max(2 ** math.ceil(math.log(memory, 2)), 2048))
actual_vm = cls.info(id)
if (actual_vm['state'] == 'running'
and actual_vm['vm_max_memory'] != best):
return best | [
"def",
"required_max_memory",
"(",
"cls",
",",
"id",
",",
"memory",
")",
":",
"best",
"=",
"int",
"(",
"max",
"(",
"2",
"**",
"math",
".",
"ceil",
"(",
"math",
".",
"log",
"(",
"memory",
",",
"2",
")",
")",
",",
"2048",
")",
")",
"actual_vm",
"=",
"cls",
".",
"info",
"(",
"id",
")",
"if",
"(",
"actual_vm",
"[",
"'state'",
"]",
"==",
"'running'",
"and",
"actual_vm",
"[",
"'vm_max_memory'",
"]",
"!=",
"best",
")",
":",
"return",
"best"
] | Recommend a max_memory setting for this vm given memory. If the
VM already has a nice setting, return None. The max_memory
param cannot be fixed too high, because page table allocation
would cost too much for small memory profile. Use a range as below. | [
"Recommend",
"a",
"max_memory",
"setting",
"for",
"this",
"vm",
"given",
"memory",
".",
"If",
"the",
"VM",
"already",
"has",
"a",
"nice",
"setting",
"return",
"None",
".",
"The",
"max_memory",
"param",
"cannot",
"be",
"fixed",
"too",
"high",
"because",
"page",
"table",
"allocation",
"would",
"cost",
"too",
"much",
"for",
"small",
"memory",
"profile",
".",
"Use",
"a",
"range",
"as",
"below",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L149-L162 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Iaas.need_finalize | def need_finalize(cls, resource):
"""Check if vm migration need to be finalized."""
vm_id = cls.usable_id(resource)
params = {'type': 'hosting_migration_vm',
'step': 'RUN',
'vm_id': vm_id}
result = cls.call('operation.list', params)
if not result or len(result) > 1:
raise MigrationNotFinalized('Cannot find VM %s '
'migration operation.' % resource)
need_finalize = result[0]['params']['inner_step'] == 'wait_finalize'
if not need_finalize:
raise MigrationNotFinalized('VM %s migration does not need '
'finalization.' % resource) | python | def need_finalize(cls, resource):
"""Check if vm migration need to be finalized."""
vm_id = cls.usable_id(resource)
params = {'type': 'hosting_migration_vm',
'step': 'RUN',
'vm_id': vm_id}
result = cls.call('operation.list', params)
if not result or len(result) > 1:
raise MigrationNotFinalized('Cannot find VM %s '
'migration operation.' % resource)
need_finalize = result[0]['params']['inner_step'] == 'wait_finalize'
if not need_finalize:
raise MigrationNotFinalized('VM %s migration does not need '
'finalization.' % resource) | [
"def",
"need_finalize",
"(",
"cls",
",",
"resource",
")",
":",
"vm_id",
"=",
"cls",
".",
"usable_id",
"(",
"resource",
")",
"params",
"=",
"{",
"'type'",
":",
"'hosting_migration_vm'",
",",
"'step'",
":",
"'RUN'",
",",
"'vm_id'",
":",
"vm_id",
"}",
"result",
"=",
"cls",
".",
"call",
"(",
"'operation.list'",
",",
"params",
")",
"if",
"not",
"result",
"or",
"len",
"(",
"result",
")",
">",
"1",
":",
"raise",
"MigrationNotFinalized",
"(",
"'Cannot find VM %s '",
"'migration operation.'",
"%",
"resource",
")",
"need_finalize",
"=",
"result",
"[",
"0",
"]",
"[",
"'params'",
"]",
"[",
"'inner_step'",
"]",
"==",
"'wait_finalize'",
"if",
"not",
"need_finalize",
":",
"raise",
"MigrationNotFinalized",
"(",
"'VM %s migration does not need '",
"'finalization.'",
"%",
"resource",
")"
] | Check if vm migration need to be finalized. | [
"Check",
"if",
"vm",
"migration",
"need",
"to",
"be",
"finalized",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L325-L339 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Iaas.check_can_migrate | def check_can_migrate(cls, resource):
"""Check if virtual machine can be migrated to another datacenter."""
vm_id = cls.usable_id(resource)
result = cls.call('hosting.vm.can_migrate', vm_id)
if not result['can_migrate']:
if result['matched']:
matched = result['matched'][0]
cls.echo('Your VM %s cannot be migrated yet. Migration will '
'be available when datacenter %s is opened.'
% (resource, matched))
else:
cls.echo('Your VM %s cannot be migrated.' % resource)
return False
return True | python | def check_can_migrate(cls, resource):
"""Check if virtual machine can be migrated to another datacenter."""
vm_id = cls.usable_id(resource)
result = cls.call('hosting.vm.can_migrate', vm_id)
if not result['can_migrate']:
if result['matched']:
matched = result['matched'][0]
cls.echo('Your VM %s cannot be migrated yet. Migration will '
'be available when datacenter %s is opened.'
% (resource, matched))
else:
cls.echo('Your VM %s cannot be migrated.' % resource)
return False
return True | [
"def",
"check_can_migrate",
"(",
"cls",
",",
"resource",
")",
":",
"vm_id",
"=",
"cls",
".",
"usable_id",
"(",
"resource",
")",
"result",
"=",
"cls",
".",
"call",
"(",
"'hosting.vm.can_migrate'",
",",
"vm_id",
")",
"if",
"not",
"result",
"[",
"'can_migrate'",
"]",
":",
"if",
"result",
"[",
"'matched'",
"]",
":",
"matched",
"=",
"result",
"[",
"'matched'",
"]",
"[",
"0",
"]",
"cls",
".",
"echo",
"(",
"'Your VM %s cannot be migrated yet. Migration will '",
"'be available when datacenter %s is opened.'",
"%",
"(",
"resource",
",",
"matched",
")",
")",
"else",
":",
"cls",
".",
"echo",
"(",
"'Your VM %s cannot be migrated.'",
"%",
"resource",
")",
"return",
"False",
"return",
"True"
] | Check if virtual machine can be migrated to another datacenter. | [
"Check",
"if",
"virtual",
"machine",
"can",
"be",
"migrated",
"to",
"another",
"datacenter",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L342-L357 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Iaas.from_hostname | def from_hostname(cls, hostname):
"""Retrieve virtual machine id associated to a hostname."""
result = cls.list({'hostname': str(hostname)})
if result:
return result[0]['id'] | python | def from_hostname(cls, hostname):
"""Retrieve virtual machine id associated to a hostname."""
result = cls.list({'hostname': str(hostname)})
if result:
return result[0]['id'] | [
"def",
"from_hostname",
"(",
"cls",
",",
"hostname",
")",
":",
"result",
"=",
"cls",
".",
"list",
"(",
"{",
"'hostname'",
":",
"str",
"(",
"hostname",
")",
"}",
")",
"if",
"result",
":",
"return",
"result",
"[",
"0",
"]",
"[",
"'id'",
"]"
] | Retrieve virtual machine id associated to a hostname. | [
"Retrieve",
"virtual",
"machine",
"id",
"associated",
"to",
"a",
"hostname",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L391-L395 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Iaas.wait_for_sshd | def wait_for_sshd(cls, vm_id):
"""Insist on having the vm booted and sshd
listening"""
cls.echo('Waiting for the vm to come online')
version, ip_addr = cls.vm_ip(vm_id)
give_up = time.time() + 300
last_error = None
while time.time() < give_up:
try:
inet = socket.AF_INET
if version == 6:
inet = socket.AF_INET6
sd = socket.socket(inet, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
sd.settimeout(5)
sd.connect((ip_addr, 22))
sd.recv(1024)
return
except socket.error as err:
if err.errno == errno.EHOSTUNREACH and version == 6:
cls.error('%s is not reachable, you may be missing '
'IPv6 connectivity' % ip_addr)
last_error = err
time.sleep(1)
except Exception as err:
last_error = err
time.sleep(1)
cls.error('VM did not spin up (last error: %s)' % last_error) | python | def wait_for_sshd(cls, vm_id):
"""Insist on having the vm booted and sshd
listening"""
cls.echo('Waiting for the vm to come online')
version, ip_addr = cls.vm_ip(vm_id)
give_up = time.time() + 300
last_error = None
while time.time() < give_up:
try:
inet = socket.AF_INET
if version == 6:
inet = socket.AF_INET6
sd = socket.socket(inet, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
sd.settimeout(5)
sd.connect((ip_addr, 22))
sd.recv(1024)
return
except socket.error as err:
if err.errno == errno.EHOSTUNREACH and version == 6:
cls.error('%s is not reachable, you may be missing '
'IPv6 connectivity' % ip_addr)
last_error = err
time.sleep(1)
except Exception as err:
last_error = err
time.sleep(1)
cls.error('VM did not spin up (last error: %s)' % last_error) | [
"def",
"wait_for_sshd",
"(",
"cls",
",",
"vm_id",
")",
":",
"cls",
".",
"echo",
"(",
"'Waiting for the vm to come online'",
")",
"version",
",",
"ip_addr",
"=",
"cls",
".",
"vm_ip",
"(",
"vm_id",
")",
"give_up",
"=",
"time",
".",
"time",
"(",
")",
"+",
"300",
"last_error",
"=",
"None",
"while",
"time",
".",
"time",
"(",
")",
"<",
"give_up",
":",
"try",
":",
"inet",
"=",
"socket",
".",
"AF_INET",
"if",
"version",
"==",
"6",
":",
"inet",
"=",
"socket",
".",
"AF_INET6",
"sd",
"=",
"socket",
".",
"socket",
"(",
"inet",
",",
"socket",
".",
"SOCK_STREAM",
",",
"socket",
".",
"IPPROTO_TCP",
")",
"sd",
".",
"settimeout",
"(",
"5",
")",
"sd",
".",
"connect",
"(",
"(",
"ip_addr",
",",
"22",
")",
")",
"sd",
".",
"recv",
"(",
"1024",
")",
"return",
"except",
"socket",
".",
"error",
"as",
"err",
":",
"if",
"err",
".",
"errno",
"==",
"errno",
".",
"EHOSTUNREACH",
"and",
"version",
"==",
"6",
":",
"cls",
".",
"error",
"(",
"'%s is not reachable, you may be missing '",
"'IPv6 connectivity'",
"%",
"ip_addr",
")",
"last_error",
"=",
"err",
"time",
".",
"sleep",
"(",
"1",
")",
"except",
"Exception",
"as",
"err",
":",
"last_error",
"=",
"err",
"time",
".",
"sleep",
"(",
"1",
")",
"cls",
".",
"error",
"(",
"'VM did not spin up (last error: %s)'",
"%",
"last_error",
")"
] | Insist on having the vm booted and sshd
listening | [
"Insist",
"on",
"having",
"the",
"vm",
"booted",
"and",
"sshd",
"listening"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L427-L454 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Iaas.ssh_keyscan | def ssh_keyscan(cls, vm_id):
"""Wipe this old key and learn the new one from a freshly
created vm. This is a security risk for this VM, however
we dont have another way to learn the key yet, so do this
for the user."""
cls.echo('Wiping old key and learning the new one')
_version, ip_addr = cls.vm_ip(vm_id)
cls.execute('ssh-keygen -R "%s"' % ip_addr)
for _ in range(5):
output = cls.exec_output('ssh-keyscan "%s"' % ip_addr)
if output:
with open(os.path.expanduser('~/.ssh/known_hosts'), 'a') as f:
f.write(output)
return True
time.sleep(.5) | python | def ssh_keyscan(cls, vm_id):
"""Wipe this old key and learn the new one from a freshly
created vm. This is a security risk for this VM, however
we dont have another way to learn the key yet, so do this
for the user."""
cls.echo('Wiping old key and learning the new one')
_version, ip_addr = cls.vm_ip(vm_id)
cls.execute('ssh-keygen -R "%s"' % ip_addr)
for _ in range(5):
output = cls.exec_output('ssh-keyscan "%s"' % ip_addr)
if output:
with open(os.path.expanduser('~/.ssh/known_hosts'), 'a') as f:
f.write(output)
return True
time.sleep(.5) | [
"def",
"ssh_keyscan",
"(",
"cls",
",",
"vm_id",
")",
":",
"cls",
".",
"echo",
"(",
"'Wiping old key and learning the new one'",
")",
"_version",
",",
"ip_addr",
"=",
"cls",
".",
"vm_ip",
"(",
"vm_id",
")",
"cls",
".",
"execute",
"(",
"'ssh-keygen -R \"%s\"'",
"%",
"ip_addr",
")",
"for",
"_",
"in",
"range",
"(",
"5",
")",
":",
"output",
"=",
"cls",
".",
"exec_output",
"(",
"'ssh-keyscan \"%s\"'",
"%",
"ip_addr",
")",
"if",
"output",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.ssh/known_hosts'",
")",
",",
"'a'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"output",
")",
"return",
"True",
"time",
".",
"sleep",
"(",
".5",
")"
] | Wipe this old key and learn the new one from a freshly
created vm. This is a security risk for this VM, however
we dont have another way to learn the key yet, so do this
for the user. | [
"Wipe",
"this",
"old",
"key",
"and",
"learn",
"the",
"new",
"one",
"from",
"a",
"freshly",
"created",
"vm",
".",
"This",
"is",
"a",
"security",
"risk",
"for",
"this",
"VM",
"however",
"we",
"dont",
"have",
"another",
"way",
"to",
"learn",
"the",
"key",
"yet",
"so",
"do",
"this",
"for",
"the",
"user",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L457-L472 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Iaas.scp | def scp(cls, vm_id, login, identity, local_file, remote_file):
"""Copy file to remote VM."""
cmd = ['scp']
if identity:
cmd.extend(('-i', identity,))
version, ip_addr = cls.vm_ip(vm_id)
if version == 6:
ip_addr = '[%s]' % ip_addr
cmd.extend((local_file, '%s@%s:%s' %
(login, ip_addr, remote_file),))
cls.echo('Running %s' % ' '.join(cmd))
for _ in range(5):
ret = cls.execute(cmd, False)
if ret:
break
time.sleep(.5)
return ret | python | def scp(cls, vm_id, login, identity, local_file, remote_file):
"""Copy file to remote VM."""
cmd = ['scp']
if identity:
cmd.extend(('-i', identity,))
version, ip_addr = cls.vm_ip(vm_id)
if version == 6:
ip_addr = '[%s]' % ip_addr
cmd.extend((local_file, '%s@%s:%s' %
(login, ip_addr, remote_file),))
cls.echo('Running %s' % ' '.join(cmd))
for _ in range(5):
ret = cls.execute(cmd, False)
if ret:
break
time.sleep(.5)
return ret | [
"def",
"scp",
"(",
"cls",
",",
"vm_id",
",",
"login",
",",
"identity",
",",
"local_file",
",",
"remote_file",
")",
":",
"cmd",
"=",
"[",
"'scp'",
"]",
"if",
"identity",
":",
"cmd",
".",
"extend",
"(",
"(",
"'-i'",
",",
"identity",
",",
")",
")",
"version",
",",
"ip_addr",
"=",
"cls",
".",
"vm_ip",
"(",
"vm_id",
")",
"if",
"version",
"==",
"6",
":",
"ip_addr",
"=",
"'[%s]'",
"%",
"ip_addr",
"cmd",
".",
"extend",
"(",
"(",
"local_file",
",",
"'%s@%s:%s'",
"%",
"(",
"login",
",",
"ip_addr",
",",
"remote_file",
")",
",",
")",
")",
"cls",
".",
"echo",
"(",
"'Running %s'",
"%",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"for",
"_",
"in",
"range",
"(",
"5",
")",
":",
"ret",
"=",
"cls",
".",
"execute",
"(",
"cmd",
",",
"False",
")",
"if",
"ret",
":",
"break",
"time",
".",
"sleep",
"(",
".5",
")",
"return",
"ret"
] | Copy file to remote VM. | [
"Copy",
"file",
"to",
"remote",
"VM",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L475-L493 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Iaas.ssh | def ssh(cls, vm_id, login, identity, args=None):
"""Spawn an ssh session to virtual machine."""
cmd = ['ssh']
if identity:
cmd.extend(('-i', identity,))
version, ip_addr = cls.vm_ip(vm_id)
if version == 6:
cmd.append('-6')
if not ip_addr:
cls.echo('No IP address found for vm %s, aborting.' % vm_id)
return
cmd.append('%s@%s' % (login, ip_addr,))
if args:
cmd.extend(args)
cls.echo('Requesting access using: %s ...' % ' '.join(cmd))
return cls.execute(cmd, False) | python | def ssh(cls, vm_id, login, identity, args=None):
"""Spawn an ssh session to virtual machine."""
cmd = ['ssh']
if identity:
cmd.extend(('-i', identity,))
version, ip_addr = cls.vm_ip(vm_id)
if version == 6:
cmd.append('-6')
if not ip_addr:
cls.echo('No IP address found for vm %s, aborting.' % vm_id)
return
cmd.append('%s@%s' % (login, ip_addr,))
if args:
cmd.extend(args)
cls.echo('Requesting access using: %s ...' % ' '.join(cmd))
return cls.execute(cmd, False) | [
"def",
"ssh",
"(",
"cls",
",",
"vm_id",
",",
"login",
",",
"identity",
",",
"args",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'ssh'",
"]",
"if",
"identity",
":",
"cmd",
".",
"extend",
"(",
"(",
"'-i'",
",",
"identity",
",",
")",
")",
"version",
",",
"ip_addr",
"=",
"cls",
".",
"vm_ip",
"(",
"vm_id",
")",
"if",
"version",
"==",
"6",
":",
"cmd",
".",
"append",
"(",
"'-6'",
")",
"if",
"not",
"ip_addr",
":",
"cls",
".",
"echo",
"(",
"'No IP address found for vm %s, aborting.'",
"%",
"vm_id",
")",
"return",
"cmd",
".",
"append",
"(",
"'%s@%s'",
"%",
"(",
"login",
",",
"ip_addr",
",",
")",
")",
"if",
"args",
":",
"cmd",
".",
"extend",
"(",
"args",
")",
"cls",
".",
"echo",
"(",
"'Requesting access using: %s ...'",
"%",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"return",
"cls",
".",
"execute",
"(",
"cmd",
",",
"False",
")"
] | Spawn an ssh session to virtual machine. | [
"Spawn",
"an",
"ssh",
"session",
"to",
"virtual",
"machine",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L496-L516 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Image.is_deprecated | def is_deprecated(cls, label, datacenter=None):
"""Check if image if flagged as deprecated."""
images = cls.list(datacenter, label)
images_visibility = dict([(image['label'], image['visibility'])
for image in images])
return images_visibility.get(label, 'all') == 'deprecated' | python | def is_deprecated(cls, label, datacenter=None):
"""Check if image if flagged as deprecated."""
images = cls.list(datacenter, label)
images_visibility = dict([(image['label'], image['visibility'])
for image in images])
return images_visibility.get(label, 'all') == 'deprecated' | [
"def",
"is_deprecated",
"(",
"cls",
",",
"label",
",",
"datacenter",
"=",
"None",
")",
":",
"images",
"=",
"cls",
".",
"list",
"(",
"datacenter",
",",
"label",
")",
"images_visibility",
"=",
"dict",
"(",
"[",
"(",
"image",
"[",
"'label'",
"]",
",",
"image",
"[",
"'visibility'",
"]",
")",
"for",
"image",
"in",
"images",
"]",
")",
"return",
"images_visibility",
".",
"get",
"(",
"label",
",",
"'all'",
")",
"==",
"'deprecated'"
] | Check if image if flagged as deprecated. | [
"Check",
"if",
"image",
"if",
"flagged",
"as",
"deprecated",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L560-L565 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Image.from_label | def from_label(cls, label, datacenter=None):
"""Retrieve disk image id associated to a label."""
result = cls.list(datacenter=datacenter)
image_labels = dict([(image['label'], image['disk_id'])
for image in result])
return image_labels.get(label) | python | def from_label(cls, label, datacenter=None):
"""Retrieve disk image id associated to a label."""
result = cls.list(datacenter=datacenter)
image_labels = dict([(image['label'], image['disk_id'])
for image in result])
return image_labels.get(label) | [
"def",
"from_label",
"(",
"cls",
",",
"label",
",",
"datacenter",
"=",
"None",
")",
":",
"result",
"=",
"cls",
".",
"list",
"(",
"datacenter",
"=",
"datacenter",
")",
"image_labels",
"=",
"dict",
"(",
"[",
"(",
"image",
"[",
"'label'",
"]",
",",
"image",
"[",
"'disk_id'",
"]",
")",
"for",
"image",
"in",
"result",
"]",
")",
"return",
"image_labels",
".",
"get",
"(",
"label",
")"
] | Retrieve disk image id associated to a label. | [
"Retrieve",
"disk",
"image",
"id",
"associated",
"to",
"a",
"label",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L568-L574 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Image.from_sysdisk | def from_sysdisk(cls, label):
"""Retrieve disk id from available system disks"""
disks = cls.safe_call('hosting.disk.list', {'name': label})
if len(disks):
return disks[0]['id'] | python | def from_sysdisk(cls, label):
"""Retrieve disk id from available system disks"""
disks = cls.safe_call('hosting.disk.list', {'name': label})
if len(disks):
return disks[0]['id'] | [
"def",
"from_sysdisk",
"(",
"cls",
",",
"label",
")",
":",
"disks",
"=",
"cls",
".",
"safe_call",
"(",
"'hosting.disk.list'",
",",
"{",
"'name'",
":",
"label",
"}",
")",
"if",
"len",
"(",
"disks",
")",
":",
"return",
"disks",
"[",
"0",
"]",
"[",
"'id'",
"]"
] | Retrieve disk id from available system disks | [
"Retrieve",
"disk",
"id",
"from",
"available",
"system",
"disks"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L577-L581 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Image.usable_id | def usable_id(cls, id, datacenter=None):
""" Retrieve id from input which can be label or id."""
try:
qry_id = int(id)
except Exception:
# if id is a string, prefer a system disk then a label
qry_id = cls.from_sysdisk(id) or cls.from_label(id, datacenter)
if not qry_id:
msg = 'unknown identifier %s' % id
cls.error(msg)
return qry_id | python | def usable_id(cls, id, datacenter=None):
""" Retrieve id from input which can be label or id."""
try:
qry_id = int(id)
except Exception:
# if id is a string, prefer a system disk then a label
qry_id = cls.from_sysdisk(id) or cls.from_label(id, datacenter)
if not qry_id:
msg = 'unknown identifier %s' % id
cls.error(msg)
return qry_id | [
"def",
"usable_id",
"(",
"cls",
",",
"id",
",",
"datacenter",
"=",
"None",
")",
":",
"try",
":",
"qry_id",
"=",
"int",
"(",
"id",
")",
"except",
"Exception",
":",
"# if id is a string, prefer a system disk then a label",
"qry_id",
"=",
"cls",
".",
"from_sysdisk",
"(",
"id",
")",
"or",
"cls",
".",
"from_label",
"(",
"id",
",",
"datacenter",
")",
"if",
"not",
"qry_id",
":",
"msg",
"=",
"'unknown identifier %s'",
"%",
"id",
"cls",
".",
"error",
"(",
"msg",
")",
"return",
"qry_id"
] | Retrieve id from input which can be label or id. | [
"Retrieve",
"id",
"from",
"input",
"which",
"can",
"be",
"label",
"or",
"id",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L584-L596 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Kernel.list | def list(cls, datacenter=None, flavor=None, match='', exact_match=False):
""" List available kernels for datacenter."""
if not datacenter:
dc_ids = [dc['id'] for dc in Datacenter.filtered_list()]
kmap = {}
for dc_id in dc_ids:
vals = cls.safe_call('hosting.disk.list_kernels', dc_id)
for key in vals:
kmap.setdefault(key, []).extend(vals.get(key, []))
# remove duplicates
for key in kmap:
kmap[key] = list(set(kmap[key]))
else:
dc_id = Datacenter.usable_id(datacenter)
kmap = cls.safe_call('hosting.disk.list_kernels', dc_id)
if match:
for flav in kmap:
if exact_match:
kmap[flav] = [x for x in kmap[flav] if match == x]
else:
kmap[flav] = [x for x in kmap[flav] if match in x]
if flavor:
if flavor not in kmap:
cls.error('flavor %s not supported here' % flavor)
return dict([(flavor, kmap[flavor])])
return kmap | python | def list(cls, datacenter=None, flavor=None, match='', exact_match=False):
""" List available kernels for datacenter."""
if not datacenter:
dc_ids = [dc['id'] for dc in Datacenter.filtered_list()]
kmap = {}
for dc_id in dc_ids:
vals = cls.safe_call('hosting.disk.list_kernels', dc_id)
for key in vals:
kmap.setdefault(key, []).extend(vals.get(key, []))
# remove duplicates
for key in kmap:
kmap[key] = list(set(kmap[key]))
else:
dc_id = Datacenter.usable_id(datacenter)
kmap = cls.safe_call('hosting.disk.list_kernels', dc_id)
if match:
for flav in kmap:
if exact_match:
kmap[flav] = [x for x in kmap[flav] if match == x]
else:
kmap[flav] = [x for x in kmap[flav] if match in x]
if flavor:
if flavor not in kmap:
cls.error('flavor %s not supported here' % flavor)
return dict([(flavor, kmap[flavor])])
return kmap | [
"def",
"list",
"(",
"cls",
",",
"datacenter",
"=",
"None",
",",
"flavor",
"=",
"None",
",",
"match",
"=",
"''",
",",
"exact_match",
"=",
"False",
")",
":",
"if",
"not",
"datacenter",
":",
"dc_ids",
"=",
"[",
"dc",
"[",
"'id'",
"]",
"for",
"dc",
"in",
"Datacenter",
".",
"filtered_list",
"(",
")",
"]",
"kmap",
"=",
"{",
"}",
"for",
"dc_id",
"in",
"dc_ids",
":",
"vals",
"=",
"cls",
".",
"safe_call",
"(",
"'hosting.disk.list_kernels'",
",",
"dc_id",
")",
"for",
"key",
"in",
"vals",
":",
"kmap",
".",
"setdefault",
"(",
"key",
",",
"[",
"]",
")",
".",
"extend",
"(",
"vals",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
")",
"# remove duplicates",
"for",
"key",
"in",
"kmap",
":",
"kmap",
"[",
"key",
"]",
"=",
"list",
"(",
"set",
"(",
"kmap",
"[",
"key",
"]",
")",
")",
"else",
":",
"dc_id",
"=",
"Datacenter",
".",
"usable_id",
"(",
"datacenter",
")",
"kmap",
"=",
"cls",
".",
"safe_call",
"(",
"'hosting.disk.list_kernels'",
",",
"dc_id",
")",
"if",
"match",
":",
"for",
"flav",
"in",
"kmap",
":",
"if",
"exact_match",
":",
"kmap",
"[",
"flav",
"]",
"=",
"[",
"x",
"for",
"x",
"in",
"kmap",
"[",
"flav",
"]",
"if",
"match",
"==",
"x",
"]",
"else",
":",
"kmap",
"[",
"flav",
"]",
"=",
"[",
"x",
"for",
"x",
"in",
"kmap",
"[",
"flav",
"]",
"if",
"match",
"in",
"x",
"]",
"if",
"flavor",
":",
"if",
"flavor",
"not",
"in",
"kmap",
":",
"cls",
".",
"error",
"(",
"'flavor %s not supported here'",
"%",
"flavor",
")",
"return",
"dict",
"(",
"[",
"(",
"flavor",
",",
"kmap",
"[",
"flavor",
"]",
")",
"]",
")",
"return",
"kmap"
] | List available kernels for datacenter. | [
"List",
"available",
"kernels",
"for",
"datacenter",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L604-L631 | train |
Gandi/gandi.cli | gandi/cli/modules/iaas.py | Kernel.is_available | def is_available(cls, disk, kernel):
""" Check if kernel is available for disk."""
kmap = cls.list(disk['datacenter_id'], None, kernel, True)
for flavor in kmap:
if kernel in kmap[flavor]:
return True
return False | python | def is_available(cls, disk, kernel):
""" Check if kernel is available for disk."""
kmap = cls.list(disk['datacenter_id'], None, kernel, True)
for flavor in kmap:
if kernel in kmap[flavor]:
return True
return False | [
"def",
"is_available",
"(",
"cls",
",",
"disk",
",",
"kernel",
")",
":",
"kmap",
"=",
"cls",
".",
"list",
"(",
"disk",
"[",
"'datacenter_id'",
"]",
",",
"None",
",",
"kernel",
",",
"True",
")",
"for",
"flavor",
"in",
"kmap",
":",
"if",
"kernel",
"in",
"kmap",
"[",
"flavor",
"]",
":",
"return",
"True",
"return",
"False"
] | Check if kernel is available for disk. | [
"Check",
"if",
"kernel",
"is",
"available",
"for",
"disk",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/iaas.py#L634-L640 | train |
Gandi/gandi.cli | gandi/cli/modules/paas.py | Paas.clone | def clone(cls, name, vhost, directory, origin):
"""Clone a PaaS instance's vhost into a local git repository."""
paas_info = cls.info(name)
if 'php' in paas_info['type'] and not vhost:
cls.error('PHP instances require indicating the VHOST to clone '
'with --vhost <vhost>')
paas_access = '%s@%s' % (paas_info['user'], paas_info['git_server'])
remote_url = 'ssh+git://%s/%s.git' % (paas_access, vhost)
command = 'git clone %s %s --origin %s' \
% (remote_url, directory, origin)
init_git = cls.execute(command)
if init_git:
cls.echo('Use `git push %s master` to push your code to the '
'instance.' % (origin))
cls.echo('Then `$ gandi deploy` to build and deploy your '
'application.') | python | def clone(cls, name, vhost, directory, origin):
"""Clone a PaaS instance's vhost into a local git repository."""
paas_info = cls.info(name)
if 'php' in paas_info['type'] and not vhost:
cls.error('PHP instances require indicating the VHOST to clone '
'with --vhost <vhost>')
paas_access = '%s@%s' % (paas_info['user'], paas_info['git_server'])
remote_url = 'ssh+git://%s/%s.git' % (paas_access, vhost)
command = 'git clone %s %s --origin %s' \
% (remote_url, directory, origin)
init_git = cls.execute(command)
if init_git:
cls.echo('Use `git push %s master` to push your code to the '
'instance.' % (origin))
cls.echo('Then `$ gandi deploy` to build and deploy your '
'application.') | [
"def",
"clone",
"(",
"cls",
",",
"name",
",",
"vhost",
",",
"directory",
",",
"origin",
")",
":",
"paas_info",
"=",
"cls",
".",
"info",
"(",
"name",
")",
"if",
"'php'",
"in",
"paas_info",
"[",
"'type'",
"]",
"and",
"not",
"vhost",
":",
"cls",
".",
"error",
"(",
"'PHP instances require indicating the VHOST to clone '",
"'with --vhost <vhost>'",
")",
"paas_access",
"=",
"'%s@%s'",
"%",
"(",
"paas_info",
"[",
"'user'",
"]",
",",
"paas_info",
"[",
"'git_server'",
"]",
")",
"remote_url",
"=",
"'ssh+git://%s/%s.git'",
"%",
"(",
"paas_access",
",",
"vhost",
")",
"command",
"=",
"'git clone %s %s --origin %s'",
"%",
"(",
"remote_url",
",",
"directory",
",",
"origin",
")",
"init_git",
"=",
"cls",
".",
"execute",
"(",
"command",
")",
"if",
"init_git",
":",
"cls",
".",
"echo",
"(",
"'Use `git push %s master` to push your code to the '",
"'instance.'",
"%",
"(",
"origin",
")",
")",
"cls",
".",
"echo",
"(",
"'Then `$ gandi deploy` to build and deploy your '",
"'application.'",
")"
] | Clone a PaaS instance's vhost into a local git repository. | [
"Clone",
"a",
"PaaS",
"instance",
"s",
"vhost",
"into",
"a",
"local",
"git",
"repository",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/paas.py#L36-L55 | train |
Gandi/gandi.cli | gandi/cli/modules/paas.py | Paas.attach | def attach(cls, name, vhost, remote_name):
"""Attach an instance's vhost to a remote from the local repository."""
paas_access = cls.get('paas_access')
if not paas_access:
paas_info = cls.info(name)
paas_access = '%s@%s' \
% (paas_info['user'], paas_info['git_server'])
remote_url = 'ssh+git://%s/%s.git' % (paas_access, vhost)
ret = cls.execute('git remote add %s %s' % (remote_name, remote_url,))
if ret:
cls.echo('Added remote `%s` to your local git repository.'
% (remote_name))
cls.echo('Use `git push %s master` to push your code to the '
'instance.' % (remote_name))
cls.echo('Then `$ gandi deploy` to build and deploy your '
'application.') | python | def attach(cls, name, vhost, remote_name):
"""Attach an instance's vhost to a remote from the local repository."""
paas_access = cls.get('paas_access')
if not paas_access:
paas_info = cls.info(name)
paas_access = '%s@%s' \
% (paas_info['user'], paas_info['git_server'])
remote_url = 'ssh+git://%s/%s.git' % (paas_access, vhost)
ret = cls.execute('git remote add %s %s' % (remote_name, remote_url,))
if ret:
cls.echo('Added remote `%s` to your local git repository.'
% (remote_name))
cls.echo('Use `git push %s master` to push your code to the '
'instance.' % (remote_name))
cls.echo('Then `$ gandi deploy` to build and deploy your '
'application.') | [
"def",
"attach",
"(",
"cls",
",",
"name",
",",
"vhost",
",",
"remote_name",
")",
":",
"paas_access",
"=",
"cls",
".",
"get",
"(",
"'paas_access'",
")",
"if",
"not",
"paas_access",
":",
"paas_info",
"=",
"cls",
".",
"info",
"(",
"name",
")",
"paas_access",
"=",
"'%s@%s'",
"%",
"(",
"paas_info",
"[",
"'user'",
"]",
",",
"paas_info",
"[",
"'git_server'",
"]",
")",
"remote_url",
"=",
"'ssh+git://%s/%s.git'",
"%",
"(",
"paas_access",
",",
"vhost",
")",
"ret",
"=",
"cls",
".",
"execute",
"(",
"'git remote add %s %s'",
"%",
"(",
"remote_name",
",",
"remote_url",
",",
")",
")",
"if",
"ret",
":",
"cls",
".",
"echo",
"(",
"'Added remote `%s` to your local git repository.'",
"%",
"(",
"remote_name",
")",
")",
"cls",
".",
"echo",
"(",
"'Use `git push %s master` to push your code to the '",
"'instance.'",
"%",
"(",
"remote_name",
")",
")",
"cls",
".",
"echo",
"(",
"'Then `$ gandi deploy` to build and deploy your '",
"'application.'",
")"
] | Attach an instance's vhost to a remote from the local repository. | [
"Attach",
"an",
"instance",
"s",
"vhost",
"to",
"a",
"remote",
"from",
"the",
"local",
"repository",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/paas.py#L58-L77 | train |
Gandi/gandi.cli | gandi/cli/modules/paas.py | Paas.cache | def cache(cls, id):
"""return the number of query cache for the last 24H"""
sampler = {'unit': 'days', 'value': 1, 'function': 'sum'}
query = 'webacc.requests.cache.all'
metrics = Metric.query(id, 60 * 60 * 24, query, 'paas', sampler)
cache = {'hit': 0, 'miss': 0, 'not': 0, 'pass': 0}
for metric in metrics:
what = metric['cache'].pop()
for point in metric['points']:
value = point.get('value', 0)
cache[what] += value
return cache | python | def cache(cls, id):
"""return the number of query cache for the last 24H"""
sampler = {'unit': 'days', 'value': 1, 'function': 'sum'}
query = 'webacc.requests.cache.all'
metrics = Metric.query(id, 60 * 60 * 24, query, 'paas', sampler)
cache = {'hit': 0, 'miss': 0, 'not': 0, 'pass': 0}
for metric in metrics:
what = metric['cache'].pop()
for point in metric['points']:
value = point.get('value', 0)
cache[what] += value
return cache | [
"def",
"cache",
"(",
"cls",
",",
"id",
")",
":",
"sampler",
"=",
"{",
"'unit'",
":",
"'days'",
",",
"'value'",
":",
"1",
",",
"'function'",
":",
"'sum'",
"}",
"query",
"=",
"'webacc.requests.cache.all'",
"metrics",
"=",
"Metric",
".",
"query",
"(",
"id",
",",
"60",
"*",
"60",
"*",
"24",
",",
"query",
",",
"'paas'",
",",
"sampler",
")",
"cache",
"=",
"{",
"'hit'",
":",
"0",
",",
"'miss'",
":",
"0",
",",
"'not'",
":",
"0",
",",
"'pass'",
":",
"0",
"}",
"for",
"metric",
"in",
"metrics",
":",
"what",
"=",
"metric",
"[",
"'cache'",
"]",
".",
"pop",
"(",
")",
"for",
"point",
"in",
"metric",
"[",
"'points'",
"]",
":",
"value",
"=",
"point",
".",
"get",
"(",
"'value'",
",",
"0",
")",
"cache",
"[",
"what",
"]",
"+=",
"value",
"return",
"cache"
] | return the number of query cache for the last 24H | [
"return",
"the",
"number",
"of",
"query",
"cache",
"for",
"the",
"last",
"24H"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/paas.py#L157-L169 | train |
Gandi/gandi.cli | gandi/cli/modules/paas.py | Paas.create | def create(cls, name, size, type, quantity, duration, datacenter, vhosts,
password, snapshot_profile, background, sshkey):
"""Create a new PaaS instance."""
if not background and not cls.intty():
background = True
datacenter_id_ = int(Datacenter.usable_id(datacenter))
paas_params = {
'name': name,
'size': size,
'type': type,
'duration': duration,
'datacenter_id': datacenter_id_,
}
if password:
paas_params['password'] = password
if quantity:
paas_params['quantity'] = quantity
paas_params.update(cls.convert_sshkey(sshkey))
if snapshot_profile:
paas_params['snapshot_profile'] = snapshot_profile
result = cls.call('paas.create', paas_params)
if not background:
# interactive mode, run a progress bar
cls.echo('Creating your PaaS instance.')
cls.display_progress(result)
cls.echo('Your PaaS instance %s has been created.' % name)
if vhosts:
paas_info = cls.info(name)
Vhost.create(paas_info, vhosts, True, background)
return result | python | def create(cls, name, size, type, quantity, duration, datacenter, vhosts,
password, snapshot_profile, background, sshkey):
"""Create a new PaaS instance."""
if not background and not cls.intty():
background = True
datacenter_id_ = int(Datacenter.usable_id(datacenter))
paas_params = {
'name': name,
'size': size,
'type': type,
'duration': duration,
'datacenter_id': datacenter_id_,
}
if password:
paas_params['password'] = password
if quantity:
paas_params['quantity'] = quantity
paas_params.update(cls.convert_sshkey(sshkey))
if snapshot_profile:
paas_params['snapshot_profile'] = snapshot_profile
result = cls.call('paas.create', paas_params)
if not background:
# interactive mode, run a progress bar
cls.echo('Creating your PaaS instance.')
cls.display_progress(result)
cls.echo('Your PaaS instance %s has been created.' % name)
if vhosts:
paas_info = cls.info(name)
Vhost.create(paas_info, vhosts, True, background)
return result | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"size",
",",
"type",
",",
"quantity",
",",
"duration",
",",
"datacenter",
",",
"vhosts",
",",
"password",
",",
"snapshot_profile",
",",
"background",
",",
"sshkey",
")",
":",
"if",
"not",
"background",
"and",
"not",
"cls",
".",
"intty",
"(",
")",
":",
"background",
"=",
"True",
"datacenter_id_",
"=",
"int",
"(",
"Datacenter",
".",
"usable_id",
"(",
"datacenter",
")",
")",
"paas_params",
"=",
"{",
"'name'",
":",
"name",
",",
"'size'",
":",
"size",
",",
"'type'",
":",
"type",
",",
"'duration'",
":",
"duration",
",",
"'datacenter_id'",
":",
"datacenter_id_",
",",
"}",
"if",
"password",
":",
"paas_params",
"[",
"'password'",
"]",
"=",
"password",
"if",
"quantity",
":",
"paas_params",
"[",
"'quantity'",
"]",
"=",
"quantity",
"paas_params",
".",
"update",
"(",
"cls",
".",
"convert_sshkey",
"(",
"sshkey",
")",
")",
"if",
"snapshot_profile",
":",
"paas_params",
"[",
"'snapshot_profile'",
"]",
"=",
"snapshot_profile",
"result",
"=",
"cls",
".",
"call",
"(",
"'paas.create'",
",",
"paas_params",
")",
"if",
"not",
"background",
":",
"# interactive mode, run a progress bar",
"cls",
".",
"echo",
"(",
"'Creating your PaaS instance.'",
")",
"cls",
".",
"display_progress",
"(",
"result",
")",
"cls",
".",
"echo",
"(",
"'Your PaaS instance %s has been created.'",
"%",
"name",
")",
"if",
"vhosts",
":",
"paas_info",
"=",
"cls",
".",
"info",
"(",
"name",
")",
"Vhost",
".",
"create",
"(",
"paas_info",
",",
"vhosts",
",",
"True",
",",
"background",
")",
"return",
"result"
] | Create a new PaaS instance. | [
"Create",
"a",
"new",
"PaaS",
"instance",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/paas.py#L237-L276 | train |
Gandi/gandi.cli | gandi/cli/modules/paas.py | Paas.console | def console(cls, id):
"""Open a console to a PaaS instance."""
oper = cls.call('paas.update', cls.usable_id(id), {'console': 1})
cls.echo('Activation of the console on your PaaS instance')
cls.display_progress(oper)
console_url = Paas.info(cls.usable_id(id))['console']
access = 'ssh %s' % console_url
cls.execute(access) | python | def console(cls, id):
"""Open a console to a PaaS instance."""
oper = cls.call('paas.update', cls.usable_id(id), {'console': 1})
cls.echo('Activation of the console on your PaaS instance')
cls.display_progress(oper)
console_url = Paas.info(cls.usable_id(id))['console']
access = 'ssh %s' % console_url
cls.execute(access) | [
"def",
"console",
"(",
"cls",
",",
"id",
")",
":",
"oper",
"=",
"cls",
".",
"call",
"(",
"'paas.update'",
",",
"cls",
".",
"usable_id",
"(",
"id",
")",
",",
"{",
"'console'",
":",
"1",
"}",
")",
"cls",
".",
"echo",
"(",
"'Activation of the console on your PaaS instance'",
")",
"cls",
".",
"display_progress",
"(",
"oper",
")",
"console_url",
"=",
"Paas",
".",
"info",
"(",
"cls",
".",
"usable_id",
"(",
"id",
")",
")",
"[",
"'console'",
"]",
"access",
"=",
"'ssh %s'",
"%",
"console_url",
"cls",
".",
"execute",
"(",
"access",
")"
] | Open a console to a PaaS instance. | [
"Open",
"a",
"console",
"to",
"a",
"PaaS",
"instance",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/paas.py#L312-L319 | train |
Gandi/gandi.cli | gandi/cli/modules/paas.py | Paas.from_vhost | def from_vhost(cls, vhost):
"""Retrieve paas instance id associated to a vhost."""
result = Vhost().list()
paas_hosts = {}
for host in result:
paas_hosts[host['name']] = host['paas_id']
return paas_hosts.get(vhost) | python | def from_vhost(cls, vhost):
"""Retrieve paas instance id associated to a vhost."""
result = Vhost().list()
paas_hosts = {}
for host in result:
paas_hosts[host['name']] = host['paas_id']
return paas_hosts.get(vhost) | [
"def",
"from_vhost",
"(",
"cls",
",",
"vhost",
")",
":",
"result",
"=",
"Vhost",
"(",
")",
".",
"list",
"(",
")",
"paas_hosts",
"=",
"{",
"}",
"for",
"host",
"in",
"result",
":",
"paas_hosts",
"[",
"host",
"[",
"'name'",
"]",
"]",
"=",
"host",
"[",
"'paas_id'",
"]",
"return",
"paas_hosts",
".",
"get",
"(",
"vhost",
")"
] | Retrieve paas instance id associated to a vhost. | [
"Retrieve",
"paas",
"instance",
"id",
"associated",
"to",
"a",
"vhost",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/paas.py#L342-L349 | train |
Gandi/gandi.cli | gandi/cli/modules/paas.py | Paas.from_hostname | def from_hostname(cls, hostname):
"""Retrieve paas instance id associated to a host."""
result = cls.list({'items_per_page': 500})
paas_hosts = {}
for host in result:
paas_hosts[host['name']] = host['id']
return paas_hosts.get(hostname) | python | def from_hostname(cls, hostname):
"""Retrieve paas instance id associated to a host."""
result = cls.list({'items_per_page': 500})
paas_hosts = {}
for host in result:
paas_hosts[host['name']] = host['id']
return paas_hosts.get(hostname) | [
"def",
"from_hostname",
"(",
"cls",
",",
"hostname",
")",
":",
"result",
"=",
"cls",
".",
"list",
"(",
"{",
"'items_per_page'",
":",
"500",
"}",
")",
"paas_hosts",
"=",
"{",
"}",
"for",
"host",
"in",
"result",
":",
"paas_hosts",
"[",
"host",
"[",
"'name'",
"]",
"]",
"=",
"host",
"[",
"'id'",
"]",
"return",
"paas_hosts",
".",
"get",
"(",
"hostname",
")"
] | Retrieve paas instance id associated to a host. | [
"Retrieve",
"paas",
"instance",
"id",
"associated",
"to",
"a",
"host",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/paas.py#L352-L359 | train |
Gandi/gandi.cli | gandi/cli/modules/paas.py | Paas.list_names | def list_names(cls):
"""Retrieve paas id and names."""
ret = dict([(item['id'], item['name'])
for item in cls.list({'items_per_page': 500})])
return ret | python | def list_names(cls):
"""Retrieve paas id and names."""
ret = dict([(item['id'], item['name'])
for item in cls.list({'items_per_page': 500})])
return ret | [
"def",
"list_names",
"(",
"cls",
")",
":",
"ret",
"=",
"dict",
"(",
"[",
"(",
"item",
"[",
"'id'",
"]",
",",
"item",
"[",
"'name'",
"]",
")",
"for",
"item",
"in",
"cls",
".",
"list",
"(",
"{",
"'items_per_page'",
":",
"500",
"}",
")",
"]",
")",
"return",
"ret"
] | Retrieve paas id and names. | [
"Retrieve",
"paas",
"id",
"and",
"names",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/paas.py#L362-L366 | train |
Gandi/gandi.cli | gandi/cli/modules/cert.py | Certificate.from_cn | def from_cn(cls, common_name):
""" Retrieve a certificate by its common name. """
# search with cn
result_cn = [(cert['id'], [cert['cn']] + cert['altnames'])
for cert in cls.list({'status': ['pending', 'valid'],
'items_per_page': 500,
'cn': common_name})]
# search with altname
result_alt = [(cert['id'], [cert['cn']] + cert['altnames'])
for cert in cls.list({'status': ['pending', 'valid'],
'items_per_page': 500,
'altname': common_name})]
result = result_cn + result_alt
ret = {}
for id_, fqdns in result:
for fqdn in fqdns:
ret.setdefault(fqdn, []).append(id_)
cert_id = ret.get(common_name)
if not cert_id:
return
return cert_id | python | def from_cn(cls, common_name):
""" Retrieve a certificate by its common name. """
# search with cn
result_cn = [(cert['id'], [cert['cn']] + cert['altnames'])
for cert in cls.list({'status': ['pending', 'valid'],
'items_per_page': 500,
'cn': common_name})]
# search with altname
result_alt = [(cert['id'], [cert['cn']] + cert['altnames'])
for cert in cls.list({'status': ['pending', 'valid'],
'items_per_page': 500,
'altname': common_name})]
result = result_cn + result_alt
ret = {}
for id_, fqdns in result:
for fqdn in fqdns:
ret.setdefault(fqdn, []).append(id_)
cert_id = ret.get(common_name)
if not cert_id:
return
return cert_id | [
"def",
"from_cn",
"(",
"cls",
",",
"common_name",
")",
":",
"# search with cn",
"result_cn",
"=",
"[",
"(",
"cert",
"[",
"'id'",
"]",
",",
"[",
"cert",
"[",
"'cn'",
"]",
"]",
"+",
"cert",
"[",
"'altnames'",
"]",
")",
"for",
"cert",
"in",
"cls",
".",
"list",
"(",
"{",
"'status'",
":",
"[",
"'pending'",
",",
"'valid'",
"]",
",",
"'items_per_page'",
":",
"500",
",",
"'cn'",
":",
"common_name",
"}",
")",
"]",
"# search with altname",
"result_alt",
"=",
"[",
"(",
"cert",
"[",
"'id'",
"]",
",",
"[",
"cert",
"[",
"'cn'",
"]",
"]",
"+",
"cert",
"[",
"'altnames'",
"]",
")",
"for",
"cert",
"in",
"cls",
".",
"list",
"(",
"{",
"'status'",
":",
"[",
"'pending'",
",",
"'valid'",
"]",
",",
"'items_per_page'",
":",
"500",
",",
"'altname'",
":",
"common_name",
"}",
")",
"]",
"result",
"=",
"result_cn",
"+",
"result_alt",
"ret",
"=",
"{",
"}",
"for",
"id_",
",",
"fqdns",
"in",
"result",
":",
"for",
"fqdn",
"in",
"fqdns",
":",
"ret",
".",
"setdefault",
"(",
"fqdn",
",",
"[",
"]",
")",
".",
"append",
"(",
"id_",
")",
"cert_id",
"=",
"ret",
".",
"get",
"(",
"common_name",
")",
"if",
"not",
"cert_id",
":",
"return",
"return",
"cert_id"
] | Retrieve a certificate by its common name. | [
"Retrieve",
"a",
"certificate",
"by",
"its",
"common",
"name",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/cert.py#L121-L144 | train |
Gandi/gandi.cli | gandi/cli/modules/cert.py | Certificate.usable_ids | def usable_ids(cls, id, accept_multi=True):
""" Retrieve id from input which can be an id or a cn."""
try:
qry_id = [int(id)]
except ValueError:
try:
qry_id = cls.from_cn(id)
except Exception:
qry_id = None
if not qry_id or not accept_multi and len(qry_id) != 1:
msg = 'unknown identifier %s' % id
cls.error(msg)
return qry_id if accept_multi else qry_id[0] | python | def usable_ids(cls, id, accept_multi=True):
""" Retrieve id from input which can be an id or a cn."""
try:
qry_id = [int(id)]
except ValueError:
try:
qry_id = cls.from_cn(id)
except Exception:
qry_id = None
if not qry_id or not accept_multi and len(qry_id) != 1:
msg = 'unknown identifier %s' % id
cls.error(msg)
return qry_id if accept_multi else qry_id[0] | [
"def",
"usable_ids",
"(",
"cls",
",",
"id",
",",
"accept_multi",
"=",
"True",
")",
":",
"try",
":",
"qry_id",
"=",
"[",
"int",
"(",
"id",
")",
"]",
"except",
"ValueError",
":",
"try",
":",
"qry_id",
"=",
"cls",
".",
"from_cn",
"(",
"id",
")",
"except",
"Exception",
":",
"qry_id",
"=",
"None",
"if",
"not",
"qry_id",
"or",
"not",
"accept_multi",
"and",
"len",
"(",
"qry_id",
")",
"!=",
"1",
":",
"msg",
"=",
"'unknown identifier %s'",
"%",
"id",
"cls",
".",
"error",
"(",
"msg",
")",
"return",
"qry_id",
"if",
"accept_multi",
"else",
"qry_id",
"[",
"0",
"]"
] | Retrieve id from input which can be an id or a cn. | [
"Retrieve",
"id",
"from",
"input",
"which",
"can",
"be",
"an",
"id",
"or",
"a",
"cn",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/cert.py#L147-L161 | train |
Gandi/gandi.cli | gandi/cli/modules/cert.py | Certificate.package_list | def package_list(cls, options=None):
""" List possible certificate packages."""
options = options or {}
try:
return cls.safe_call('cert.package.list', options)
except UsageError as err:
if err.code == 150020:
return []
raise | python | def package_list(cls, options=None):
""" List possible certificate packages."""
options = options or {}
try:
return cls.safe_call('cert.package.list', options)
except UsageError as err:
if err.code == 150020:
return []
raise | [
"def",
"package_list",
"(",
"cls",
",",
"options",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"try",
":",
"return",
"cls",
".",
"safe_call",
"(",
"'cert.package.list'",
",",
"options",
")",
"except",
"UsageError",
"as",
"err",
":",
"if",
"err",
".",
"code",
"==",
"150020",
":",
"return",
"[",
"]",
"raise"
] | List possible certificate packages. | [
"List",
"possible",
"certificate",
"packages",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/cert.py#L169-L177 | train |
Gandi/gandi.cli | gandi/cli/modules/cert.py | Certificate.advice_dcv_method | def advice_dcv_method(cls, csr, package, altnames, dcv_method,
cert_id=None):
""" Display dcv_method information. """
params = {'csr': csr, 'package': package, 'dcv_method': dcv_method}
if cert_id:
params['cert_id'] = cert_id
result = cls.call('cert.get_dcv_params', params)
if dcv_method == 'dns':
cls.echo('You have to add these records in your domain zone :')
cls.echo('\n'.join(result['message'])) | python | def advice_dcv_method(cls, csr, package, altnames, dcv_method,
cert_id=None):
""" Display dcv_method information. """
params = {'csr': csr, 'package': package, 'dcv_method': dcv_method}
if cert_id:
params['cert_id'] = cert_id
result = cls.call('cert.get_dcv_params', params)
if dcv_method == 'dns':
cls.echo('You have to add these records in your domain zone :')
cls.echo('\n'.join(result['message'])) | [
"def",
"advice_dcv_method",
"(",
"cls",
",",
"csr",
",",
"package",
",",
"altnames",
",",
"dcv_method",
",",
"cert_id",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'csr'",
":",
"csr",
",",
"'package'",
":",
"package",
",",
"'dcv_method'",
":",
"dcv_method",
"}",
"if",
"cert_id",
":",
"params",
"[",
"'cert_id'",
"]",
"=",
"cert_id",
"result",
"=",
"cls",
".",
"call",
"(",
"'cert.get_dcv_params'",
",",
"params",
")",
"if",
"dcv_method",
"==",
"'dns'",
":",
"cls",
".",
"echo",
"(",
"'You have to add these records in your domain zone :'",
")",
"cls",
".",
"echo",
"(",
"'\\n'",
".",
"join",
"(",
"result",
"[",
"'message'",
"]",
")",
")"
] | Display dcv_method information. | [
"Display",
"dcv_method",
"information",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/cert.py#L236-L245 | train |
Gandi/gandi.cli | gandi/cli/modules/cert.py | Certificate.create_csr | def create_csr(cls, common_name, private_key=None, params=None):
""" Create CSR. """
params = params or []
params = [(key, val) for key, val in params if val]
subj = '/' + '/'.join(['='.join(value) for value in params])
cmd, private_key = cls.gen_pk(common_name, private_key)
if private_key.endswith('.crt') or private_key.endswith('.key'):
csr_file = re.sub(r'\.(crt|key)$', '.csr', private_key)
else:
csr_file = private_key + '.csr'
cmd = cmd % {'csr': csr_file, 'key': private_key, 'subj': subj}
result = cls.execute(cmd)
if not result:
cls.echo('CSR creation failed')
cls.echo(cmd)
return
return csr_file | python | def create_csr(cls, common_name, private_key=None, params=None):
""" Create CSR. """
params = params or []
params = [(key, val) for key, val in params if val]
subj = '/' + '/'.join(['='.join(value) for value in params])
cmd, private_key = cls.gen_pk(common_name, private_key)
if private_key.endswith('.crt') or private_key.endswith('.key'):
csr_file = re.sub(r'\.(crt|key)$', '.csr', private_key)
else:
csr_file = private_key + '.csr'
cmd = cmd % {'csr': csr_file, 'key': private_key, 'subj': subj}
result = cls.execute(cmd)
if not result:
cls.echo('CSR creation failed')
cls.echo(cmd)
return
return csr_file | [
"def",
"create_csr",
"(",
"cls",
",",
"common_name",
",",
"private_key",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"params",
"or",
"[",
"]",
"params",
"=",
"[",
"(",
"key",
",",
"val",
")",
"for",
"key",
",",
"val",
"in",
"params",
"if",
"val",
"]",
"subj",
"=",
"'/'",
"+",
"'/'",
".",
"join",
"(",
"[",
"'='",
".",
"join",
"(",
"value",
")",
"for",
"value",
"in",
"params",
"]",
")",
"cmd",
",",
"private_key",
"=",
"cls",
".",
"gen_pk",
"(",
"common_name",
",",
"private_key",
")",
"if",
"private_key",
".",
"endswith",
"(",
"'.crt'",
")",
"or",
"private_key",
".",
"endswith",
"(",
"'.key'",
")",
":",
"csr_file",
"=",
"re",
".",
"sub",
"(",
"r'\\.(crt|key)$'",
",",
"'.csr'",
",",
"private_key",
")",
"else",
":",
"csr_file",
"=",
"private_key",
"+",
"'.csr'",
"cmd",
"=",
"cmd",
"%",
"{",
"'csr'",
":",
"csr_file",
",",
"'key'",
":",
"private_key",
",",
"'subj'",
":",
"subj",
"}",
"result",
"=",
"cls",
".",
"execute",
"(",
"cmd",
")",
"if",
"not",
"result",
":",
"cls",
".",
"echo",
"(",
"'CSR creation failed'",
")",
"cls",
".",
"echo",
"(",
"cmd",
")",
"return",
"return",
"csr_file"
] | Create CSR. | [
"Create",
"CSR",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/cert.py#L337-L358 | train |
Gandi/gandi.cli | gandi/cli/modules/cert.py | Certificate.get_common_name | def get_common_name(cls, csr):
""" Read information from CSR. """
from tempfile import NamedTemporaryFile
fhandle = NamedTemporaryFile()
fhandle.write(csr.encode('latin1'))
fhandle.flush()
output = cls.exec_output('openssl req -noout -subject -in %s' %
fhandle.name)
if not output:
return
common_name = output.split('=')[-1].strip()
fhandle.close()
return common_name | python | def get_common_name(cls, csr):
""" Read information from CSR. """
from tempfile import NamedTemporaryFile
fhandle = NamedTemporaryFile()
fhandle.write(csr.encode('latin1'))
fhandle.flush()
output = cls.exec_output('openssl req -noout -subject -in %s' %
fhandle.name)
if not output:
return
common_name = output.split('=')[-1].strip()
fhandle.close()
return common_name | [
"def",
"get_common_name",
"(",
"cls",
",",
"csr",
")",
":",
"from",
"tempfile",
"import",
"NamedTemporaryFile",
"fhandle",
"=",
"NamedTemporaryFile",
"(",
")",
"fhandle",
".",
"write",
"(",
"csr",
".",
"encode",
"(",
"'latin1'",
")",
")",
"fhandle",
".",
"flush",
"(",
")",
"output",
"=",
"cls",
".",
"exec_output",
"(",
"'openssl req -noout -subject -in %s'",
"%",
"fhandle",
".",
"name",
")",
"if",
"not",
"output",
":",
"return",
"common_name",
"=",
"output",
".",
"split",
"(",
"'='",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"fhandle",
".",
"close",
"(",
")",
"return",
"common_name"
] | Read information from CSR. | [
"Read",
"information",
"from",
"CSR",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/cert.py#L361-L374 | train |
Gandi/gandi.cli | gandi/cli/modules/cert.py | Certificate.process_csr | def process_csr(cls, common_name, csr=None, private_key=None,
country=None, state=None, city=None, organisation=None,
branch=None):
""" Create a PK and a CSR if needed."""
if csr:
if branch or organisation or city or state or country:
cls.echo('Following options are only used to generate'
' the CSR.')
else:
params = (('CN', common_name),
('OU', branch),
('O', organisation),
('L', city),
('ST', state),
('C', country))
params = [(key, val) for key, val in params if val]
csr = cls.create_csr(common_name, private_key, params)
if csr and os.path.exists(csr):
with open(csr) as fcsr:
csr = fcsr.read()
return csr | python | def process_csr(cls, common_name, csr=None, private_key=None,
country=None, state=None, city=None, organisation=None,
branch=None):
""" Create a PK and a CSR if needed."""
if csr:
if branch or organisation or city or state or country:
cls.echo('Following options are only used to generate'
' the CSR.')
else:
params = (('CN', common_name),
('OU', branch),
('O', organisation),
('L', city),
('ST', state),
('C', country))
params = [(key, val) for key, val in params if val]
csr = cls.create_csr(common_name, private_key, params)
if csr and os.path.exists(csr):
with open(csr) as fcsr:
csr = fcsr.read()
return csr | [
"def",
"process_csr",
"(",
"cls",
",",
"common_name",
",",
"csr",
"=",
"None",
",",
"private_key",
"=",
"None",
",",
"country",
"=",
"None",
",",
"state",
"=",
"None",
",",
"city",
"=",
"None",
",",
"organisation",
"=",
"None",
",",
"branch",
"=",
"None",
")",
":",
"if",
"csr",
":",
"if",
"branch",
"or",
"organisation",
"or",
"city",
"or",
"state",
"or",
"country",
":",
"cls",
".",
"echo",
"(",
"'Following options are only used to generate'",
"' the CSR.'",
")",
"else",
":",
"params",
"=",
"(",
"(",
"'CN'",
",",
"common_name",
")",
",",
"(",
"'OU'",
",",
"branch",
")",
",",
"(",
"'O'",
",",
"organisation",
")",
",",
"(",
"'L'",
",",
"city",
")",
",",
"(",
"'ST'",
",",
"state",
")",
",",
"(",
"'C'",
",",
"country",
")",
")",
"params",
"=",
"[",
"(",
"key",
",",
"val",
")",
"for",
"key",
",",
"val",
"in",
"params",
"if",
"val",
"]",
"csr",
"=",
"cls",
".",
"create_csr",
"(",
"common_name",
",",
"private_key",
",",
"params",
")",
"if",
"csr",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"csr",
")",
":",
"with",
"open",
"(",
"csr",
")",
"as",
"fcsr",
":",
"csr",
"=",
"fcsr",
".",
"read",
"(",
")",
"return",
"csr"
] | Create a PK and a CSR if needed. | [
"Create",
"a",
"PK",
"and",
"a",
"CSR",
"if",
"needed",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/cert.py#L377-L399 | train |
Gandi/gandi.cli | gandi/cli/modules/cert.py | Certificate.pretty_format_cert | def pretty_format_cert(cls, cert):
""" Pretty display of a certificate."""
crt = cert.get('cert')
if crt:
crt = ('-----BEGIN CERTIFICATE-----\n' +
'\n'.join([crt[index * 64:(index + 1) * 64]
for index in range(int(len(crt) / 64) + 1)]).rstrip('\n') + # noqa
'\n-----END CERTIFICATE-----')
return crt | python | def pretty_format_cert(cls, cert):
""" Pretty display of a certificate."""
crt = cert.get('cert')
if crt:
crt = ('-----BEGIN CERTIFICATE-----\n' +
'\n'.join([crt[index * 64:(index + 1) * 64]
for index in range(int(len(crt) / 64) + 1)]).rstrip('\n') + # noqa
'\n-----END CERTIFICATE-----')
return crt | [
"def",
"pretty_format_cert",
"(",
"cls",
",",
"cert",
")",
":",
"crt",
"=",
"cert",
".",
"get",
"(",
"'cert'",
")",
"if",
"crt",
":",
"crt",
"=",
"(",
"'-----BEGIN CERTIFICATE-----\\n'",
"+",
"'\\n'",
".",
"join",
"(",
"[",
"crt",
"[",
"index",
"*",
"64",
":",
"(",
"index",
"+",
"1",
")",
"*",
"64",
"]",
"for",
"index",
"in",
"range",
"(",
"int",
"(",
"len",
"(",
"crt",
")",
"/",
"64",
")",
"+",
"1",
")",
"]",
")",
".",
"rstrip",
"(",
"'\\n'",
")",
"+",
"# noqa",
"'\\n-----END CERTIFICATE-----'",
")",
"return",
"crt"
] | Pretty display of a certificate. | [
"Pretty",
"display",
"of",
"a",
"certificate",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/cert.py#L402-L410 | train |
Gandi/gandi.cli | gandi/cli/commands/webacc.py | info | def info(gandi, resource, format):
""" Display information about a webaccelerator """
result = gandi.webacc.info(resource)
if format:
output_json(gandi, format, result)
return result
output_base = {
'name': result['name'],
'algorithm': result['lb']['algorithm'],
'datacenter': result['datacenter']['name'],
'state': result['state'],
'ssl': 'Disable' if result['ssl_enable'] is False else 'Enabled'
}
output_keys = ['name', 'state', 'datacenter', 'ssl', 'algorithm']
output_generic(gandi, output_base, output_keys, justify=14)
gandi.echo('Vhosts :')
for vhost in result['vhosts']:
output_vhosts = ['vhost', 'ssl']
vhost['vhost'] = vhost['name']
vhost['ssl'] = 'None' if vhost['cert_id'] is None else 'Exists'
output_sub_generic(gandi, vhost, output_vhosts, justify=14)
gandi.echo('')
gandi.echo('Backends :')
for server in result['servers']:
try:
ip = gandi.ip.info(server['ip'])
iface = gandi.iface.info(ip['iface_id'])
server['name'] = gandi.iaas.info(iface['vm_id'])['hostname']
output_servers = ['name', 'ip', 'port', 'state']
except Exception:
warningmsg = ('\tBackend with ip address %s no longer exists.'
'\n\tYou should remove it.' % server['ip'])
gandi.echo(warningmsg)
output_servers = ['ip', 'port', 'state']
output_sub_generic(gandi, server, output_servers, justify=14)
gandi.echo('')
gandi.echo('Probe :')
output_probe = ['state', 'host', 'interval', 'method', 'response',
'threshold', 'timeout', 'url', 'window']
result['probe']['state'] = ('Disable'
if result['probe']['enable'] is False
else 'Enabled')
output_sub_generic(gandi, result['probe'], output_probe, justify=14)
return result | python | def info(gandi, resource, format):
""" Display information about a webaccelerator """
result = gandi.webacc.info(resource)
if format:
output_json(gandi, format, result)
return result
output_base = {
'name': result['name'],
'algorithm': result['lb']['algorithm'],
'datacenter': result['datacenter']['name'],
'state': result['state'],
'ssl': 'Disable' if result['ssl_enable'] is False else 'Enabled'
}
output_keys = ['name', 'state', 'datacenter', 'ssl', 'algorithm']
output_generic(gandi, output_base, output_keys, justify=14)
gandi.echo('Vhosts :')
for vhost in result['vhosts']:
output_vhosts = ['vhost', 'ssl']
vhost['vhost'] = vhost['name']
vhost['ssl'] = 'None' if vhost['cert_id'] is None else 'Exists'
output_sub_generic(gandi, vhost, output_vhosts, justify=14)
gandi.echo('')
gandi.echo('Backends :')
for server in result['servers']:
try:
ip = gandi.ip.info(server['ip'])
iface = gandi.iface.info(ip['iface_id'])
server['name'] = gandi.iaas.info(iface['vm_id'])['hostname']
output_servers = ['name', 'ip', 'port', 'state']
except Exception:
warningmsg = ('\tBackend with ip address %s no longer exists.'
'\n\tYou should remove it.' % server['ip'])
gandi.echo(warningmsg)
output_servers = ['ip', 'port', 'state']
output_sub_generic(gandi, server, output_servers, justify=14)
gandi.echo('')
gandi.echo('Probe :')
output_probe = ['state', 'host', 'interval', 'method', 'response',
'threshold', 'timeout', 'url', 'window']
result['probe']['state'] = ('Disable'
if result['probe']['enable'] is False
else 'Enabled')
output_sub_generic(gandi, result['probe'], output_probe, justify=14)
return result | [
"def",
"info",
"(",
"gandi",
",",
"resource",
",",
"format",
")",
":",
"result",
"=",
"gandi",
".",
"webacc",
".",
"info",
"(",
"resource",
")",
"if",
"format",
":",
"output_json",
"(",
"gandi",
",",
"format",
",",
"result",
")",
"return",
"result",
"output_base",
"=",
"{",
"'name'",
":",
"result",
"[",
"'name'",
"]",
",",
"'algorithm'",
":",
"result",
"[",
"'lb'",
"]",
"[",
"'algorithm'",
"]",
",",
"'datacenter'",
":",
"result",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
",",
"'state'",
":",
"result",
"[",
"'state'",
"]",
",",
"'ssl'",
":",
"'Disable'",
"if",
"result",
"[",
"'ssl_enable'",
"]",
"is",
"False",
"else",
"'Enabled'",
"}",
"output_keys",
"=",
"[",
"'name'",
",",
"'state'",
",",
"'datacenter'",
",",
"'ssl'",
",",
"'algorithm'",
"]",
"output_generic",
"(",
"gandi",
",",
"output_base",
",",
"output_keys",
",",
"justify",
"=",
"14",
")",
"gandi",
".",
"echo",
"(",
"'Vhosts :'",
")",
"for",
"vhost",
"in",
"result",
"[",
"'vhosts'",
"]",
":",
"output_vhosts",
"=",
"[",
"'vhost'",
",",
"'ssl'",
"]",
"vhost",
"[",
"'vhost'",
"]",
"=",
"vhost",
"[",
"'name'",
"]",
"vhost",
"[",
"'ssl'",
"]",
"=",
"'None'",
"if",
"vhost",
"[",
"'cert_id'",
"]",
"is",
"None",
"else",
"'Exists'",
"output_sub_generic",
"(",
"gandi",
",",
"vhost",
",",
"output_vhosts",
",",
"justify",
"=",
"14",
")",
"gandi",
".",
"echo",
"(",
"''",
")",
"gandi",
".",
"echo",
"(",
"'Backends :'",
")",
"for",
"server",
"in",
"result",
"[",
"'servers'",
"]",
":",
"try",
":",
"ip",
"=",
"gandi",
".",
"ip",
".",
"info",
"(",
"server",
"[",
"'ip'",
"]",
")",
"iface",
"=",
"gandi",
".",
"iface",
".",
"info",
"(",
"ip",
"[",
"'iface_id'",
"]",
")",
"server",
"[",
"'name'",
"]",
"=",
"gandi",
".",
"iaas",
".",
"info",
"(",
"iface",
"[",
"'vm_id'",
"]",
")",
"[",
"'hostname'",
"]",
"output_servers",
"=",
"[",
"'name'",
",",
"'ip'",
",",
"'port'",
",",
"'state'",
"]",
"except",
"Exception",
":",
"warningmsg",
"=",
"(",
"'\\tBackend with ip address %s no longer exists.'",
"'\\n\\tYou should remove it.'",
"%",
"server",
"[",
"'ip'",
"]",
")",
"gandi",
".",
"echo",
"(",
"warningmsg",
")",
"output_servers",
"=",
"[",
"'ip'",
",",
"'port'",
",",
"'state'",
"]",
"output_sub_generic",
"(",
"gandi",
",",
"server",
",",
"output_servers",
",",
"justify",
"=",
"14",
")",
"gandi",
".",
"echo",
"(",
"''",
")",
"gandi",
".",
"echo",
"(",
"'Probe :'",
")",
"output_probe",
"=",
"[",
"'state'",
",",
"'host'",
",",
"'interval'",
",",
"'method'",
",",
"'response'",
",",
"'threshold'",
",",
"'timeout'",
",",
"'url'",
",",
"'window'",
"]",
"result",
"[",
"'probe'",
"]",
"[",
"'state'",
"]",
"=",
"(",
"'Disable'",
"if",
"result",
"[",
"'probe'",
"]",
"[",
"'enable'",
"]",
"is",
"False",
"else",
"'Enabled'",
")",
"output_sub_generic",
"(",
"gandi",
",",
"result",
"[",
"'probe'",
"]",
",",
"output_probe",
",",
"justify",
"=",
"14",
")",
"return",
"result"
] | Display information about a webaccelerator | [
"Display",
"information",
"about",
"a",
"webaccelerator"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/webacc.py#L80-L127 | train |
Gandi/gandi.cli | gandi/cli/commands/webacc.py | delete | def delete(gandi, webacc, vhost, backend, port):
""" Delete a webaccelerator, a vhost or a backend """
result = []
if webacc:
result = gandi.webacc.delete(webacc)
if backend:
backends = backend
for backend in backends:
if 'port' not in backend:
if not port:
backend['port'] = click.prompt('Please set a port for '
'backends. If you want to '
' different port for '
'each backend, use `-b '
'ip:port`', type=int)
else:
backend['port'] = port
result = gandi.webacc.backend_remove(backend)
if vhost:
vhosts = vhost
for vhost in vhosts:
result = gandi.webacc.vhost_remove(vhost)
return result | python | def delete(gandi, webacc, vhost, backend, port):
""" Delete a webaccelerator, a vhost or a backend """
result = []
if webacc:
result = gandi.webacc.delete(webacc)
if backend:
backends = backend
for backend in backends:
if 'port' not in backend:
if not port:
backend['port'] = click.prompt('Please set a port for '
'backends. If you want to '
' different port for '
'each backend, use `-b '
'ip:port`', type=int)
else:
backend['port'] = port
result = gandi.webacc.backend_remove(backend)
if vhost:
vhosts = vhost
for vhost in vhosts:
result = gandi.webacc.vhost_remove(vhost)
return result | [
"def",
"delete",
"(",
"gandi",
",",
"webacc",
",",
"vhost",
",",
"backend",
",",
"port",
")",
":",
"result",
"=",
"[",
"]",
"if",
"webacc",
":",
"result",
"=",
"gandi",
".",
"webacc",
".",
"delete",
"(",
"webacc",
")",
"if",
"backend",
":",
"backends",
"=",
"backend",
"for",
"backend",
"in",
"backends",
":",
"if",
"'port'",
"not",
"in",
"backend",
":",
"if",
"not",
"port",
":",
"backend",
"[",
"'port'",
"]",
"=",
"click",
".",
"prompt",
"(",
"'Please set a port for '",
"'backends. If you want to '",
"' different port for '",
"'each backend, use `-b '",
"'ip:port`'",
",",
"type",
"=",
"int",
")",
"else",
":",
"backend",
"[",
"'port'",
"]",
"=",
"port",
"result",
"=",
"gandi",
".",
"webacc",
".",
"backend_remove",
"(",
"backend",
")",
"if",
"vhost",
":",
"vhosts",
"=",
"vhost",
"for",
"vhost",
"in",
"vhosts",
":",
"result",
"=",
"gandi",
".",
"webacc",
".",
"vhost_remove",
"(",
"vhost",
")",
"return",
"result"
] | Delete a webaccelerator, a vhost or a backend | [
"Delete",
"a",
"webaccelerator",
"a",
"vhost",
"or",
"a",
"backend"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/webacc.py#L215-L240 | train |
Gandi/gandi.cli | gandi/cli/commands/webacc.py | add | def add(gandi, resource, vhost, zone_alter, backend, port, ssl, private_key,
poll_cert):
""" Add a backend or a vhost on a webaccelerator """
result = []
if backend:
backends = backend
for backend in backends:
# Check if a port is set for each backend, else set a default port
if 'port' not in backend:
if not port:
backend['port'] = click.prompt('Please set a port for '
'backends. If you want to '
' different port for '
'each backend, use `-b '
'ip:port`', type=int)
else:
backend['port'] = port
result = gandi.webacc.backend_add(resource, backend)
if vhost:
if not gandi.hostedcert.activate_ssl(vhost, ssl, private_key,
poll_cert):
return
vhosts = vhost
for vhost in vhosts:
params = {'vhost': vhost}
if zone_alter:
params['zone_alter'] = zone_alter
result = gandi.webacc.vhost_add(resource, params)
return result | python | def add(gandi, resource, vhost, zone_alter, backend, port, ssl, private_key,
poll_cert):
""" Add a backend or a vhost on a webaccelerator """
result = []
if backend:
backends = backend
for backend in backends:
# Check if a port is set for each backend, else set a default port
if 'port' not in backend:
if not port:
backend['port'] = click.prompt('Please set a port for '
'backends. If you want to '
' different port for '
'each backend, use `-b '
'ip:port`', type=int)
else:
backend['port'] = port
result = gandi.webacc.backend_add(resource, backend)
if vhost:
if not gandi.hostedcert.activate_ssl(vhost, ssl, private_key,
poll_cert):
return
vhosts = vhost
for vhost in vhosts:
params = {'vhost': vhost}
if zone_alter:
params['zone_alter'] = zone_alter
result = gandi.webacc.vhost_add(resource, params)
return result | [
"def",
"add",
"(",
"gandi",
",",
"resource",
",",
"vhost",
",",
"zone_alter",
",",
"backend",
",",
"port",
",",
"ssl",
",",
"private_key",
",",
"poll_cert",
")",
":",
"result",
"=",
"[",
"]",
"if",
"backend",
":",
"backends",
"=",
"backend",
"for",
"backend",
"in",
"backends",
":",
"# Check if a port is set for each backend, else set a default port",
"if",
"'port'",
"not",
"in",
"backend",
":",
"if",
"not",
"port",
":",
"backend",
"[",
"'port'",
"]",
"=",
"click",
".",
"prompt",
"(",
"'Please set a port for '",
"'backends. If you want to '",
"' different port for '",
"'each backend, use `-b '",
"'ip:port`'",
",",
"type",
"=",
"int",
")",
"else",
":",
"backend",
"[",
"'port'",
"]",
"=",
"port",
"result",
"=",
"gandi",
".",
"webacc",
".",
"backend_add",
"(",
"resource",
",",
"backend",
")",
"if",
"vhost",
":",
"if",
"not",
"gandi",
".",
"hostedcert",
".",
"activate_ssl",
"(",
"vhost",
",",
"ssl",
",",
"private_key",
",",
"poll_cert",
")",
":",
"return",
"vhosts",
"=",
"vhost",
"for",
"vhost",
"in",
"vhosts",
":",
"params",
"=",
"{",
"'vhost'",
":",
"vhost",
"}",
"if",
"zone_alter",
":",
"params",
"[",
"'zone_alter'",
"]",
"=",
"zone_alter",
"result",
"=",
"gandi",
".",
"webacc",
".",
"vhost_add",
"(",
"resource",
",",
"params",
")",
"return",
"result"
] | Add a backend or a vhost on a webaccelerator | [
"Add",
"a",
"backend",
"or",
"a",
"vhost",
"on",
"a",
"webaccelerator"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/webacc.py#L260-L289 | train |
Gandi/gandi.cli | gandi/cli/commands/webacc.py | enable | def enable(gandi, resource, backend, port, probe):
""" Enable a backend or a probe on a webaccelerator """
result = []
if backend:
backends = backend
for backend in backends:
if 'port' not in backend:
if not port:
backend['port'] = click.prompt('Please set a port for '
'backends. If you want to '
' different port for '
'each backend, use `-b '
'ip:port`', type=int)
else:
backend['port'] = port
result = gandi.webacc.backend_enable(backend)
if probe:
if not resource:
gandi.echo('You need to indicate the Webaccelerator name')
return
result = gandi.webacc.probe_enable(resource)
return result | python | def enable(gandi, resource, backend, port, probe):
""" Enable a backend or a probe on a webaccelerator """
result = []
if backend:
backends = backend
for backend in backends:
if 'port' not in backend:
if not port:
backend['port'] = click.prompt('Please set a port for '
'backends. If you want to '
' different port for '
'each backend, use `-b '
'ip:port`', type=int)
else:
backend['port'] = port
result = gandi.webacc.backend_enable(backend)
if probe:
if not resource:
gandi.echo('You need to indicate the Webaccelerator name')
return
result = gandi.webacc.probe_enable(resource)
return result | [
"def",
"enable",
"(",
"gandi",
",",
"resource",
",",
"backend",
",",
"port",
",",
"probe",
")",
":",
"result",
"=",
"[",
"]",
"if",
"backend",
":",
"backends",
"=",
"backend",
"for",
"backend",
"in",
"backends",
":",
"if",
"'port'",
"not",
"in",
"backend",
":",
"if",
"not",
"port",
":",
"backend",
"[",
"'port'",
"]",
"=",
"click",
".",
"prompt",
"(",
"'Please set a port for '",
"'backends. If you want to '",
"' different port for '",
"'each backend, use `-b '",
"'ip:port`'",
",",
"type",
"=",
"int",
")",
"else",
":",
"backend",
"[",
"'port'",
"]",
"=",
"port",
"result",
"=",
"gandi",
".",
"webacc",
".",
"backend_enable",
"(",
"backend",
")",
"if",
"probe",
":",
"if",
"not",
"resource",
":",
"gandi",
".",
"echo",
"(",
"'You need to indicate the Webaccelerator name'",
")",
"return",
"result",
"=",
"gandi",
".",
"webacc",
".",
"probe_enable",
"(",
"resource",
")",
"return",
"result"
] | Enable a backend or a probe on a webaccelerator | [
"Enable",
"a",
"backend",
"or",
"a",
"probe",
"on",
"a",
"webaccelerator"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/webacc.py#L301-L324 | train |
Gandi/gandi.cli | gandi/cli/commands/webacc.py | disable | def disable(gandi, resource, backend, port, probe):
""" Disable a backend or a probe on a webaccelerator """
result = []
if backend:
backends = backend
for backend in backends:
if 'port' not in backend:
if not port:
backend['port'] = click.prompt('Please set a port for '
'backends. If you want to '
' different port for '
'each backend, use `-b '
'ip:port`', type=int)
else:
backend['port'] = port
result = gandi.webacc.backend_disable(backend)
if probe:
if not resource:
gandi.echo('You need to indicate the Webaccelerator name')
return
result = gandi.webacc.probe_disable(resource)
return result | python | def disable(gandi, resource, backend, port, probe):
""" Disable a backend or a probe on a webaccelerator """
result = []
if backend:
backends = backend
for backend in backends:
if 'port' not in backend:
if not port:
backend['port'] = click.prompt('Please set a port for '
'backends. If you want to '
' different port for '
'each backend, use `-b '
'ip:port`', type=int)
else:
backend['port'] = port
result = gandi.webacc.backend_disable(backend)
if probe:
if not resource:
gandi.echo('You need to indicate the Webaccelerator name')
return
result = gandi.webacc.probe_disable(resource)
return result | [
"def",
"disable",
"(",
"gandi",
",",
"resource",
",",
"backend",
",",
"port",
",",
"probe",
")",
":",
"result",
"=",
"[",
"]",
"if",
"backend",
":",
"backends",
"=",
"backend",
"for",
"backend",
"in",
"backends",
":",
"if",
"'port'",
"not",
"in",
"backend",
":",
"if",
"not",
"port",
":",
"backend",
"[",
"'port'",
"]",
"=",
"click",
".",
"prompt",
"(",
"'Please set a port for '",
"'backends. If you want to '",
"' different port for '",
"'each backend, use `-b '",
"'ip:port`'",
",",
"type",
"=",
"int",
")",
"else",
":",
"backend",
"[",
"'port'",
"]",
"=",
"port",
"result",
"=",
"gandi",
".",
"webacc",
".",
"backend_disable",
"(",
"backend",
")",
"if",
"probe",
":",
"if",
"not",
"resource",
":",
"gandi",
".",
"echo",
"(",
"'You need to indicate the Webaccelerator name'",
")",
"return",
"result",
"=",
"gandi",
".",
"webacc",
".",
"probe_disable",
"(",
"resource",
")",
"return",
"result"
] | Disable a backend or a probe on a webaccelerator | [
"Disable",
"a",
"backend",
"or",
"a",
"probe",
"on",
"a",
"webaccelerator"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/webacc.py#L336-L359 | train |
Gandi/gandi.cli | gandi/cli/commands/webacc.py | probe | def probe(gandi, resource, enable, disable, test, host, interval, http_method,
http_response, threshold, timeout, url, window):
""" Manage a probe for a webaccelerator """
result = gandi.webacc.probe(resource, enable, disable, test, host,
interval, http_method, http_response,
threshold, timeout, url, window)
output_keys = ['status', 'timeout']
output_generic(gandi, result, output_keys, justify=14)
return result | python | def probe(gandi, resource, enable, disable, test, host, interval, http_method,
http_response, threshold, timeout, url, window):
""" Manage a probe for a webaccelerator """
result = gandi.webacc.probe(resource, enable, disable, test, host,
interval, http_method, http_response,
threshold, timeout, url, window)
output_keys = ['status', 'timeout']
output_generic(gandi, result, output_keys, justify=14)
return result | [
"def",
"probe",
"(",
"gandi",
",",
"resource",
",",
"enable",
",",
"disable",
",",
"test",
",",
"host",
",",
"interval",
",",
"http_method",
",",
"http_response",
",",
"threshold",
",",
"timeout",
",",
"url",
",",
"window",
")",
":",
"result",
"=",
"gandi",
".",
"webacc",
".",
"probe",
"(",
"resource",
",",
"enable",
",",
"disable",
",",
"test",
",",
"host",
",",
"interval",
",",
"http_method",
",",
"http_response",
",",
"threshold",
",",
"timeout",
",",
"url",
",",
"window",
")",
"output_keys",
"=",
"[",
"'status'",
",",
"'timeout'",
"]",
"output_generic",
"(",
"gandi",
",",
"result",
",",
"output_keys",
",",
"justify",
"=",
"14",
")",
"return",
"result"
] | Manage a probe for a webaccelerator | [
"Manage",
"a",
"probe",
"for",
"a",
"webaccelerator"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/webacc.py#L385-L393 | train |
Gandi/gandi.cli | gandi/cli/commands/dns.py | domain_list | def domain_list(gandi):
"""List domains manageable by REST API."""
domains = gandi.dns.list()
for domain in domains:
gandi.echo(domain['fqdn'])
return domains | python | def domain_list(gandi):
"""List domains manageable by REST API."""
domains = gandi.dns.list()
for domain in domains:
gandi.echo(domain['fqdn'])
return domains | [
"def",
"domain_list",
"(",
"gandi",
")",
":",
"domains",
"=",
"gandi",
".",
"dns",
".",
"list",
"(",
")",
"for",
"domain",
"in",
"domains",
":",
"gandi",
".",
"echo",
"(",
"domain",
"[",
"'fqdn'",
"]",
")",
"return",
"domains"
] | List domains manageable by REST API. | [
"List",
"domains",
"manageable",
"by",
"REST",
"API",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dns.py#L19-L25 | train |
Gandi/gandi.cli | gandi/cli/commands/dns.py | list | def list(gandi, fqdn, name, sort, type, rrset_type, text):
"""Display records for a domain."""
domains = gandi.dns.list()
domains = [domain['fqdn'] for domain in domains]
if fqdn not in domains:
gandi.echo('Sorry domain %s does not exist' % fqdn)
gandi.echo('Please use one of the following: %s' % ', '.join(domains))
return
output_keys = ['name', 'ttl', 'type', 'values']
result = gandi.dns.records(fqdn, sort_by=sort, text=text)
if text:
gandi.echo(result)
return result
for num, rec in enumerate(result):
if type and rec['rrset_type'] != type:
continue
if rrset_type and rec['rrset_type'] != rrset_type:
continue
if name and rec['rrset_name'] != name:
continue
if num:
gandi.separator_line()
output_dns_records(gandi, rec, output_keys)
return result | python | def list(gandi, fqdn, name, sort, type, rrset_type, text):
"""Display records for a domain."""
domains = gandi.dns.list()
domains = [domain['fqdn'] for domain in domains]
if fqdn not in domains:
gandi.echo('Sorry domain %s does not exist' % fqdn)
gandi.echo('Please use one of the following: %s' % ', '.join(domains))
return
output_keys = ['name', 'ttl', 'type', 'values']
result = gandi.dns.records(fqdn, sort_by=sort, text=text)
if text:
gandi.echo(result)
return result
for num, rec in enumerate(result):
if type and rec['rrset_type'] != type:
continue
if rrset_type and rec['rrset_type'] != rrset_type:
continue
if name and rec['rrset_name'] != name:
continue
if num:
gandi.separator_line()
output_dns_records(gandi, rec, output_keys)
return result | [
"def",
"list",
"(",
"gandi",
",",
"fqdn",
",",
"name",
",",
"sort",
",",
"type",
",",
"rrset_type",
",",
"text",
")",
":",
"domains",
"=",
"gandi",
".",
"dns",
".",
"list",
"(",
")",
"domains",
"=",
"[",
"domain",
"[",
"'fqdn'",
"]",
"for",
"domain",
"in",
"domains",
"]",
"if",
"fqdn",
"not",
"in",
"domains",
":",
"gandi",
".",
"echo",
"(",
"'Sorry domain %s does not exist'",
"%",
"fqdn",
")",
"gandi",
".",
"echo",
"(",
"'Please use one of the following: %s'",
"%",
"', '",
".",
"join",
"(",
"domains",
")",
")",
"return",
"output_keys",
"=",
"[",
"'name'",
",",
"'ttl'",
",",
"'type'",
",",
"'values'",
"]",
"result",
"=",
"gandi",
".",
"dns",
".",
"records",
"(",
"fqdn",
",",
"sort_by",
"=",
"sort",
",",
"text",
"=",
"text",
")",
"if",
"text",
":",
"gandi",
".",
"echo",
"(",
"result",
")",
"return",
"result",
"for",
"num",
",",
"rec",
"in",
"enumerate",
"(",
"result",
")",
":",
"if",
"type",
"and",
"rec",
"[",
"'rrset_type'",
"]",
"!=",
"type",
":",
"continue",
"if",
"rrset_type",
"and",
"rec",
"[",
"'rrset_type'",
"]",
"!=",
"rrset_type",
":",
"continue",
"if",
"name",
"and",
"rec",
"[",
"'rrset_name'",
"]",
"!=",
"name",
":",
"continue",
"if",
"num",
":",
"gandi",
".",
"separator_line",
"(",
")",
"output_dns_records",
"(",
"gandi",
",",
"rec",
",",
"output_keys",
")",
"return",
"result"
] | Display records for a domain. | [
"Display",
"records",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dns.py#L40-L67 | train |
Gandi/gandi.cli | gandi/cli/commands/dns.py | create | def create(gandi, fqdn, name, type, value, ttl):
"""Create new record entry for a domain.
multiple value parameters can be provided.
"""
domains = gandi.dns.list()
domains = [domain['fqdn'] for domain in domains]
if fqdn not in domains:
gandi.echo('Sorry domain %s does not exist' % fqdn)
gandi.echo('Please use one of the following: %s' % ', '.join(domains))
return
result = gandi.dns.add_record(fqdn, name, type, value, ttl)
gandi.echo(result['message']) | python | def create(gandi, fqdn, name, type, value, ttl):
"""Create new record entry for a domain.
multiple value parameters can be provided.
"""
domains = gandi.dns.list()
domains = [domain['fqdn'] for domain in domains]
if fqdn not in domains:
gandi.echo('Sorry domain %s does not exist' % fqdn)
gandi.echo('Please use one of the following: %s' % ', '.join(domains))
return
result = gandi.dns.add_record(fqdn, name, type, value, ttl)
gandi.echo(result['message']) | [
"def",
"create",
"(",
"gandi",
",",
"fqdn",
",",
"name",
",",
"type",
",",
"value",
",",
"ttl",
")",
":",
"domains",
"=",
"gandi",
".",
"dns",
".",
"list",
"(",
")",
"domains",
"=",
"[",
"domain",
"[",
"'fqdn'",
"]",
"for",
"domain",
"in",
"domains",
"]",
"if",
"fqdn",
"not",
"in",
"domains",
":",
"gandi",
".",
"echo",
"(",
"'Sorry domain %s does not exist'",
"%",
"fqdn",
")",
"gandi",
".",
"echo",
"(",
"'Please use one of the following: %s'",
"%",
"', '",
".",
"join",
"(",
"domains",
")",
")",
"return",
"result",
"=",
"gandi",
".",
"dns",
".",
"add_record",
"(",
"fqdn",
",",
"name",
",",
"type",
",",
"value",
",",
"ttl",
")",
"gandi",
".",
"echo",
"(",
"result",
"[",
"'message'",
"]",
")"
] | Create new record entry for a domain.
multiple value parameters can be provided. | [
"Create",
"new",
"record",
"entry",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dns.py#L78-L91 | train |
Gandi/gandi.cli | gandi/cli/commands/dns.py | update | def update(gandi, fqdn, name, type, value, ttl, file):
"""Update record entry for a domain.
--file option will ignore other parameters and overwrite current zone
content with provided file content.
"""
domains = gandi.dns.list()
domains = [domain['fqdn'] for domain in domains]
if fqdn not in domains:
gandi.echo('Sorry domain %s does not exist' % fqdn)
gandi.echo('Please use one of the following: %s' % ', '.join(domains))
return
content = ''
if file:
content = file.read()
elif not sys.stdin.isatty():
content = click.get_text_stream('stdin').read()
content = content.strip()
if not content and not name and not type and not value:
click.echo('Cannot find parameters for zone content to update.')
return
if name and type and not value:
click.echo('You must provide one or more value parameter.')
return
result = gandi.dns.update_record(fqdn, name, type, value, ttl, content)
gandi.echo(result['message']) | python | def update(gandi, fqdn, name, type, value, ttl, file):
"""Update record entry for a domain.
--file option will ignore other parameters and overwrite current zone
content with provided file content.
"""
domains = gandi.dns.list()
domains = [domain['fqdn'] for domain in domains]
if fqdn not in domains:
gandi.echo('Sorry domain %s does not exist' % fqdn)
gandi.echo('Please use one of the following: %s' % ', '.join(domains))
return
content = ''
if file:
content = file.read()
elif not sys.stdin.isatty():
content = click.get_text_stream('stdin').read()
content = content.strip()
if not content and not name and not type and not value:
click.echo('Cannot find parameters for zone content to update.')
return
if name and type and not value:
click.echo('You must provide one or more value parameter.')
return
result = gandi.dns.update_record(fqdn, name, type, value, ttl, content)
gandi.echo(result['message']) | [
"def",
"update",
"(",
"gandi",
",",
"fqdn",
",",
"name",
",",
"type",
",",
"value",
",",
"ttl",
",",
"file",
")",
":",
"domains",
"=",
"gandi",
".",
"dns",
".",
"list",
"(",
")",
"domains",
"=",
"[",
"domain",
"[",
"'fqdn'",
"]",
"for",
"domain",
"in",
"domains",
"]",
"if",
"fqdn",
"not",
"in",
"domains",
":",
"gandi",
".",
"echo",
"(",
"'Sorry domain %s does not exist'",
"%",
"fqdn",
")",
"gandi",
".",
"echo",
"(",
"'Please use one of the following: %s'",
"%",
"', '",
".",
"join",
"(",
"domains",
")",
")",
"return",
"content",
"=",
"''",
"if",
"file",
":",
"content",
"=",
"file",
".",
"read",
"(",
")",
"elif",
"not",
"sys",
".",
"stdin",
".",
"isatty",
"(",
")",
":",
"content",
"=",
"click",
".",
"get_text_stream",
"(",
"'stdin'",
")",
".",
"read",
"(",
")",
"content",
"=",
"content",
".",
"strip",
"(",
")",
"if",
"not",
"content",
"and",
"not",
"name",
"and",
"not",
"type",
"and",
"not",
"value",
":",
"click",
".",
"echo",
"(",
"'Cannot find parameters for zone content to update.'",
")",
"return",
"if",
"name",
"and",
"type",
"and",
"not",
"value",
":",
"click",
".",
"echo",
"(",
"'You must provide one or more value parameter.'",
")",
"return",
"result",
"=",
"gandi",
".",
"dns",
".",
"update_record",
"(",
"fqdn",
",",
"name",
",",
"type",
",",
"value",
",",
"ttl",
",",
"content",
")",
"gandi",
".",
"echo",
"(",
"result",
"[",
"'message'",
"]",
")"
] | Update record entry for a domain.
--file option will ignore other parameters and overwrite current zone
content with provided file content. | [
"Update",
"record",
"entry",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dns.py#L106-L135 | train |
Gandi/gandi.cli | gandi/cli/commands/dns.py | delete | def delete(gandi, fqdn, name, type, force):
"""Delete record entry for a domain."""
domains = gandi.dns.list()
domains = [domain['fqdn'] for domain in domains]
if fqdn not in domains:
gandi.echo('Sorry domain %s does not exist' % fqdn)
gandi.echo('Please use one of the following: %s' % ', '.join(domains))
return
if not force:
if not name and not type:
prompt = ("Are you sure to delete all records for domain %s ?" %
fqdn)
elif name and not type:
prompt = ("Are you sure to delete all '%s' name records for "
"domain %s ?" % (name, fqdn))
else:
prompt = ("Are you sure to delete all '%s' records of type %s "
"for domain %s ?" % (name, type, fqdn))
proceed = click.confirm(prompt)
if not proceed:
return
result = gandi.dns.del_record(fqdn, name, type)
gandi.echo('Delete successful.')
return result | python | def delete(gandi, fqdn, name, type, force):
"""Delete record entry for a domain."""
domains = gandi.dns.list()
domains = [domain['fqdn'] for domain in domains]
if fqdn not in domains:
gandi.echo('Sorry domain %s does not exist' % fqdn)
gandi.echo('Please use one of the following: %s' % ', '.join(domains))
return
if not force:
if not name and not type:
prompt = ("Are you sure to delete all records for domain %s ?" %
fqdn)
elif name and not type:
prompt = ("Are you sure to delete all '%s' name records for "
"domain %s ?" % (name, fqdn))
else:
prompt = ("Are you sure to delete all '%s' records of type %s "
"for domain %s ?" % (name, type, fqdn))
proceed = click.confirm(prompt)
if not proceed:
return
result = gandi.dns.del_record(fqdn, name, type)
gandi.echo('Delete successful.')
return result | [
"def",
"delete",
"(",
"gandi",
",",
"fqdn",
",",
"name",
",",
"type",
",",
"force",
")",
":",
"domains",
"=",
"gandi",
".",
"dns",
".",
"list",
"(",
")",
"domains",
"=",
"[",
"domain",
"[",
"'fqdn'",
"]",
"for",
"domain",
"in",
"domains",
"]",
"if",
"fqdn",
"not",
"in",
"domains",
":",
"gandi",
".",
"echo",
"(",
"'Sorry domain %s does not exist'",
"%",
"fqdn",
")",
"gandi",
".",
"echo",
"(",
"'Please use one of the following: %s'",
"%",
"', '",
".",
"join",
"(",
"domains",
")",
")",
"return",
"if",
"not",
"force",
":",
"if",
"not",
"name",
"and",
"not",
"type",
":",
"prompt",
"=",
"(",
"\"Are you sure to delete all records for domain %s ?\"",
"%",
"fqdn",
")",
"elif",
"name",
"and",
"not",
"type",
":",
"prompt",
"=",
"(",
"\"Are you sure to delete all '%s' name records for \"",
"\"domain %s ?\"",
"%",
"(",
"name",
",",
"fqdn",
")",
")",
"else",
":",
"prompt",
"=",
"(",
"\"Are you sure to delete all '%s' records of type %s \"",
"\"for domain %s ?\"",
"%",
"(",
"name",
",",
"type",
",",
"fqdn",
")",
")",
"proceed",
"=",
"click",
".",
"confirm",
"(",
"prompt",
")",
"if",
"not",
"proceed",
":",
"return",
"result",
"=",
"gandi",
".",
"dns",
".",
"del_record",
"(",
"fqdn",
",",
"name",
",",
"type",
")",
"gandi",
".",
"echo",
"(",
"'Delete successful.'",
")",
"return",
"result"
] | Delete record entry for a domain. | [
"Delete",
"record",
"entry",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dns.py#L146-L173 | train |
Gandi/gandi.cli | gandi/cli/commands/dns.py | keys_list | def keys_list(gandi, fqdn):
"""List domain keys."""
keys = gandi.dns.keys(fqdn)
output_keys = ['uuid', 'algorithm', 'algorithm_name', 'ds', 'flags',
'status']
for num, key in enumerate(keys):
if num:
gandi.separator_line()
output_generic(gandi, key, output_keys, justify=15)
return keys | python | def keys_list(gandi, fqdn):
"""List domain keys."""
keys = gandi.dns.keys(fqdn)
output_keys = ['uuid', 'algorithm', 'algorithm_name', 'ds', 'flags',
'status']
for num, key in enumerate(keys):
if num:
gandi.separator_line()
output_generic(gandi, key, output_keys, justify=15)
return keys | [
"def",
"keys_list",
"(",
"gandi",
",",
"fqdn",
")",
":",
"keys",
"=",
"gandi",
".",
"dns",
".",
"keys",
"(",
"fqdn",
")",
"output_keys",
"=",
"[",
"'uuid'",
",",
"'algorithm'",
",",
"'algorithm_name'",
",",
"'ds'",
",",
"'flags'",
",",
"'status'",
"]",
"for",
"num",
",",
"key",
"in",
"enumerate",
"(",
"keys",
")",
":",
"if",
"num",
":",
"gandi",
".",
"separator_line",
"(",
")",
"output_generic",
"(",
"gandi",
",",
"key",
",",
"output_keys",
",",
"justify",
"=",
"15",
")",
"return",
"keys"
] | List domain keys. | [
"List",
"domain",
"keys",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dns.py#L185-L194 | train |
Gandi/gandi.cli | gandi/cli/commands/dns.py | keys_info | def keys_info(gandi, fqdn, key):
"""Display information about a domain key."""
key_info = gandi.dns.keys_info(fqdn, key)
output_keys = ['uuid', 'algorithm', 'algorithm_name', 'ds', 'fingerprint',
'public_key', 'flags', 'tag', 'status']
output_generic(gandi, key_info, output_keys, justify=15)
return key_info | python | def keys_info(gandi, fqdn, key):
"""Display information about a domain key."""
key_info = gandi.dns.keys_info(fqdn, key)
output_keys = ['uuid', 'algorithm', 'algorithm_name', 'ds', 'fingerprint',
'public_key', 'flags', 'tag', 'status']
output_generic(gandi, key_info, output_keys, justify=15)
return key_info | [
"def",
"keys_info",
"(",
"gandi",
",",
"fqdn",
",",
"key",
")",
":",
"key_info",
"=",
"gandi",
".",
"dns",
".",
"keys_info",
"(",
"fqdn",
",",
"key",
")",
"output_keys",
"=",
"[",
"'uuid'",
",",
"'algorithm'",
",",
"'algorithm_name'",
",",
"'ds'",
",",
"'fingerprint'",
",",
"'public_key'",
",",
"'flags'",
",",
"'tag'",
",",
"'status'",
"]",
"output_generic",
"(",
"gandi",
",",
"key_info",
",",
"output_keys",
",",
"justify",
"=",
"15",
")",
"return",
"key_info"
] | Display information about a domain key. | [
"Display",
"information",
"about",
"a",
"domain",
"key",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dns.py#L201-L207 | train |
Gandi/gandi.cli | gandi/cli/commands/dns.py | keys_create | def keys_create(gandi, fqdn, flag):
"""Create key for a domain."""
key_info = gandi.dns.keys_create(fqdn, int(flag))
output_keys = ['uuid', 'algorithm', 'algorithm_name', 'ds', 'fingerprint',
'public_key', 'flags', 'tag', 'status']
output_generic(gandi, key_info, output_keys, justify=15)
return key_info | python | def keys_create(gandi, fqdn, flag):
"""Create key for a domain."""
key_info = gandi.dns.keys_create(fqdn, int(flag))
output_keys = ['uuid', 'algorithm', 'algorithm_name', 'ds', 'fingerprint',
'public_key', 'flags', 'tag', 'status']
output_generic(gandi, key_info, output_keys, justify=15)
return key_info | [
"def",
"keys_create",
"(",
"gandi",
",",
"fqdn",
",",
"flag",
")",
":",
"key_info",
"=",
"gandi",
".",
"dns",
".",
"keys_create",
"(",
"fqdn",
",",
"int",
"(",
"flag",
")",
")",
"output_keys",
"=",
"[",
"'uuid'",
",",
"'algorithm'",
",",
"'algorithm_name'",
",",
"'ds'",
",",
"'fingerprint'",
",",
"'public_key'",
",",
"'flags'",
",",
"'tag'",
",",
"'status'",
"]",
"output_generic",
"(",
"gandi",
",",
"key_info",
",",
"output_keys",
",",
"justify",
"=",
"15",
")",
"return",
"key_info"
] | Create key for a domain. | [
"Create",
"key",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dns.py#L214-L221 | train |
Gandi/gandi.cli | gandi/cli/modules/docker.py | Docker.handle | def handle(cls, vm, args):
"""
Setup forwarding connection to given VM and pipe docker cmds over SSH.
"""
docker = Iaas.info(vm)
if not docker:
raise Exception('docker vm %s not found' % vm)
if docker['state'] != 'running':
Iaas.start(vm)
# XXX
remote_addr = docker['ifaces'][0]['ips'][0]['ip']
port = unixpipe.setup(remote_addr, 'root', '/var/run/docker.sock')
os.environ['DOCKER_HOST'] = 'tcp://localhost:%d' % port
cls.echo('using DOCKER_HOST=%s' % os.environ['DOCKER_HOST'])
subprocess.call(['docker'] + list(args)) | python | def handle(cls, vm, args):
"""
Setup forwarding connection to given VM and pipe docker cmds over SSH.
"""
docker = Iaas.info(vm)
if not docker:
raise Exception('docker vm %s not found' % vm)
if docker['state'] != 'running':
Iaas.start(vm)
# XXX
remote_addr = docker['ifaces'][0]['ips'][0]['ip']
port = unixpipe.setup(remote_addr, 'root', '/var/run/docker.sock')
os.environ['DOCKER_HOST'] = 'tcp://localhost:%d' % port
cls.echo('using DOCKER_HOST=%s' % os.environ['DOCKER_HOST'])
subprocess.call(['docker'] + list(args)) | [
"def",
"handle",
"(",
"cls",
",",
"vm",
",",
"args",
")",
":",
"docker",
"=",
"Iaas",
".",
"info",
"(",
"vm",
")",
"if",
"not",
"docker",
":",
"raise",
"Exception",
"(",
"'docker vm %s not found'",
"%",
"vm",
")",
"if",
"docker",
"[",
"'state'",
"]",
"!=",
"'running'",
":",
"Iaas",
".",
"start",
"(",
"vm",
")",
"# XXX",
"remote_addr",
"=",
"docker",
"[",
"'ifaces'",
"]",
"[",
"0",
"]",
"[",
"'ips'",
"]",
"[",
"0",
"]",
"[",
"'ip'",
"]",
"port",
"=",
"unixpipe",
".",
"setup",
"(",
"remote_addr",
",",
"'root'",
",",
"'/var/run/docker.sock'",
")",
"os",
".",
"environ",
"[",
"'DOCKER_HOST'",
"]",
"=",
"'tcp://localhost:%d'",
"%",
"port",
"cls",
".",
"echo",
"(",
"'using DOCKER_HOST=%s'",
"%",
"os",
".",
"environ",
"[",
"'DOCKER_HOST'",
"]",
")",
"subprocess",
".",
"call",
"(",
"[",
"'docker'",
"]",
"+",
"list",
"(",
"args",
")",
")"
] | Setup forwarding connection to given VM and pipe docker cmds over SSH. | [
"Setup",
"forwarding",
"connection",
"to",
"given",
"VM",
"and",
"pipe",
"docker",
"cmds",
"over",
"SSH",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/docker.py#L29-L48 | train |
Gandi/gandi.cli | gandi/cli/commands/vm.py | list | def list(gandi, state, id, limit, datacenter):
"""List virtual machines."""
options = {
'items_per_page': limit,
}
if state:
options['state'] = state
if datacenter:
options['datacenter_id'] = gandi.datacenter.usable_id(datacenter)
output_keys = ['hostname', 'state']
if id:
output_keys.append('id')
result = gandi.iaas.list(options)
for num, vm in enumerate(result):
if num:
gandi.separator_line()
output_vm(gandi, vm, [], output_keys)
return result | python | def list(gandi, state, id, limit, datacenter):
"""List virtual machines."""
options = {
'items_per_page': limit,
}
if state:
options['state'] = state
if datacenter:
options['datacenter_id'] = gandi.datacenter.usable_id(datacenter)
output_keys = ['hostname', 'state']
if id:
output_keys.append('id')
result = gandi.iaas.list(options)
for num, vm in enumerate(result):
if num:
gandi.separator_line()
output_vm(gandi, vm, [], output_keys)
return result | [
"def",
"list",
"(",
"gandi",
",",
"state",
",",
"id",
",",
"limit",
",",
"datacenter",
")",
":",
"options",
"=",
"{",
"'items_per_page'",
":",
"limit",
",",
"}",
"if",
"state",
":",
"options",
"[",
"'state'",
"]",
"=",
"state",
"if",
"datacenter",
":",
"options",
"[",
"'datacenter_id'",
"]",
"=",
"gandi",
".",
"datacenter",
".",
"usable_id",
"(",
"datacenter",
")",
"output_keys",
"=",
"[",
"'hostname'",
",",
"'state'",
"]",
"if",
"id",
":",
"output_keys",
".",
"append",
"(",
"'id'",
")",
"result",
"=",
"gandi",
".",
"iaas",
".",
"list",
"(",
"options",
")",
"for",
"num",
",",
"vm",
"in",
"enumerate",
"(",
"result",
")",
":",
"if",
"num",
":",
"gandi",
".",
"separator_line",
"(",
")",
"output_vm",
"(",
"gandi",
",",
"vm",
",",
"[",
"]",
",",
"output_keys",
")",
"return",
"result"
] | List virtual machines. | [
"List",
"virtual",
"machines",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/vm.py#L32-L52 | train |
Gandi/gandi.cli | gandi/cli/commands/vm.py | info | def info(gandi, resource, stat):
"""Display information about a virtual machine.
Resource can be a Hostname or an ID
"""
output_keys = ['hostname', 'state', 'cores', 'memory', 'console',
'datacenter', 'ip']
justify = 14
if stat is True:
sampler = {'unit': 'hours', 'value': 1, 'function': 'max'}
time_range = 3600 * 24
query_vif = 'vif.bytes.all'
query_vbd = 'vbd.bytes.all'
resource = sorted(tuple(set(resource)))
datacenters = gandi.datacenter.list()
ret = []
for num, item in enumerate(resource):
if num:
gandi.separator_line()
vm = gandi.iaas.info(item)
output_vm(gandi, vm, datacenters, output_keys, justify)
ret.append(vm)
for disk in vm['disks']:
gandi.echo('')
disk_out_keys = ['label', 'kernel_version', 'name', 'size']
output_image(gandi, disk, datacenters, disk_out_keys, justify,
warn_deprecated=False)
if stat is True:
metrics_vif = gandi.metric.query(vm['id'], time_range, query_vif,
'vm', sampler)
metrics_vbd = gandi.metric.query(vm['id'], time_range, query_vbd,
'vm', sampler)
gandi.echo('')
gandi.echo('vm network stats')
output_metric(gandi, metrics_vif, 'direction', justify)
gandi.echo('disk network stats')
output_metric(gandi, metrics_vbd, 'direction', justify)
return ret | python | def info(gandi, resource, stat):
"""Display information about a virtual machine.
Resource can be a Hostname or an ID
"""
output_keys = ['hostname', 'state', 'cores', 'memory', 'console',
'datacenter', 'ip']
justify = 14
if stat is True:
sampler = {'unit': 'hours', 'value': 1, 'function': 'max'}
time_range = 3600 * 24
query_vif = 'vif.bytes.all'
query_vbd = 'vbd.bytes.all'
resource = sorted(tuple(set(resource)))
datacenters = gandi.datacenter.list()
ret = []
for num, item in enumerate(resource):
if num:
gandi.separator_line()
vm = gandi.iaas.info(item)
output_vm(gandi, vm, datacenters, output_keys, justify)
ret.append(vm)
for disk in vm['disks']:
gandi.echo('')
disk_out_keys = ['label', 'kernel_version', 'name', 'size']
output_image(gandi, disk, datacenters, disk_out_keys, justify,
warn_deprecated=False)
if stat is True:
metrics_vif = gandi.metric.query(vm['id'], time_range, query_vif,
'vm', sampler)
metrics_vbd = gandi.metric.query(vm['id'], time_range, query_vbd,
'vm', sampler)
gandi.echo('')
gandi.echo('vm network stats')
output_metric(gandi, metrics_vif, 'direction', justify)
gandi.echo('disk network stats')
output_metric(gandi, metrics_vbd, 'direction', justify)
return ret | [
"def",
"info",
"(",
"gandi",
",",
"resource",
",",
"stat",
")",
":",
"output_keys",
"=",
"[",
"'hostname'",
",",
"'state'",
",",
"'cores'",
",",
"'memory'",
",",
"'console'",
",",
"'datacenter'",
",",
"'ip'",
"]",
"justify",
"=",
"14",
"if",
"stat",
"is",
"True",
":",
"sampler",
"=",
"{",
"'unit'",
":",
"'hours'",
",",
"'value'",
":",
"1",
",",
"'function'",
":",
"'max'",
"}",
"time_range",
"=",
"3600",
"*",
"24",
"query_vif",
"=",
"'vif.bytes.all'",
"query_vbd",
"=",
"'vbd.bytes.all'",
"resource",
"=",
"sorted",
"(",
"tuple",
"(",
"set",
"(",
"resource",
")",
")",
")",
"datacenters",
"=",
"gandi",
".",
"datacenter",
".",
"list",
"(",
")",
"ret",
"=",
"[",
"]",
"for",
"num",
",",
"item",
"in",
"enumerate",
"(",
"resource",
")",
":",
"if",
"num",
":",
"gandi",
".",
"separator_line",
"(",
")",
"vm",
"=",
"gandi",
".",
"iaas",
".",
"info",
"(",
"item",
")",
"output_vm",
"(",
"gandi",
",",
"vm",
",",
"datacenters",
",",
"output_keys",
",",
"justify",
")",
"ret",
".",
"append",
"(",
"vm",
")",
"for",
"disk",
"in",
"vm",
"[",
"'disks'",
"]",
":",
"gandi",
".",
"echo",
"(",
"''",
")",
"disk_out_keys",
"=",
"[",
"'label'",
",",
"'kernel_version'",
",",
"'name'",
",",
"'size'",
"]",
"output_image",
"(",
"gandi",
",",
"disk",
",",
"datacenters",
",",
"disk_out_keys",
",",
"justify",
",",
"warn_deprecated",
"=",
"False",
")",
"if",
"stat",
"is",
"True",
":",
"metrics_vif",
"=",
"gandi",
".",
"metric",
".",
"query",
"(",
"vm",
"[",
"'id'",
"]",
",",
"time_range",
",",
"query_vif",
",",
"'vm'",
",",
"sampler",
")",
"metrics_vbd",
"=",
"gandi",
".",
"metric",
".",
"query",
"(",
"vm",
"[",
"'id'",
"]",
",",
"time_range",
",",
"query_vbd",
",",
"'vm'",
",",
"sampler",
")",
"gandi",
".",
"echo",
"(",
"''",
")",
"gandi",
".",
"echo",
"(",
"'vm network stats'",
")",
"output_metric",
"(",
"gandi",
",",
"metrics_vif",
",",
"'direction'",
",",
"justify",
")",
"gandi",
".",
"echo",
"(",
"'disk network stats'",
")",
"output_metric",
"(",
"gandi",
",",
"metrics_vbd",
",",
"'direction'",
",",
"justify",
")",
"return",
"ret"
] | Display information about a virtual machine.
Resource can be a Hostname or an ID | [
"Display",
"information",
"about",
"a",
"virtual",
"machine",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/vm.py#L60-L99 | train |
Gandi/gandi.cli | gandi/cli/commands/vm.py | ssh | def ssh(gandi, resource, login, identity, wipe_key, wait, args):
"""Spawn an SSH session to virtual machine.
Resource can be a Hostname or an ID
"""
if '@' in resource:
(login, resource) = resource.split('@', 1)
if wipe_key:
gandi.iaas.ssh_keyscan(resource)
if wait:
gandi.iaas.wait_for_sshd(resource)
gandi.iaas.ssh(resource, login, identity, args) | python | def ssh(gandi, resource, login, identity, wipe_key, wait, args):
"""Spawn an SSH session to virtual machine.
Resource can be a Hostname or an ID
"""
if '@' in resource:
(login, resource) = resource.split('@', 1)
if wipe_key:
gandi.iaas.ssh_keyscan(resource)
if wait:
gandi.iaas.wait_for_sshd(resource)
gandi.iaas.ssh(resource, login, identity, args) | [
"def",
"ssh",
"(",
"gandi",
",",
"resource",
",",
"login",
",",
"identity",
",",
"wipe_key",
",",
"wait",
",",
"args",
")",
":",
"if",
"'@'",
"in",
"resource",
":",
"(",
"login",
",",
"resource",
")",
"=",
"resource",
".",
"split",
"(",
"'@'",
",",
"1",
")",
"if",
"wipe_key",
":",
"gandi",
".",
"iaas",
".",
"ssh_keyscan",
"(",
"resource",
")",
"if",
"wait",
":",
"gandi",
".",
"iaas",
".",
"wait_for_sshd",
"(",
"resource",
")",
"gandi",
".",
"iaas",
".",
"ssh",
"(",
"resource",
",",
"login",
",",
"identity",
",",
"args",
")"
] | Spawn an SSH session to virtual machine.
Resource can be a Hostname or an ID | [
"Spawn",
"an",
"SSH",
"session",
"to",
"virtual",
"machine",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/vm.py#L420-L431 | train |
Gandi/gandi.cli | gandi/cli/commands/vm.py | images | def images(gandi, label, datacenter):
"""List available system images for virtual machines.
You can also filter results using label, by example:
$ gandi vm images Ubuntu --datacenter LU
or
$ gandi vm images 'Ubuntu 10.04' --datacenter LU
"""
output_keys = ['label', 'os_arch', 'kernel_version', 'disk_id',
'dc', 'name']
datacenters = gandi.datacenter.list()
result = gandi.image.list(datacenter, label)
for num, image in enumerate(result):
if num:
gandi.separator_line()
output_image(gandi, image, datacenters, output_keys)
# also display usable disks
result = gandi.disk.list_create(datacenter, label)
for disk in result:
gandi.separator_line()
output_image(gandi, disk, datacenters, output_keys)
return result | python | def images(gandi, label, datacenter):
"""List available system images for virtual machines.
You can also filter results using label, by example:
$ gandi vm images Ubuntu --datacenter LU
or
$ gandi vm images 'Ubuntu 10.04' --datacenter LU
"""
output_keys = ['label', 'os_arch', 'kernel_version', 'disk_id',
'dc', 'name']
datacenters = gandi.datacenter.list()
result = gandi.image.list(datacenter, label)
for num, image in enumerate(result):
if num:
gandi.separator_line()
output_image(gandi, image, datacenters, output_keys)
# also display usable disks
result = gandi.disk.list_create(datacenter, label)
for disk in result:
gandi.separator_line()
output_image(gandi, disk, datacenters, output_keys)
return result | [
"def",
"images",
"(",
"gandi",
",",
"label",
",",
"datacenter",
")",
":",
"output_keys",
"=",
"[",
"'label'",
",",
"'os_arch'",
",",
"'kernel_version'",
",",
"'disk_id'",
",",
"'dc'",
",",
"'name'",
"]",
"datacenters",
"=",
"gandi",
".",
"datacenter",
".",
"list",
"(",
")",
"result",
"=",
"gandi",
".",
"image",
".",
"list",
"(",
"datacenter",
",",
"label",
")",
"for",
"num",
",",
"image",
"in",
"enumerate",
"(",
"result",
")",
":",
"if",
"num",
":",
"gandi",
".",
"separator_line",
"(",
")",
"output_image",
"(",
"gandi",
",",
"image",
",",
"datacenters",
",",
"output_keys",
")",
"# also display usable disks",
"result",
"=",
"gandi",
".",
"disk",
".",
"list_create",
"(",
"datacenter",
",",
"label",
")",
"for",
"disk",
"in",
"result",
":",
"gandi",
".",
"separator_line",
"(",
")",
"output_image",
"(",
"gandi",
",",
"disk",
",",
"datacenters",
",",
"output_keys",
")",
"return",
"result"
] | List available system images for virtual machines.
You can also filter results using label, by example:
$ gandi vm images Ubuntu --datacenter LU
or
$ gandi vm images 'Ubuntu 10.04' --datacenter LU | [
"List",
"available",
"system",
"images",
"for",
"virtual",
"machines",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/vm.py#L439-L467 | train |
Gandi/gandi.cli | gandi/cli/commands/vm.py | kernels | def kernels(gandi, vm, datacenter, flavor, match):
"""List available kernels."""
if vm:
vm = gandi.iaas.info(vm)
dc_list = gandi.datacenter.filtered_list(datacenter, vm)
for num, dc in enumerate(dc_list):
if num:
gandi.echo('\n')
output_datacenter(gandi, dc, ['dc_name'])
kmap = gandi.kernel.list(dc['id'], flavor, match)
for _flavor in kmap:
gandi.separator_line()
output_kernels(gandi, _flavor, kmap[_flavor]) | python | def kernels(gandi, vm, datacenter, flavor, match):
"""List available kernels."""
if vm:
vm = gandi.iaas.info(vm)
dc_list = gandi.datacenter.filtered_list(datacenter, vm)
for num, dc in enumerate(dc_list):
if num:
gandi.echo('\n')
output_datacenter(gandi, dc, ['dc_name'])
kmap = gandi.kernel.list(dc['id'], flavor, match)
for _flavor in kmap:
gandi.separator_line()
output_kernels(gandi, _flavor, kmap[_flavor]) | [
"def",
"kernels",
"(",
"gandi",
",",
"vm",
",",
"datacenter",
",",
"flavor",
",",
"match",
")",
":",
"if",
"vm",
":",
"vm",
"=",
"gandi",
".",
"iaas",
".",
"info",
"(",
"vm",
")",
"dc_list",
"=",
"gandi",
".",
"datacenter",
".",
"filtered_list",
"(",
"datacenter",
",",
"vm",
")",
"for",
"num",
",",
"dc",
"in",
"enumerate",
"(",
"dc_list",
")",
":",
"if",
"num",
":",
"gandi",
".",
"echo",
"(",
"'\\n'",
")",
"output_datacenter",
"(",
"gandi",
",",
"dc",
",",
"[",
"'dc_name'",
"]",
")",
"kmap",
"=",
"gandi",
".",
"kernel",
".",
"list",
"(",
"dc",
"[",
"'id'",
"]",
",",
"flavor",
",",
"match",
")",
"for",
"_flavor",
"in",
"kmap",
":",
"gandi",
".",
"separator_line",
"(",
")",
"output_kernels",
"(",
"gandi",
",",
"_flavor",
",",
"kmap",
"[",
"_flavor",
"]",
")"
] | List available kernels. | [
"List",
"available",
"kernels",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/vm.py#L479-L494 | train |
Gandi/gandi.cli | gandi/cli/commands/vm.py | datacenters | def datacenters(gandi, id):
"""List available datacenters."""
output_keys = ['iso', 'name', 'country', 'dc_code', 'status']
if id:
output_keys.append('id')
result = gandi.datacenter.list()
for num, dc in enumerate(result):
if num:
gandi.separator_line()
output_datacenter(gandi, dc, output_keys, justify=10)
return result | python | def datacenters(gandi, id):
"""List available datacenters."""
output_keys = ['iso', 'name', 'country', 'dc_code', 'status']
if id:
output_keys.append('id')
result = gandi.datacenter.list()
for num, dc in enumerate(result):
if num:
gandi.separator_line()
output_datacenter(gandi, dc, output_keys, justify=10)
return result | [
"def",
"datacenters",
"(",
"gandi",
",",
"id",
")",
":",
"output_keys",
"=",
"[",
"'iso'",
",",
"'name'",
",",
"'country'",
",",
"'dc_code'",
",",
"'status'",
"]",
"if",
"id",
":",
"output_keys",
".",
"append",
"(",
"'id'",
")",
"result",
"=",
"gandi",
".",
"datacenter",
".",
"list",
"(",
")",
"for",
"num",
",",
"dc",
"in",
"enumerate",
"(",
"result",
")",
":",
"if",
"num",
":",
"gandi",
".",
"separator_line",
"(",
")",
"output_datacenter",
"(",
"gandi",
",",
"dc",
",",
"output_keys",
",",
"justify",
"=",
"10",
")",
"return",
"result"
] | List available datacenters. | [
"List",
"available",
"datacenters",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/vm.py#L500-L512 | train |
Gandi/gandi.cli | gandi/cli/modules/hostedcert.py | HostedCert.usable_id | def usable_id(cls, id):
""" Retrieve id from single input. """
hcs = cls.from_fqdn(id)
if hcs:
return [hc_['id'] for hc_ in hcs]
try:
return int(id)
except (TypeError, ValueError):
pass | python | def usable_id(cls, id):
""" Retrieve id from single input. """
hcs = cls.from_fqdn(id)
if hcs:
return [hc_['id'] for hc_ in hcs]
try:
return int(id)
except (TypeError, ValueError):
pass | [
"def",
"usable_id",
"(",
"cls",
",",
"id",
")",
":",
"hcs",
"=",
"cls",
".",
"from_fqdn",
"(",
"id",
")",
"if",
"hcs",
":",
"return",
"[",
"hc_",
"[",
"'id'",
"]",
"for",
"hc_",
"in",
"hcs",
"]",
"try",
":",
"return",
"int",
"(",
"id",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"pass"
] | Retrieve id from single input. | [
"Retrieve",
"id",
"from",
"single",
"input",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/hostedcert.py#L21-L30 | train |
Gandi/gandi.cli | gandi/cli/modules/hostedcert.py | HostedCert.infos | def infos(cls, fqdn):
""" Display information about hosted certificates for a fqdn. """
if isinstance(fqdn, (list, tuple)):
ids = []
for fqd_ in fqdn:
ids.extend(cls.infos(fqd_))
return ids
ids = cls.usable_id(fqdn)
if not ids:
return []
if not isinstance(ids, (list, tuple)):
ids = [ids]
return [cls.info(id_) for id_ in ids] | python | def infos(cls, fqdn):
""" Display information about hosted certificates for a fqdn. """
if isinstance(fqdn, (list, tuple)):
ids = []
for fqd_ in fqdn:
ids.extend(cls.infos(fqd_))
return ids
ids = cls.usable_id(fqdn)
if not ids:
return []
if not isinstance(ids, (list, tuple)):
ids = [ids]
return [cls.info(id_) for id_ in ids] | [
"def",
"infos",
"(",
"cls",
",",
"fqdn",
")",
":",
"if",
"isinstance",
"(",
"fqdn",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"ids",
"=",
"[",
"]",
"for",
"fqd_",
"in",
"fqdn",
":",
"ids",
".",
"extend",
"(",
"cls",
".",
"infos",
"(",
"fqd_",
")",
")",
"return",
"ids",
"ids",
"=",
"cls",
".",
"usable_id",
"(",
"fqdn",
")",
"if",
"not",
"ids",
":",
"return",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"ids",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"ids",
"=",
"[",
"ids",
"]",
"return",
"[",
"cls",
".",
"info",
"(",
"id_",
")",
"for",
"id_",
"in",
"ids",
"]"
] | Display information about hosted certificates for a fqdn. | [
"Display",
"information",
"about",
"hosted",
"certificates",
"for",
"a",
"fqdn",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/hostedcert.py#L44-L59 | train |
Gandi/gandi.cli | gandi/cli/modules/hostedcert.py | HostedCert.create | def create(cls, key, crt):
""" Add a new crt in the hosted cert store. """
options = {'crt': crt, 'key': key}
return cls.call('cert.hosted.create', options) | python | def create(cls, key, crt):
""" Add a new crt in the hosted cert store. """
options = {'crt': crt, 'key': key}
return cls.call('cert.hosted.create', options) | [
"def",
"create",
"(",
"cls",
",",
"key",
",",
"crt",
")",
":",
"options",
"=",
"{",
"'crt'",
":",
"crt",
",",
"'key'",
":",
"key",
"}",
"return",
"cls",
".",
"call",
"(",
"'cert.hosted.create'",
",",
"options",
")"
] | Add a new crt in the hosted cert store. | [
"Add",
"a",
"new",
"crt",
"in",
"the",
"hosted",
"cert",
"store",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/hostedcert.py#L62-L65 | train |
Gandi/gandi.cli | gandi/cli/commands/domain.py | list | def list(gandi, limit):
"""List domains."""
options = {'items_per_page': limit}
domains = gandi.domain.list(options)
for domain in domains:
gandi.echo(domain['fqdn'])
return domains | python | def list(gandi, limit):
"""List domains."""
options = {'items_per_page': limit}
domains = gandi.domain.list(options)
for domain in domains:
gandi.echo(domain['fqdn'])
return domains | [
"def",
"list",
"(",
"gandi",
",",
"limit",
")",
":",
"options",
"=",
"{",
"'items_per_page'",
":",
"limit",
"}",
"domains",
"=",
"gandi",
".",
"domain",
".",
"list",
"(",
"options",
")",
"for",
"domain",
"in",
"domains",
":",
"gandi",
".",
"echo",
"(",
"domain",
"[",
"'fqdn'",
"]",
")",
"return",
"domains"
] | List domains. | [
"List",
"domains",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/domain.py#L26-L33 | train |
Gandi/gandi.cli | gandi/cli/commands/domain.py | info | def info(gandi, resource):
"""Display information about a domain."""
output_keys = ['fqdn', 'nameservers', 'services', 'zone_id', 'tags',
'created', 'expires', 'updated']
contact_field = ['owner', 'admin', 'bill', 'tech', 'reseller']
result = gandi.domain.info(resource)
output_contact_info(gandi, result['contacts'], contact_field, justify=12)
output_domain(gandi, result, output_keys, justify=12)
return result | python | def info(gandi, resource):
"""Display information about a domain."""
output_keys = ['fqdn', 'nameservers', 'services', 'zone_id', 'tags',
'created', 'expires', 'updated']
contact_field = ['owner', 'admin', 'bill', 'tech', 'reseller']
result = gandi.domain.info(resource)
output_contact_info(gandi, result['contacts'], contact_field, justify=12)
output_domain(gandi, result, output_keys, justify=12)
return result | [
"def",
"info",
"(",
"gandi",
",",
"resource",
")",
":",
"output_keys",
"=",
"[",
"'fqdn'",
",",
"'nameservers'",
",",
"'services'",
",",
"'zone_id'",
",",
"'tags'",
",",
"'created'",
",",
"'expires'",
",",
"'updated'",
"]",
"contact_field",
"=",
"[",
"'owner'",
",",
"'admin'",
",",
"'bill'",
",",
"'tech'",
",",
"'reseller'",
"]",
"result",
"=",
"gandi",
".",
"domain",
".",
"info",
"(",
"resource",
")",
"output_contact_info",
"(",
"gandi",
",",
"result",
"[",
"'contacts'",
"]",
",",
"contact_field",
",",
"justify",
"=",
"12",
")",
"output_domain",
"(",
"gandi",
",",
"result",
",",
"output_keys",
",",
"justify",
"=",
"12",
")",
"return",
"result"
] | Display information about a domain. | [
"Display",
"information",
"about",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/domain.py#L39-L49 | train |
Gandi/gandi.cli | gandi/cli/commands/domain.py | create | def create(gandi, resource, domain, duration, owner, admin, tech, bill,
nameserver, extra_parameter, background):
"""Buy a domain."""
if domain:
gandi.echo('/!\ --domain option is deprecated and will be removed '
'upon next release.')
gandi.echo("You should use 'gandi domain create %s' instead." % domain)
if (domain and resource) and (domain != resource):
gandi.echo('/!\ You specified both an option and an argument which '
'are different, please choose only one between: %s and %s.'
% (domain, resource))
return
_domain = domain or resource
if not _domain:
_domain = click.prompt('Name of the domain')
result = gandi.domain.create(_domain, duration, owner, admin, tech, bill,
nameserver, extra_parameter, background)
if background:
gandi.pretty_echo(result)
return result | python | def create(gandi, resource, domain, duration, owner, admin, tech, bill,
nameserver, extra_parameter, background):
"""Buy a domain."""
if domain:
gandi.echo('/!\ --domain option is deprecated and will be removed '
'upon next release.')
gandi.echo("You should use 'gandi domain create %s' instead." % domain)
if (domain and resource) and (domain != resource):
gandi.echo('/!\ You specified both an option and an argument which '
'are different, please choose only one between: %s and %s.'
% (domain, resource))
return
_domain = domain or resource
if not _domain:
_domain = click.prompt('Name of the domain')
result = gandi.domain.create(_domain, duration, owner, admin, tech, bill,
nameserver, extra_parameter, background)
if background:
gandi.pretty_echo(result)
return result | [
"def",
"create",
"(",
"gandi",
",",
"resource",
",",
"domain",
",",
"duration",
",",
"owner",
",",
"admin",
",",
"tech",
",",
"bill",
",",
"nameserver",
",",
"extra_parameter",
",",
"background",
")",
":",
"if",
"domain",
":",
"gandi",
".",
"echo",
"(",
"'/!\\ --domain option is deprecated and will be removed '",
"'upon next release.'",
")",
"gandi",
".",
"echo",
"(",
"\"You should use 'gandi domain create %s' instead.\"",
"%",
"domain",
")",
"if",
"(",
"domain",
"and",
"resource",
")",
"and",
"(",
"domain",
"!=",
"resource",
")",
":",
"gandi",
".",
"echo",
"(",
"'/!\\ You specified both an option and an argument which '",
"'are different, please choose only one between: %s and %s.'",
"%",
"(",
"domain",
",",
"resource",
")",
")",
"return",
"_domain",
"=",
"domain",
"or",
"resource",
"if",
"not",
"_domain",
":",
"_domain",
"=",
"click",
".",
"prompt",
"(",
"'Name of the domain'",
")",
"result",
"=",
"gandi",
".",
"domain",
".",
"create",
"(",
"_domain",
",",
"duration",
",",
"owner",
",",
"admin",
",",
"tech",
",",
"bill",
",",
"nameserver",
",",
"extra_parameter",
",",
"background",
")",
"if",
"background",
":",
"gandi",
".",
"pretty_echo",
"(",
"result",
")",
"return",
"result"
] | Buy a domain. | [
"Buy",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/domain.py#L74-L97 | train |
Gandi/gandi.cli | gandi/cli/commands/root.py | api | def api(gandi):
"""Display information about API used."""
key_name = 'API version'
result = gandi.api.info()
result[key_name] = result.pop('api_version')
output_generic(gandi, result, [key_name])
return result | python | def api(gandi):
"""Display information about API used."""
key_name = 'API version'
result = gandi.api.info()
result[key_name] = result.pop('api_version')
output_generic(gandi, result, [key_name])
return result | [
"def",
"api",
"(",
"gandi",
")",
":",
"key_name",
"=",
"'API version'",
"result",
"=",
"gandi",
".",
"api",
".",
"info",
"(",
")",
"result",
"[",
"key_name",
"]",
"=",
"result",
".",
"pop",
"(",
"'api_version'",
")",
"output_generic",
"(",
"gandi",
",",
"result",
",",
"[",
"key_name",
"]",
")",
"return",
"result"
] | Display information about API used. | [
"Display",
"information",
"about",
"API",
"used",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/root.py#L34-L42 | train |
Gandi/gandi.cli | gandi/cli/commands/root.py | help | def help(ctx, command):
"""Display help for a command."""
command = ' '.join(command)
if not command:
click.echo(cli.get_help(ctx))
return
cmd = cli.get_command(ctx, command)
if cmd:
click.echo(cmd.get_help(ctx))
else:
click.echo(cli.get_help(ctx)) | python | def help(ctx, command):
"""Display help for a command."""
command = ' '.join(command)
if not command:
click.echo(cli.get_help(ctx))
return
cmd = cli.get_command(ctx, command)
if cmd:
click.echo(cmd.get_help(ctx))
else:
click.echo(cli.get_help(ctx)) | [
"def",
"help",
"(",
"ctx",
",",
"command",
")",
":",
"command",
"=",
"' '",
".",
"join",
"(",
"command",
")",
"if",
"not",
"command",
":",
"click",
".",
"echo",
"(",
"cli",
".",
"get_help",
"(",
"ctx",
")",
")",
"return",
"cmd",
"=",
"cli",
".",
"get_command",
"(",
"ctx",
",",
"command",
")",
"if",
"cmd",
":",
"click",
".",
"echo",
"(",
"cmd",
".",
"get_help",
"(",
"ctx",
")",
")",
"else",
":",
"click",
".",
"echo",
"(",
"cli",
".",
"get_help",
"(",
"ctx",
")",
")"
] | Display help for a command. | [
"Display",
"help",
"for",
"a",
"command",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/root.py#L48-L59 | train |
Gandi/gandi.cli | gandi/cli/commands/root.py | status | def status(gandi, service):
"""Display current status from status.gandi.net."""
if not service:
global_status = gandi.status.status()
if global_status['status'] == 'FOGGY':
# something is going on but not affecting services
filters = {
'category': 'Incident',
'current': True,
}
events = gandi.status.events(filters)
for event in events:
if event['services']:
# do not process services
continue
event_url = gandi.status.event_timeline(event)
service_detail = '%s - %s' % (event['title'], event_url)
gandi.echo(service_detail)
# then check other services
descs = gandi.status.descriptions()
needed = services = gandi.status.services()
if service:
needed = [serv for serv in services
if serv['name'].lower() == service.lower()]
for serv in needed:
if serv['status'] != 'STORMY':
output_service(gandi, serv['name'], descs[serv['status']])
continue
filters = {
'category': 'Incident',
'services': serv['name'],
'current': True,
}
events = gandi.status.events(filters)
for event in events:
event_url = gandi.status.event_timeline(event)
service_detail = '%s - %s' % (event['title'], event_url)
output_service(gandi, serv['name'], service_detail)
return services | python | def status(gandi, service):
"""Display current status from status.gandi.net."""
if not service:
global_status = gandi.status.status()
if global_status['status'] == 'FOGGY':
# something is going on but not affecting services
filters = {
'category': 'Incident',
'current': True,
}
events = gandi.status.events(filters)
for event in events:
if event['services']:
# do not process services
continue
event_url = gandi.status.event_timeline(event)
service_detail = '%s - %s' % (event['title'], event_url)
gandi.echo(service_detail)
# then check other services
descs = gandi.status.descriptions()
needed = services = gandi.status.services()
if service:
needed = [serv for serv in services
if serv['name'].lower() == service.lower()]
for serv in needed:
if serv['status'] != 'STORMY':
output_service(gandi, serv['name'], descs[serv['status']])
continue
filters = {
'category': 'Incident',
'services': serv['name'],
'current': True,
}
events = gandi.status.events(filters)
for event in events:
event_url = gandi.status.event_timeline(event)
service_detail = '%s - %s' % (event['title'], event_url)
output_service(gandi, serv['name'], service_detail)
return services | [
"def",
"status",
"(",
"gandi",
",",
"service",
")",
":",
"if",
"not",
"service",
":",
"global_status",
"=",
"gandi",
".",
"status",
".",
"status",
"(",
")",
"if",
"global_status",
"[",
"'status'",
"]",
"==",
"'FOGGY'",
":",
"# something is going on but not affecting services",
"filters",
"=",
"{",
"'category'",
":",
"'Incident'",
",",
"'current'",
":",
"True",
",",
"}",
"events",
"=",
"gandi",
".",
"status",
".",
"events",
"(",
"filters",
")",
"for",
"event",
"in",
"events",
":",
"if",
"event",
"[",
"'services'",
"]",
":",
"# do not process services",
"continue",
"event_url",
"=",
"gandi",
".",
"status",
".",
"event_timeline",
"(",
"event",
")",
"service_detail",
"=",
"'%s - %s'",
"%",
"(",
"event",
"[",
"'title'",
"]",
",",
"event_url",
")",
"gandi",
".",
"echo",
"(",
"service_detail",
")",
"# then check other services",
"descs",
"=",
"gandi",
".",
"status",
".",
"descriptions",
"(",
")",
"needed",
"=",
"services",
"=",
"gandi",
".",
"status",
".",
"services",
"(",
")",
"if",
"service",
":",
"needed",
"=",
"[",
"serv",
"for",
"serv",
"in",
"services",
"if",
"serv",
"[",
"'name'",
"]",
".",
"lower",
"(",
")",
"==",
"service",
".",
"lower",
"(",
")",
"]",
"for",
"serv",
"in",
"needed",
":",
"if",
"serv",
"[",
"'status'",
"]",
"!=",
"'STORMY'",
":",
"output_service",
"(",
"gandi",
",",
"serv",
"[",
"'name'",
"]",
",",
"descs",
"[",
"serv",
"[",
"'status'",
"]",
"]",
")",
"continue",
"filters",
"=",
"{",
"'category'",
":",
"'Incident'",
",",
"'services'",
":",
"serv",
"[",
"'name'",
"]",
",",
"'current'",
":",
"True",
",",
"}",
"events",
"=",
"gandi",
".",
"status",
".",
"events",
"(",
"filters",
")",
"for",
"event",
"in",
"events",
":",
"event_url",
"=",
"gandi",
".",
"status",
".",
"event_timeline",
"(",
"event",
")",
"service_detail",
"=",
"'%s - %s'",
"%",
"(",
"event",
"[",
"'title'",
"]",
",",
"event_url",
")",
"output_service",
"(",
"gandi",
",",
"serv",
"[",
"'name'",
"]",
",",
"service_detail",
")",
"return",
"services"
] | Display current status from status.gandi.net. | [
"Display",
"current",
"status",
"from",
"status",
".",
"gandi",
".",
"net",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/root.py#L65-L108 | train |
Gandi/gandi.cli | gandi/cli/commands/forward.py | list | def list(gandi, domain, limit):
"""List mail forwards for a domain."""
options = {'items_per_page': limit}
result = gandi.forward.list(domain, options)
for forward in result:
output_forward(gandi, domain, forward)
return result | python | def list(gandi, domain, limit):
"""List mail forwards for a domain."""
options = {'items_per_page': limit}
result = gandi.forward.list(domain, options)
for forward in result:
output_forward(gandi, domain, forward)
return result | [
"def",
"list",
"(",
"gandi",
",",
"domain",
",",
"limit",
")",
":",
"options",
"=",
"{",
"'items_per_page'",
":",
"limit",
"}",
"result",
"=",
"gandi",
".",
"forward",
".",
"list",
"(",
"domain",
",",
"options",
")",
"for",
"forward",
"in",
"result",
":",
"output_forward",
"(",
"gandi",
",",
"domain",
",",
"forward",
")",
"return",
"result"
] | List mail forwards for a domain. | [
"List",
"mail",
"forwards",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/forward.py#L21-L27 | train |
Gandi/gandi.cli | gandi/cli/commands/forward.py | update | def update(gandi, address, dest_add, dest_del):
"""Update a domain mail forward."""
source, domain = address
if not dest_add and not dest_del:
gandi.echo('Nothing to update: you must provide destinations to '
'update, use --dest-add/-a or -dest-del/-d parameters.')
return
result = gandi.forward.update(domain, source, dest_add, dest_del)
return result | python | def update(gandi, address, dest_add, dest_del):
"""Update a domain mail forward."""
source, domain = address
if not dest_add and not dest_del:
gandi.echo('Nothing to update: you must provide destinations to '
'update, use --dest-add/-a or -dest-del/-d parameters.')
return
result = gandi.forward.update(domain, source, dest_add, dest_del)
return result | [
"def",
"update",
"(",
"gandi",
",",
"address",
",",
"dest_add",
",",
"dest_del",
")",
":",
"source",
",",
"domain",
"=",
"address",
"if",
"not",
"dest_add",
"and",
"not",
"dest_del",
":",
"gandi",
".",
"echo",
"(",
"'Nothing to update: you must provide destinations to '",
"'update, use --dest-add/-a or -dest-del/-d parameters.'",
")",
"return",
"result",
"=",
"gandi",
".",
"forward",
".",
"update",
"(",
"domain",
",",
"source",
",",
"dest_add",
",",
"dest_del",
")",
"return",
"result"
] | Update a domain mail forward. | [
"Update",
"a",
"domain",
"mail",
"forward",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/forward.py#L51-L62 | train |
Gandi/gandi.cli | gandi/cli/commands/forward.py | delete | def delete(gandi, address, force):
"""Delete a domain mail forward."""
source, domain = address
if not force:
proceed = click.confirm('Are you sure to delete the domain '
'mail forward %s@%s ?' % (source, domain))
if not proceed:
return
result = gandi.forward.delete(domain, source)
return result | python | def delete(gandi, address, force):
"""Delete a domain mail forward."""
source, domain = address
if not force:
proceed = click.confirm('Are you sure to delete the domain '
'mail forward %s@%s ?' % (source, domain))
if not proceed:
return
result = gandi.forward.delete(domain, source)
return result | [
"def",
"delete",
"(",
"gandi",
",",
"address",
",",
"force",
")",
":",
"source",
",",
"domain",
"=",
"address",
"if",
"not",
"force",
":",
"proceed",
"=",
"click",
".",
"confirm",
"(",
"'Are you sure to delete the domain '",
"'mail forward %s@%s ?'",
"%",
"(",
"source",
",",
"domain",
")",
")",
"if",
"not",
"proceed",
":",
"return",
"result",
"=",
"gandi",
".",
"forward",
".",
"delete",
"(",
"domain",
",",
"source",
")",
"return",
"result"
] | Delete a domain mail forward. | [
"Delete",
"a",
"domain",
"mail",
"forward",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/forward.py#L71-L84 | train |
Gandi/gandi.cli | gandi/cli/commands/record.py | list | def list(gandi, domain, zone_id, output, format, limit):
"""List DNS zone records for a domain."""
options = {
'items_per_page': limit,
}
output_keys = ['name', 'type', 'value', 'ttl']
if not zone_id:
result = gandi.domain.info(domain)
zone_id = result['zone_id']
if not zone_id:
gandi.echo('No zone records found, domain %s doesn\'t seems to be '
'managed at Gandi.' % domain)
return
records = gandi.record.list(zone_id, options)
if not output and not format:
for num, rec in enumerate(records):
if num:
gandi.separator_line()
output_generic(gandi, rec, output_keys, justify=12)
elif output:
zone_filename = domain + "_" + str(zone_id)
if os.path.isfile(zone_filename):
open(zone_filename, 'w').close()
for record in records:
format_record = ('%s %s IN %s %s' %
(record['name'], record['ttl'],
record['type'], record['value']))
with open(zone_filename, 'ab') as zone_file:
zone_file.write(format_record + '\n')
gandi.echo('Your zone file have been writen in %s' % zone_filename)
elif format:
if format == 'text':
for record in records:
format_record = ('%s %s IN %s %s' %
(record['name'], record['ttl'],
record['type'], record['value']))
gandi.echo(format_record)
if format == 'json':
format_record = json.dumps(records, sort_keys=True,
indent=4, separators=(',', ': '))
gandi.echo(format_record)
return records | python | def list(gandi, domain, zone_id, output, format, limit):
"""List DNS zone records for a domain."""
options = {
'items_per_page': limit,
}
output_keys = ['name', 'type', 'value', 'ttl']
if not zone_id:
result = gandi.domain.info(domain)
zone_id = result['zone_id']
if not zone_id:
gandi.echo('No zone records found, domain %s doesn\'t seems to be '
'managed at Gandi.' % domain)
return
records = gandi.record.list(zone_id, options)
if not output and not format:
for num, rec in enumerate(records):
if num:
gandi.separator_line()
output_generic(gandi, rec, output_keys, justify=12)
elif output:
zone_filename = domain + "_" + str(zone_id)
if os.path.isfile(zone_filename):
open(zone_filename, 'w').close()
for record in records:
format_record = ('%s %s IN %s %s' %
(record['name'], record['ttl'],
record['type'], record['value']))
with open(zone_filename, 'ab') as zone_file:
zone_file.write(format_record + '\n')
gandi.echo('Your zone file have been writen in %s' % zone_filename)
elif format:
if format == 'text':
for record in records:
format_record = ('%s %s IN %s %s' %
(record['name'], record['ttl'],
record['type'], record['value']))
gandi.echo(format_record)
if format == 'json':
format_record = json.dumps(records, sort_keys=True,
indent=4, separators=(',', ': '))
gandi.echo(format_record)
return records | [
"def",
"list",
"(",
"gandi",
",",
"domain",
",",
"zone_id",
",",
"output",
",",
"format",
",",
"limit",
")",
":",
"options",
"=",
"{",
"'items_per_page'",
":",
"limit",
",",
"}",
"output_keys",
"=",
"[",
"'name'",
",",
"'type'",
",",
"'value'",
",",
"'ttl'",
"]",
"if",
"not",
"zone_id",
":",
"result",
"=",
"gandi",
".",
"domain",
".",
"info",
"(",
"domain",
")",
"zone_id",
"=",
"result",
"[",
"'zone_id'",
"]",
"if",
"not",
"zone_id",
":",
"gandi",
".",
"echo",
"(",
"'No zone records found, domain %s doesn\\'t seems to be '",
"'managed at Gandi.'",
"%",
"domain",
")",
"return",
"records",
"=",
"gandi",
".",
"record",
".",
"list",
"(",
"zone_id",
",",
"options",
")",
"if",
"not",
"output",
"and",
"not",
"format",
":",
"for",
"num",
",",
"rec",
"in",
"enumerate",
"(",
"records",
")",
":",
"if",
"num",
":",
"gandi",
".",
"separator_line",
"(",
")",
"output_generic",
"(",
"gandi",
",",
"rec",
",",
"output_keys",
",",
"justify",
"=",
"12",
")",
"elif",
"output",
":",
"zone_filename",
"=",
"domain",
"+",
"\"_\"",
"+",
"str",
"(",
"zone_id",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"zone_filename",
")",
":",
"open",
"(",
"zone_filename",
",",
"'w'",
")",
".",
"close",
"(",
")",
"for",
"record",
"in",
"records",
":",
"format_record",
"=",
"(",
"'%s %s IN %s %s'",
"%",
"(",
"record",
"[",
"'name'",
"]",
",",
"record",
"[",
"'ttl'",
"]",
",",
"record",
"[",
"'type'",
"]",
",",
"record",
"[",
"'value'",
"]",
")",
")",
"with",
"open",
"(",
"zone_filename",
",",
"'ab'",
")",
"as",
"zone_file",
":",
"zone_file",
".",
"write",
"(",
"format_record",
"+",
"'\\n'",
")",
"gandi",
".",
"echo",
"(",
"'Your zone file have been writen in %s'",
"%",
"zone_filename",
")",
"elif",
"format",
":",
"if",
"format",
"==",
"'text'",
":",
"for",
"record",
"in",
"records",
":",
"format_record",
"=",
"(",
"'%s %s IN %s %s'",
"%",
"(",
"record",
"[",
"'name'",
"]",
",",
"record",
"[",
"'ttl'",
"]",
",",
"record",
"[",
"'type'",
"]",
",",
"record",
"[",
"'value'",
"]",
")",
")",
"gandi",
".",
"echo",
"(",
"format_record",
")",
"if",
"format",
"==",
"'json'",
":",
"format_record",
"=",
"json",
".",
"dumps",
"(",
"records",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")",
"gandi",
".",
"echo",
"(",
"format_record",
")",
"return",
"records"
] | List DNS zone records for a domain. | [
"List",
"DNS",
"zone",
"records",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/record.py#L31-L77 | train |
Gandi/gandi.cli | gandi/cli/commands/record.py | create | def create(gandi, domain, zone_id, name, type, value, ttl):
"""Create new DNS zone record entry for a domain."""
if not zone_id:
result = gandi.domain.info(domain)
zone_id = result['zone_id']
if not zone_id:
gandi.echo('No zone records found, domain %s doesn\'t seems to be '
'managed at Gandi.' % domain)
return
record = {'type': type, 'name': name, 'value': value}
if ttl:
record['ttl'] = ttl
result = gandi.record.create(zone_id, record)
return result | python | def create(gandi, domain, zone_id, name, type, value, ttl):
"""Create new DNS zone record entry for a domain."""
if not zone_id:
result = gandi.domain.info(domain)
zone_id = result['zone_id']
if not zone_id:
gandi.echo('No zone records found, domain %s doesn\'t seems to be '
'managed at Gandi.' % domain)
return
record = {'type': type, 'name': name, 'value': value}
if ttl:
record['ttl'] = ttl
result = gandi.record.create(zone_id, record)
return result | [
"def",
"create",
"(",
"gandi",
",",
"domain",
",",
"zone_id",
",",
"name",
",",
"type",
",",
"value",
",",
"ttl",
")",
":",
"if",
"not",
"zone_id",
":",
"result",
"=",
"gandi",
".",
"domain",
".",
"info",
"(",
"domain",
")",
"zone_id",
"=",
"result",
"[",
"'zone_id'",
"]",
"if",
"not",
"zone_id",
":",
"gandi",
".",
"echo",
"(",
"'No zone records found, domain %s doesn\\'t seems to be '",
"'managed at Gandi.'",
"%",
"domain",
")",
"return",
"record",
"=",
"{",
"'type'",
":",
"type",
",",
"'name'",
":",
"name",
",",
"'value'",
":",
"value",
"}",
"if",
"ttl",
":",
"record",
"[",
"'ttl'",
"]",
"=",
"ttl",
"result",
"=",
"gandi",
".",
"record",
".",
"create",
"(",
"zone_id",
",",
"record",
")",
"return",
"result"
] | Create new DNS zone record entry for a domain. | [
"Create",
"new",
"DNS",
"zone",
"record",
"entry",
"for",
"a",
"domain",
"."
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/record.py#L101-L118 | train |
Gandi/gandi.cli | gandi/cli/commands/record.py | delete | def delete(gandi, domain, zone_id, name, type, value):
"""Delete a record entry for a domain"""
if not zone_id:
result = gandi.domain.info(domain)
zone_id = result['zone_id']
if not zone_id:
gandi.echo('No zone records found, domain %s doesn\'t seems to be '
'managed at Gandi.' % domain)
return
if not name and not type and not value:
proceed = click.confirm('This command without parameters --type, '
'--name or --value will remove all records'
' in this zone file. Are you sur to '
'perform this action ?')
if not proceed:
return
record = {'name': name, 'type': type, 'value': value}
result = gandi.record.delete(zone_id, record)
return result | python | def delete(gandi, domain, zone_id, name, type, value):
"""Delete a record entry for a domain"""
if not zone_id:
result = gandi.domain.info(domain)
zone_id = result['zone_id']
if not zone_id:
gandi.echo('No zone records found, domain %s doesn\'t seems to be '
'managed at Gandi.' % domain)
return
if not name and not type and not value:
proceed = click.confirm('This command without parameters --type, '
'--name or --value will remove all records'
' in this zone file. Are you sur to '
'perform this action ?')
if not proceed:
return
record = {'name': name, 'type': type, 'value': value}
result = gandi.record.delete(zone_id, record)
return result | [
"def",
"delete",
"(",
"gandi",
",",
"domain",
",",
"zone_id",
",",
"name",
",",
"type",
",",
"value",
")",
":",
"if",
"not",
"zone_id",
":",
"result",
"=",
"gandi",
".",
"domain",
".",
"info",
"(",
"domain",
")",
"zone_id",
"=",
"result",
"[",
"'zone_id'",
"]",
"if",
"not",
"zone_id",
":",
"gandi",
".",
"echo",
"(",
"'No zone records found, domain %s doesn\\'t seems to be '",
"'managed at Gandi.'",
"%",
"domain",
")",
"return",
"if",
"not",
"name",
"and",
"not",
"type",
"and",
"not",
"value",
":",
"proceed",
"=",
"click",
".",
"confirm",
"(",
"'This command without parameters --type, '",
"'--name or --value will remove all records'",
"' in this zone file. Are you sur to '",
"'perform this action ?'",
")",
"if",
"not",
"proceed",
":",
"return",
"record",
"=",
"{",
"'name'",
":",
"name",
",",
"'type'",
":",
"type",
",",
"'value'",
":",
"value",
"}",
"result",
"=",
"gandi",
".",
"record",
".",
"delete",
"(",
"zone_id",
",",
"record",
")",
"return",
"result"
] | Delete a record entry for a domain | [
"Delete",
"a",
"record",
"entry",
"for",
"a",
"domain"
] | 6ee5b8fc8ec44b0a6c232043ca610606ad8f693d | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/record.py#L138-L157 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.