Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
aab9ca0
fixed type in readme.rst
allmightyspiff Sep 4, 2019
a303dd7
Merge branch 'master' of github.com:softlayer/softlayer-python
allmightyspiff Sep 4, 2019
cb51390
Merge branch 'master' of github.com:softlayer/softlayer-python
allmightyspiff Sep 25, 2019
ef284ae
skeleton for autoscale
allmightyspiff Sep 25, 2019
e00e4cf
autoscale detail and list
allmightyspiff Sep 25, 2019
65baab0
Merge branch 'master' of github.com:allmightyspiff/softlayer-python
allmightyspiff Sep 26, 2019
6f60c7c
Merge branch 'autoscale' of github.com:allmightyspiff/softlayer-pytho…
allmightyspiff Sep 26, 2019
feb8f9a
autoscale details mostly done
allmightyspiff Sep 26, 2019
ebc80cd
added autoscale scale commands
allmightyspiff Sep 27, 2019
645df87
autoscale logs, tox fixes
allmightyspiff Sep 27, 2019
53c17e1
#627 autoscale feature documentation
allmightyspiff Sep 27, 2019
eed15b0
tox fixes
allmightyspiff Sep 27, 2019
69e11f1
Autoscale cli list and managers unit test.
Oct 3, 2019
2fcd61b
Fix analysis tox.
Oct 3, 2019
3f6f16c
Fix analysis tox.
Oct 3, 2019
d027f82
unit test logs and scale
Oct 3, 2019
292d4fa
unit test logs and scale
Oct 3, 2019
5cc7737
fix the tox analysis
Oct 3, 2019
63de0ad
Merge pull request #1174 from softlayer/fo_autoscale_test
allmightyspiff Oct 3, 2019
fbbe532
solved conflicts and fix code review comments
Oct 4, 2019
5056650
fix any problems with merge
caberos Oct 4, 2019
5e61352
adding a default value to dictionaries
ATGE Oct 4, 2019
a3605da
Merge remote-tracking branch 'upstream/autoscale' into autoscale
ATGE Oct 4, 2019
29ab911
added autoscale detail test
ATGE Oct 4, 2019
52d3600
fix identation
ATGE Oct 4, 2019
3e85319
Update SoftLayer_Scale_Group.py
caberos Oct 4, 2019
3dcf3f6
fix analysis tool
caberos Oct 4, 2019
8dd2ddb
Merge pull request #1175 from caberos/unittest_autoscale
allmightyspiff Oct 4, 2019
7980088
Merge pull request #1176 from ATGE/autoscale
allmightyspiff Oct 4, 2019
58b27c6
#627 added autoscale tag, to allow users to tag all guests in a group…
allmightyspiff Oct 4, 2019
878db94
Edit autoscale groups command
allmightyspiff Oct 8, 2019
f1922ab
tox fixes
allmightyspiff Oct 8, 2019
daeaff4
removed debug code
allmightyspiff Oct 8, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ For the CLI, just use the -vvv option. If you are using the REST endpoint, this

If you are using the library directly in python, you can do something like this.

.. code-bock:: python
.. code-block:: python

import SoftLayer
import logging
Expand Down
Empty file.
92 changes: 92 additions & 0 deletions SoftLayer/CLI/autoscale/detail.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""Get details of an Autoscale groups."""
# :license: MIT, see LICENSE for more details.

import click

import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.managers.autoscale import AutoScaleManager
from SoftLayer import utils


@click.command()
@click.argument('identifier')
@environment.pass_env
def cli(env, identifier):
"""Get details of an Autoscale groups."""

autoscale = AutoScaleManager(env.client)
group = autoscale.details(identifier)

# Group Config Table
table = formatting.KeyValueTable(["Group", "Value"])
table.align['Group'] = 'l'
table.align['Value'] = 'l'

table.add_row(['Id', group.get('id')])
# Ideally we would use regionalGroup->preferredDatacenter, but that generates an error.
table.add_row(['Datacenter', group['regionalGroup']['locations'][0]['longName']])
table.add_row(['Termination', utils.lookup(group, 'terminationPolicy', 'name')])
table.add_row(['Minimum Members', group.get('minimumMemberCount')])
table.add_row(['Maximum Members', group.get('maximumMemberCount')])
table.add_row(['Current Members', group.get('virtualGuestMemberCount')])
table.add_row(['Cooldown', "{} seconds".format(group.get('cooldown'))])
table.add_row(['Last Action', utils.clean_time(group.get('lastActionDate'))])

for network in group.get('networkVlans', []):
network_type = utils.lookup(network, 'networkVlan', 'networkSpace')
router = utils.lookup(network, 'networkVlan', 'primaryRouter', 'hostname')
vlan_number = utils.lookup(network, 'networkVlan', 'vlanNumber')
vlan_name = "{}.{}".format(router, vlan_number)
table.add_row([network_type, vlan_name])

env.fout(table)

# Template Config Table
config_table = formatting.KeyValueTable(["Template", "Value"])
config_table.align['Template'] = 'l'
config_table.align['Value'] = 'l'

template = group.get('virtualGuestMemberTemplate')

config_table.add_row(['Hostname', template.get('hostname')])
config_table.add_row(['Domain', template.get('domain')])
config_table.add_row(['Core', template.get('startCpus')])
config_table.add_row(['Ram', template.get('maxMemory')])
network = template.get('networkComponents')
config_table.add_row(['Network', network[0]['maxSpeed'] if network else 'Default'])
ssh_keys = template.get('sshKeys', [])
ssh_manager = SoftLayer.SshKeyManager(env.client)
for key in ssh_keys:
# Label isn't included when retrieved from the AutoScale group...
ssh_key = ssh_manager.get_key(key.get('id'))
config_table.add_row(['SSH Key {}'.format(ssh_key.get('id')), ssh_key.get('label')])
disks = template.get('blockDevices', [])
disk_type = "Local" if template.get('localDiskFlag') else "SAN"

for disk in disks:
disk_image = disk.get('diskImage')
config_table.add_row(['{} Disk {}'.format(disk_type, disk.get('device')), disk_image.get('capacity')])
config_table.add_row(['OS', template.get('operatingSystemReferenceCode')])
config_table.add_row(['Post Install', template.get('postInstallScriptUri') or 'None'])

env.fout(config_table)

# Policy Config Table
policy_table = formatting.KeyValueTable(["Policy", "Cooldown"])
policies = group.get('policies', [])
for policy in policies:
policy_table.add_row([policy.get('name'), policy.get('cooldown') or group.get('cooldown')])

env.fout(policy_table)

# Active Guests
member_table = formatting.Table(['Id', 'Hostname', 'Created'], title="Active Guests")
guests = group.get('virtualGuestMembers', [])
for guest in guests:
real_guest = guest.get('virtualGuest')
member_table.add_row([
real_guest.get('id'), real_guest.get('hostname'), utils.clean_time(real_guest.get('provisionDate'))
])
env.fout(member_table)
57 changes: 57 additions & 0 deletions SoftLayer/CLI/autoscale/edit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Edits an Autoscale group."""
# :license: MIT, see LICENSE for more details.

import click

from SoftLayer.CLI import environment
from SoftLayer.managers.autoscale import AutoScaleManager


@click.command()
@click.argument('identifier')
@click.option('--name', help="Scale group's name.")
@click.option('--min', 'minimum', type=click.INT, help="Set the minimum number of guests")
@click.option('--max', 'maximum', type=click.INT, help="Set the maximum number of guests")
@click.option('--userdata', help="User defined metadata string")
@click.option('--userfile', '-F', help="Read userdata from a file",
type=click.Path(exists=True, readable=True, resolve_path=True))
@click.option('--cpu', type=click.INT, help="Number of CPUs for new guests (existing not effected")
@click.option('--memory', type=click.INT, help="RAM in MB or GB for new guests (existing not effected")
@environment.pass_env
def cli(env, identifier, name, minimum, maximum, userdata, userfile, cpu, memory):
"""Edits an Autoscale group."""

