Commit c45788dd authored by Adam Lewenberg's avatar Adam Lewenberg
Browse files

start work on Python classes

parent 8cffae16
import time
import sys
import pprint
import yaml
import os
# Deployment
# DeploymentSpec
# PodTemplateSpec
# PodSpec
# Containers
# Image
# Port
# Probes
# Env
# VolumeMounts
# Volumes
from kubernetes.stream import stream
from kubernetes import client, config
from kubernetes.client.models.v1_object_meta import V1ObjectMeta
from kubernetes.client.models.v1_label_selector import *
from kubernetes.client.models.v1_deployment import *
from kubernetes.client.models.v1_deployment_spec import *
from kubernetes.client.models.v1_pod_template_spec import *
from kubernetes.client.models.v1_pod_spec import *
from kubernetes.client.models.v1_container import *
from kubernetes.client.models.v1_container_port import *
from kubernetes.client.models.v1_env_var import *
from kubernetes.client.models.v1_probe import *
from kubernetes.client.models.v1_http_get_action import *
from kubernetes.client.models.v1_volume_mount import *
from kubernetes.client.models.v1_volume import *
from kubernetes.client.models.v1_secret_volume_source import *
# Extra
from kubernetes.client.models.v1_pod import *
#################################################################
## Make a class for our Apache Shib Pod
class Project():
ATTRIBUTE_MAP = {
'app_name': 'apache-shib',
'app_namespace': None,
'image': None,
'image_tag': None,
'image_pull_policy': 'Always',
'apache_port': '80',
'server_name': None,
'replicas': 1,
}
def __init__(self, values = None, read_via = 'env_var'):
name = values['name']
for key, value in Project.ATTRIBUTE_MAP.items():
setattr(self, key, value)
self.container = ApacheShibContainer(values=values)
self.pod_spec = ApacheShibPodSpec(containers=[self.container])
self.pod_template_spec = ApacheShibPodTemplateSpec(spec=self.pod_spec)
self.deployment_spec = ApacheShibDeploymentSpec(pod_template_spec=self.pod_template_spec)
self.deployment = ApacheShibDeployment(name=name, spec=self.deployment_spec)
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.deployment.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def to_yaml(self):
return yaml.dump(self.deployment.to_dict())
@staticmethod
def load_values_from_yaml(yaml_file):
data = yaml.safe_load(open(yaml_file))
return data
def load_values_from_environment(self):
if (os.environ['app_namespace']):
settatr(self, 'app_namespace', os.environ['app_namespace'])
class ApacheShibDeployment(V1Deployment):
def __init__(self, name, spec):
metadata = V1ObjectMeta(name=name)
super(ApacheShibDeployment, self).__init__(metadata=metadata, spec=spec)
class ApacheShibDeploymentSpec(V1DeploymentSpec):
def __init__(self, pod_template_spec):
selector = V1LabelSelector(match_labels = {'app': 'my-app'})
super(ApacheShibDeploymentSpec, self).__init__(
template=pod_template_spec,
selector=selector,
replicas = 3,
)
class ApacheShibPodTemplateSpec(V1PodTemplateSpec):
def __init__(self, spec):
metadata = V1ObjectMeta(labels={'app': 'my-app'})
super(ApacheShibPodTemplateSpec, self).__init__(metadata=metadata, spec=spec)
class ApacheShibPodSpec(V1PodSpec):
def __init__(self, containers):
vol_saml_crt = V1Volume(name='saml-crt',
secret=V1SecretVolumeSource(secret_name='something-saml-crt')
)
vol_saml_key = V1Volume(name='saml-key',
secret=V1SecretVolumeSource(secret_name='something-saml-key')
)
super(ApacheShibPodSpec, self).__init__(
containers=containers,
volumes=[vol_saml_crt, vol_saml_key],
)
class ApacheShibContainer(V1Container):
def __init__(self, values):
name = values['name']
super(ApacheShibContainer, self).__init__(name=name)
# Docker image
self.image = values['image']
self.image_pull_policy = values['imagePullPolicy']
# Port
port = V1ContainerPort(name='http', container_port='80', protocol='TCP')
self.ports = [port]
# Readiness and liveness probes
http_get = V1HTTPGetAction(port="80", path='/Shibboleth.sso/Metadata')
readiness_probe = V1Probe(http_get=http_get,
initial_delay_seconds=10,
period_seconds=10,
)
self.readiness_probe = readiness_probe
self.liveness_probe = readiness_probe
# Environment variables
env_vars = [
V1EnvVar(name='SHIB_ENTITY_ID', value=values['SHIB_ENTITY_ID']),
V1EnvVar(name='SERVER_NAME', value=values['SERVER_NAME']),
]
self.env = env_vars
# Volume mounts
vol_mounts = [
V1VolumeMount(name='saml-crt',
mount_path='/etc/ssl/certs/saml-crt.pem',
sub_path='saml-crt.pem'
),
V1VolumeMount(name='saml-key',
mount_path='/etc/ssl/certs/saml-key.pem',
sub_path='saml-key.pem'
),
]
self.volume_mounts = vol_mounts
#################################################################
values = {
'name': 'httpd',
'image': 'nginx',
'imagePullPolicy': 'always',
'SERVER_NAME': 'example.com',
'SHIB_ENTITY_ID': 'https://example.com',
}
yaml_file = './test.yaml'
values = Project.load_values_from_yaml(yaml_file)
config.load_kube_config()
container = V1Container(name='nginx')
#container = ApacheShibContainer(values=values)
#pod_spec = ApacheShibPodSpec(containers=[container])
#pod_template_spec = ApacheShibPodTemplateSpec(spec=pod_spec)
#deployment_spec = ApacheShibDeploymentSpec(pod_template_spec=pod_template_spec)
#deployment = ApacheShibDeployment(name='zzzzzzz', spec=deployment_spec)
project = Project(values)
project.load_values_from_environment()
#print(project)
#print(project.to_yaml())
# Override something
project.deployment.spec.replicas = 4
print(project.to_yaml())
#print(container)
sys.exit()
api_instance = client.CoreV1Api()
def create_ns(namespace):
ns = client.V1Namespace(metadata=client.V1ObjectMeta(name=namespace))
resp = api_instance.create_namespace(body=ns)
print resp
def create_pod(namespace):
pod_name = 'nginx'
# Create a Pod with nginx
pod_manifest = {
'apiVersion': 'v1',
'kind': 'Pod',
'metadata': {
'name': pod_name
},
'spec': {
'containers': [{
'image': 'busybox',
'name': 'sleep',
"args": [
"/bin/sh",
"-c",
"while true;do date;sleep 5; done"
]
}]
}
}
resp = api_instance.create_namespaced_pod(body=pod_manifest,
namespace=namespace)
while True:
resp = api_instance.read_namespaced_pod(name=pod_name,
namespace=namespace)
if resp.status.phase != 'Pending':
break
time.sleep(1)
print("Done.")
exec_command = [
'/bin/sh',
'-c',
'echo This message goes to stderr; echo This message goes to stdout']
print("sleep a bit")
time.sleep(3)
print("done sleeping")
resp = stream(api_instance.connect_get_namespaced_pod_exec,
pod_name,
namespace,
command=exec_command,
stderr=True, stdin=False,
stdout=True, tty=False)
print("Response: " + resp)
#### #### #### #### #### #### #### #### #### #### ####
namespace = 'adamhl-testing'
pod_spec = V1PodSpec(containers=[container])
pod_metadata = V1ObjectMeta(name='example-pod')
pod = V1Pod(metadata=pod_metadata, spec=pod_spec)
# Start pod?
resp = api_instance.create_namespaced_pod(body=pod,
namespace=namespace)
print (pod.to_dict())
#create_pod(namespace)
#v1 = client.CoreV1Api()
#print("Listing pods with their IPs:")
#ret = v1.list_pod_for_all_namespaces(watch=False)
#for i in ret.items:
# print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
#
---
app_name: apache-shib
name: httpd
image: nginx
imagePullPolicy: always
SERVER_NAME: example.com
SHIB_ENTITY_ID: https://example.com
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment