Skip to content

Commit

Permalink
'kube-network' option
Browse files Browse the repository at this point in the history
  • Loading branch information
Smana committed Apr 15, 2016
1 parent 89caa85 commit f657467
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 10 deletions.
20 changes: 14 additions & 6 deletions bin/kargo
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# You should have received a copy of the GNU General Public License
# along with Foobar. If not, see <http://www.gnu.org/licenses/>.

__version__ = '0.2.3'
__version__ = '0.2.4'

import os
import argparse
Expand Down Expand Up @@ -69,17 +69,18 @@ if __name__ == '__main__':
)
subparsers = parser.add_subparsers(help='commands')

parser.add_argument(
'-v', '--version', action='version',
version='%(prog)s'+' %s' % __version__
)

# Options shared by all subparsers
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument(
'-p', '--path', dest='kargo_path',
help='Where the Ansible playbooks are installed'
)
parent_parser.add_argument('--config', dest='configfile', help="Config file")
parser.add_argument(
'--version', action='version',
version='%(prog)s'+' %s' % __version__
)
parent_parser.add_argument(
'-y', '--assumeyes', default=False, dest='assume_yes', action='store_true',
help='When a yes/no prompt would be presented, assume that the user entered "yes"'
Expand Down Expand Up @@ -177,12 +178,19 @@ if __name__ == '__main__':
help='Create GCE machines and generate inventory'
)
deploy_parser.add_argument(
'-k', '--sshkey', dest='ssh_key', help='ssh key for authentication on remote servers'
'-k', '--sshkey', dest='ssh_key',
help='ssh key for authentication on remote servers'
)
deploy_parser.add_argument(
'-u', '--user', dest='ansible_user', default=getpass.getuser(),
help='Ansible SSH user (remote user)'
)
deploy_parser.add_argument(
'-N', '--kube-network', dest='kube_network', default='10.233.0.0/16',
help="""Network to be used inside the cluster (/16),
(must not overlap with any of your infrastructure networks).
default: 10.233.0.0/16"""
)
deploy_parser.add_argument(
'-n', '--network-plugin', default='flannel',
choices=['flannel', 'weave', 'calico']
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

setup(
name='kargo',
version='0.2.3',
version='0.2.4',
description="Kargo kubernetes cluster deployment",
author="Smaine Kahlouch",
author_email='smainklh@gmail.com',
Expand Down
2 changes: 1 addition & 1 deletion src/kargo/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# (c) 2016, Smaine Kahlouch <smainklh@gmail.com>
__author__ = 'smana'
__version__ = '0.2.3'
__version__ = '0.2.4'
19 changes: 18 additions & 1 deletion src/kargo/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@

import sys
import os
import requests
import random
import yaml
import json
from kargo.inventory import CfgInventory
Expand Down Expand Up @@ -130,6 +132,16 @@ def create_instances(self):
self.logger.critical('Cannot create instances: %s' % emsg)
sys.exit(1)

def get_cluster_name(self):
try:
word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = requests.get(word_site)
words = response.content.splitlines()
cluster_name = random.choice(words).decode("utf-8")
except:
cluster_name = id_generator()
return(cluster_name)


class AWS(Cloud):

Expand Down Expand Up @@ -193,6 +205,7 @@ def gen_gce_playbook(self):
]
# Define instance names
gce_instance_names = list()
cluster_name = self.get_cluster_name()
for x in range(self.options['count']):
if self.options['add_node']:
current_inventory = self.Cfg.read_inventory()
Expand All @@ -202,10 +215,14 @@ def gen_gce_playbook(self):
gce_instance_names.append(
cluster_name + '-%s' % id_generator()
)
else:
elif 'cluster_name' in self.options.keys():
gce_instance_names.append(
self.options['cluster_name'] + '-%s' % id_generator()
)
else:
gce_instance_names.append(
'k8s-' + cluster_name + '-%s' % id_generator()
)
gce_instance_names = ','.join(gce_instance_names)
# Define GCE task
gce_task = {'gce': {},
Expand Down
14 changes: 14 additions & 0 deletions src/kargo/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import logging
import shutil
import os
import netaddr
import sys
import string
import random
Expand Down Expand Up @@ -127,3 +128,16 @@ def run_command(description, cmd):

def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))


def validate_cidr(cidr, version):
"""
Validates that a CIDR is valid. Returns true if valid, false if
not. Version can be "4", "6", None for "IPv4", "IPv6", or "either"
respectively.
"""
try:
ip = netaddr.IPNetwork(cidr, version=version)
return True
except (netaddr.core.AddrFormatError, ValueError, TypeError):
return False
39 changes: 38 additions & 1 deletion src/kargo/deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@
import sys
import os
import signal
import netaddr
from subprocess import PIPE, STDOUT, Popen, check_output, CalledProcessError
from kargo.common import get_logger, query_yes_no, run_command, which
from kargo.common import get_logger, query_yes_no, run_command, which, validate_cidr
from ansible.utils.display import Display
display = Display()
playbook_exec = which('ansible-playbook')
Expand Down Expand Up @@ -134,6 +135,25 @@ def coreos_bootstrap(self):
os.kill(int(os.environ.get('SSH_AGENT_PID')), signal.SIGTERM)
sys.exit(1)

def get_subnets(self):
'''Check the subnet value and split into 2 distincts subnets'''
svc_pfx = 24
pods_pfx = 17
net = netaddr.IPNetwork(self.options['kube_network'])
pfx_error_msg = (
"You have to choose a network with a prefix length = 16, "
"Please use Ansible options if you need to configure a different netmask."
)
if net.prefixlen is not 16:
display.error(pfx_error_msg)
os.kill(int(os.environ.get('SSH_AGENT_PID')), signal.SIGTERM)
sys.exit(1)
subnets = list(net.subnet(pods_pfx))
pods_network, remaining = subnets[0:2]
net = netaddr.IPNetwork(remaining)
svc_network = list(net.subnet(svc_pfx))[0]
return(svc_network, pods_network)

def deploy_kubernetes(self):
'''
Run the ansible playbook command
Expand All @@ -145,13 +165,30 @@ def deploy_kubernetes(self):
'-b', '--become-user=root', '-i', self.inventorycfg,
os.path.join(self.options['kargo_path'], 'cluster.yml')
]
# Configure the network subnets pods and k8s services
if not validate_cidr(self.options['kube_network'], version=4):
display.error('Invalid Kubernetes network address')
os.kill(int(os.environ.get('SSH_AGENT_PID')), signal.SIGTERM)
sys.exit(1)
svc_network, pods_network = self.get_subnets()
# Add any additionnal Ansible option
if 'ansible-opts' in self.options.keys():
cmd = cmd + self.options['ansible-opts'].split(' ')
for cloud in ['aws', 'gce']:
if self.options[cloud]:
cmd = cmd + ['-e', 'cloud_provider=%s' % cloud]
if not self.options['coreos']:
self.check_ping()
display.display(
'Kubernetes services network : %s (%s IPs)'
% (svc_network.cidr, str(svc_network.size.real - 2)),
color='bright gray'
)
display.display(
'Pods network : %s (%s IPs)'
% (pods_network.cidr, str(pods_network.size.real - 2)),
color='bright gray'
)
display.display(' '.join(cmd), color='bright blue')
if not self.options['assume_yes']:
if not query_yes_no(
Expand Down

0 comments on commit f657467

Please sign in to comment.