template = {}
autoscale = AutoScaleManager(env.client)
group = autoscale.details(identifier)

template['name'] = name
template['minimumMemberCount'] = minimum
template['maximumMemberCount'] = maximum
virt_template = {}
if userdata:
virt_template['userData'] = [{"value": userdata}]
elif userfile:
with open(userfile, 'r') as userfile_obj:
virt_template['userData'] = [{"value": userfile_obj.read()}]
virt_template['startCpus'] = cpu
virt_template['maxMemory'] = memory

# Remove any entries that are `None` as the API will complain about them.
template['virtualGuestMemberTemplate'] = clean_dict(virt_template)
clean_template = clean_dict(template)

# If there are any values edited in the template, we need to get the OLD template values and replace them.
if template['virtualGuestMemberTemplate']:
# Update old template with new values
for key, value in clean_template['virtualGuestMemberTemplate'].items():
group['virtualGuestMemberTemplate'][key] = value
clean_template['virtualGuestMemberTemplate'] = group['virtualGuestMemberTemplate']

autoscale.edit(identifier, clean_template)
click.echo("Done")


def clean_dict(dictionary):
"""Removes any `None` entires from the dictionary"""
return {k: v for k, v in dictionary.items() if v}
29 changes: 29 additions & 0 deletions SoftLayer/CLI/autoscale/list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""List Autoscale groups."""
# :license: MIT, see LICENSE for more details.

import click

from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.managers.autoscale import AutoScaleManager
from SoftLayer import utils


@click.command()
@environment.pass_env
def cli(env):
"""List AutoScale Groups."""

autoscale = AutoScaleManager(env.client)
groups = autoscale.list()

table = formatting.Table(["Id", "Name", "Status", "Min/Max", "Running"])
table.align['Name'] = 'l'
for group in groups:
status = utils.lookup(group, 'status', 'name')
min_max = "{}/{}".format(group.get('minimumMemberCount'), group.get('maximumMemberCount'))
table.add_row([
group.get('id'), group.get('name'), status, min_max, group.get('virtualGuestMemberCount')
])

env.fout(table)
37 changes: 37 additions & 0 deletions SoftLayer/CLI/autoscale/logs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""Retreive logs for an autoscale group"""
# :license: MIT, see LICENSE for more details.

import click

from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.managers.autoscale import AutoScaleManager
from SoftLayer import utils


@click.command()
@click.argument('identifier')
@click.option('--date-min', '-d', 'date_min', type=click.DateTime(formats=["%Y-%m-%d", "%m/%d/%Y"]),
help='Earliest date to retreive logs for.')
@environment.pass_env
def cli(env, identifier, date_min):
"""Retreive logs for an autoscale group"""

autoscale = AutoScaleManager(env.client)

mask = "mask[id,createDate,description]"
object_filter = {}
if date_min:
object_filter['logs'] = {
'createDate': {
'operation': 'greaterThanDate',
'options': [{'name': 'date', 'value': [date_min.strftime("%m/%d/%Y")]}]
}
}

logs = autoscale.get_logs(identifier, mask=mask, object_filter=object_filter)
table = formatting.Table(['Date', 'Entry'], title="Logs")
table.align['Entry'] = 'l'
for log in logs:
table.add_row([utils.clean_time(log.get('createDate')), log.get('description')])
env.fout(table)
55 changes: 55 additions & 0 deletions SoftLayer/CLI/autoscale/scale.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""Scales an Autoscale group"""
# :license: MIT, see LICENSE for more details.

import click

from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.managers.autoscale import AutoScaleManager
from SoftLayer import utils


@click.command()
@click.argument('identifier')
@click.option('--up/--down', 'scale_up', is_flag=True, default=True,
help="'--up' adds guests, '--down' removes guests.")
@click.option('--by/--to', 'scale_by', is_flag=True, required=True,
help="'--by' will add/remove the specified number of guests."
" '--to' will add/remove a number of guests to get the group's guest count to the specified number.")
@click.option('--amount', required=True, type=click.INT, help="Number of guests for the scale action.")
@environment.pass_env
def cli(env, identifier, scale_up, scale_by, amount):
"""Scales an Autoscale group. Bypasses a scale group's cooldown period."""

autoscale = AutoScaleManager(env.client)

# Scale By, and go down, need to use negative amount
if not scale_up and scale_by:
amount = amount * -1

result = []
if scale_by:
click.secho("Scaling group {} by {}".format(identifier, amount), fg='green')
result = autoscale.scale(identifier, amount)
else:
click.secho("Scaling group {} to {}".format(identifier, amount), fg='green')
result = autoscale.scale_to(identifier, amount)

try:
# Check if the first guest has a cancellation date, assume we are removing guests if it is.
cancel_date = result[0]['virtualGuest']['billingItem']['cancellationDate'] or False
except (IndexError, KeyError, TypeError):
cancel_date = False

if cancel_date:
member_table = formatting.Table(['Id', 'Hostname', 'Created'], title="Cancelled Guests")
else:
member_table = formatting.Table(['Id', 'Hostname', 'Created'], title="Added Guests")

for guest in result:
real_guest = guest.get('virtualGuest')
member_table.add_row([
guest.get('id'), real_guest.get('hostname'), utils.clean_time(real_guest.get('createDate'))
])

env.fout(member_table)
33 changes: 33 additions & 0 deletions SoftLayer/CLI/autoscale/tag.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""Tags all guests in an autoscale group."""
# :license: MIT, see LICENSE for more details.

import click

from SoftLayer.CLI import environment
from SoftLayer.managers.autoscale import AutoScaleManager
from SoftLayer.managers.vs import VSManager


@click.command()
@click.argument('identifier')
@click.option('--tags', '-g', help="Tags to set for each guest in this group. Existing tags are overwritten. "
"An empty string will remove all tags")
@environment.pass_env
def cli(env, identifier, tags):
"""Tags all guests in an autoscale group.

--tags "Use, quotes, if you, want whitespace"

--tags Otherwise,Just,commas
"""

autoscale = AutoScaleManager(env.client)
vsmanager = VSManager(env.client)
mask = "mask[id,virtualGuestId,virtualGuest[tagReferences,id,hostname]]"
guests = autoscale.get_virtual_guests(identifier, mask=mask)
click.echo("New Tags: {}".format(tags))
for guest in guests:
real_guest = guest.get('virtualGuest')
click.echo("Setting tags for {}".format(real_guest.get('hostname')))
vsmanager.set_tags(tags, real_guest.get('id'),)
click.echo("Done")
8 changes: 8 additions & 0 deletions SoftLayer/CLI/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,14 @@

('report', 'SoftLayer.CLI.report'),
('report:bandwidth', 'SoftLayer.CLI.report.bandwidth:cli'),

('autoscale', 'SoftLayer.CLI.autoscale'),
('autoscale:list', 'SoftLayer.CLI.autoscale.list:cli'),
('autoscale:detail', 'SoftLayer.CLI.autoscale.detail:cli'),
('autoscale:scale', 'SoftLayer.CLI.autoscale.scale:cli'),
('autoscale:logs', 'SoftLayer.CLI.autoscale.logs:cli'),
('autoscale:tag', 'SoftLayer.CLI.autoscale.tag:cli'),
('autoscale:edit', 'SoftLayer.CLI.autoscale.edit:cli')
]

ALL_ALIASES = {
Expand Down
Loading