SlideShare a Scribd company logo
1 of 14
Download to read offline
Mesos Python framework
O. Sallou, DevExp 2016
CC-BY-SA 3.0
Interacting with Mesos, 2 choices
Python API:
- not compatible with Python 3
- Easy to implement
- Bindings over C API
HTTP API:
- HTTP calls with persistent connection and streaming
- Recent
- Language independent,
Workflow
Register => Listen for offer => accept/decline offer => listen for job status
Messages use Protobuf [0], HTTP interface also supports JSON.
See Mesos protobuf definition [1] to read or create messages.
[0] https://developers.google.com/protocol-buffers/
[1] https://github.com/apache/mesos/blob/master/include/mesos/mesos.proto
Simple example
Python API
Register
framework = mesos_pb2.FrameworkInfo()
# mesos_pb2.XXX() read/use/write protobuf Mesos objects
framework.user = "" # Have Mesos fill in the current user.
framework.name = "Example Mesos framework"
framework.failover_timeout = 3600 * 24*7 # 1 week
# Optionally, restart from a previous run
mesos_framework_id = mesos_pb2.FrameworkID()
mesos_framework_id.value = XYZ
framework.id.MergeFrom(mesos_framework_id)
framework.principal = "godocker-mesos-framework"
# We will create our scheduler class MesosScheduler in next slide
mesosScheduler = MesosScheduler(1, executor)
# Let’s declare a framework, with a scheduler to manage offers
driver = mesos.native.MesosSchedulerDriver(
mesosScheduler,
framework,
‘zk://127.0.01:2881’)
driver.start()
executor = mesos_pb2.ExecutorInfo()
executor.executor_id.value = "sample"
executor.name = "Example executor"
When scheduler ends...
When scheduler stops, Mesos will kill any remaining tasks after
“failover_timeout” value.
One can set FrameworkID to restart framework and keep same context.
Mesos will keep tasks, and send status messages to framework.
Scheduler skeleton
class MesosScheduler(mesos.interface.Scheduler):
def registered(self, driver, frameworkId, masterInfo):
logging.info("Registered with framework ID %s" % frameworkId.value)
self.frameworkId = frameworkId.value
def resourceOffers(self, driver, offers):
'''
Receive offers, an offer defines a node
with available resources (cpu, mem, etc.)
'''
for offer in offers:
logging.debug('Mesos:Offer:Decline)
driver.declineOffer(offer.id)
def statusUpdate(self, driver, update):
'''
Receive status info from submitted tasks
(switch to running, failure of node, etc.)
'''
logging.debug("Task %s is in state %s" % 
(update.task_id.value, mesos_pb2.TaskState.Name
(update.state)))
def frameworkMessage(self, driver,
executorId, slaveId, message):
logging.debug("Received framework message")
# usually, nothing to do here
Messages are asynchronous
Status updates and offers are asynchronous callbacks. Scheduler run in a
separate thread.
You’re never the initiator of the requests (except registration), but you will
receive callback messages when something change on Mesos side (job switch
to running, node failure, …)
Submit a task
for offer in offers:
# Get available cpu and mem for this offer
offerCpus = 0
offerMem = 0
for resource in offer.resources:
if resource.name == "cpus":
offerCpus += resource.scalar.value
elif resource.name == "mem":
offerMem += resource.scalar.value
# We could chek for other resources here
logging.debug("Mesos:Received offer %s with cpus: %s and mem: %s" 
% (offer.id.value, offerCpus, offerMem))
# We should check that offer has enough resources
sample_task = create_a_sample_task(offer)
array_of_task = [ sample_task ]
driver.launchTasks(offer.id, array_of_task)
Mesos support any custom resource definition on
nodes (gpu, slots, disk, …), using scalar or range
values
When a task is launched, requested resources will be
removed from available resources for the selected
node.
Next offers won’t propose thoses resources again
until task is over (or killed).
Define a task
def create_a_sample_task(offer):
task = mesos_pb2.TaskInfo()
# The container part (native or docker)
container = mesos_pb2.ContainerInfo()
container.type = 1 # mesos_pb2.ContainerInfo.Type.DOCKER
# Let’s add a volume
volume = container.volumes.add()
volume.container_path = “/tmp/test”
volume.host_path = “/tmp/incontainer”
volume.mode = 1 # mesos_pb2.Volume.Mode.RW
# The command to execute, if not using entrypoint
command = mesos_pb2.CommandInfo()
command.value = “echo hello world”
task.command.MergeFrom(command)
# Unique identifier (or let mesos assign one)
task.task_id.value = XYZ_UNIQUE_IDENTIFIER
# the slave where task is executed
task.slave_id.value = offer.slave_id.value
task.name = “my_sample_task”
# The resources/requirements
# Resources have names, cpu, mem and ports are available
# by default, one can define custom ones per slave node
# and get them by their name here
cpus = task.resources.add()
cpus.name = "cpus"
cpus.type = mesos_pb2.Value.SCALAR
cpus.scalar.value = 2
mem = task.resources.add()
mem.name = "mem"
mem.type = mesos_pb2.Value.SCALAR
mem.scalar.value = 3000 #3 Go
Define a task (next)
# Now the Docker part
docker = mesos_pb2.ContainerInfo.DockerInfo()
docker.image = “debian:latest”
docker.network = 2 # mesos_pb2.ContainerInfo.DockerInfo.Network.BRIDGE
docker.force_pull_image = True
container.docker.MergeFrom(docker)
# Let’s map some ports, ports are resources like cpu and mem
# We will map container port 80 to an available host port
# Let’s pick the first available port for this offer, for simplicity
# we will skip here controls and suppose there is at least one port
offer_port = None
for resource in offer.resources:
if resource.name == "ports":
for mesos_range in resource.ranges.range:
offer_port = mesos_range.begin
break
# We map port 80 to offer_port in container
docker_port = docker.port_mappings.add()
docker_port.host_port = 80
docker_port.container_port = offer_port
# We tell mesos that we reserve this port
# Mesos will remove it from next offers until task
completion
mesos_ports = task.resources.add()
mesos_ports.name = "ports"
mesos_ports.type = mesos_pb2.Value.RANGES
port_range = mesos_ports.ranges.range.add()
port_range.begin = offer_port
port_range.end = offer_port
task.container.MergeFrom(container)
return task
Task status
def statusUpdate(self, driver, update):
'''
Receive status info from submitted tasks
(switch to running, failure of node, etc.)
'''
logging.debug("Task %s is in state %s" % 
(update.task_id.value, mesos_pb2.TaskState.Name(update.state)))
if int(update.state= == 1:
#Switched to RUNNING
container_info = json.loads(update.data)
if int(update.state) in [2,3,4,5,7]:
# Over or failure
logging.error(“Task is over or failed”)
Want to kill a task?
def resourceOffers(self, driver, offers):
….
task_id = mesos_pb2.TaskID()
task_id.value = my_unique_task_id
driver.killTask(task_id)
A framework
Quite easy to setup
Many logs on Mesos side for
debug
Share the same resources with
other frameworks
Different executors (docker,
native, …)
In a few lines of code

More Related Content

What's hot

Introduction to mesos bay
Introduction to mesos bayIntroduction to mesos bay
Introduction to mesos bayhongbin034
 
Making Apache Kafka Elastic with Apache Mesos
Making Apache Kafka Elastic with Apache MesosMaking Apache Kafka Elastic with Apache Mesos
Making Apache Kafka Elastic with Apache MesosJoe Stein
 
Introduction to Mesos
Introduction to MesosIntroduction to Mesos
Introduction to Mesoskoboltmarky
 
Hands On Intro to Node.js
Hands On Intro to Node.jsHands On Intro to Node.js
Hands On Intro to Node.jsChris Cowan
 
Configuring MongoDB HA Replica Set on AWS EC2
Configuring MongoDB HA Replica Set on AWS EC2Configuring MongoDB HA Replica Set on AWS EC2
Configuring MongoDB HA Replica Set on AWS EC2ShepHertz
 
Integrating Docker with Mesos and Marathon
Integrating Docker with Mesos and MarathonIntegrating Docker with Mesos and Marathon
Integrating Docker with Mesos and MarathonRishabh Chaudhary
 
Terraform modules restructured
Terraform modules restructuredTerraform modules restructured
Terraform modules restructuredAmi Mahloof
 
[오픈소스컨설팅] EFK Stack 소개와 설치 방법
[오픈소스컨설팅] EFK Stack 소개와 설치 방법[오픈소스컨설팅] EFK Stack 소개와 설치 방법
[오픈소스컨설팅] EFK Stack 소개와 설치 방법Open Source Consulting
 
Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021TomStraub5
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introductionJason Vance
 
Building Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker SwarmBuilding Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker SwarmWei Lin
 
Zookeeper In Action
Zookeeper In ActionZookeeper In Action
Zookeeper In Actionjuvenxu
 
WebCamp 2016: DevOps. Ярослав Погребняк: Gobetween - новый лоад балансер для ...
WebCamp 2016: DevOps. Ярослав Погребняк: Gobetween - новый лоад балансер для ...WebCamp 2016: DevOps. Ярослав Погребняк: Gobetween - новый лоад балансер для ...
WebCamp 2016: DevOps. Ярослав Погребняк: Gobetween - новый лоад балансер для ...WebCamp
 
Drupaljam 2017 - Deploying Drupal 8 onto Hosted Kubernetes in Google Cloud
Drupaljam 2017 - Deploying Drupal 8 onto Hosted Kubernetes in Google CloudDrupaljam 2017 - Deploying Drupal 8 onto Hosted Kubernetes in Google Cloud
Drupaljam 2017 - Deploying Drupal 8 onto Hosted Kubernetes in Google CloudDropsolid
 

What's hot (20)

Introduction to mesos bay
Introduction to mesos bayIntroduction to mesos bay
Introduction to mesos bay
 
Making Apache Kafka Elastic with Apache Mesos
Making Apache Kafka Elastic with Apache MesosMaking Apache Kafka Elastic with Apache Mesos
Making Apache Kafka Elastic with Apache Mesos
 
Introduction to Mesos
Introduction to MesosIntroduction to Mesos
Introduction to Mesos
 
Apache mesos - overview
Apache mesos - overviewApache mesos - overview
Apache mesos - overview
 
Hands On Intro to Node.js
Hands On Intro to Node.jsHands On Intro to Node.js
Hands On Intro to Node.js
 
Java 8 고급 (6/6)
Java 8 고급 (6/6)Java 8 고급 (6/6)
Java 8 고급 (6/6)
 
Terraform day02
Terraform day02Terraform day02
Terraform day02
 
Configuring MongoDB HA Replica Set on AWS EC2
Configuring MongoDB HA Replica Set on AWS EC2Configuring MongoDB HA Replica Set on AWS EC2
Configuring MongoDB HA Replica Set on AWS EC2
 
Integrating Docker with Mesos and Marathon
Integrating Docker with Mesos and MarathonIntegrating Docker with Mesos and Marathon
Integrating Docker with Mesos and Marathon
 
Terraform modules restructured
Terraform modules restructuredTerraform modules restructured
Terraform modules restructured
 
[오픈소스컨설팅] EFK Stack 소개와 설치 방법
[오픈소스컨설팅] EFK Stack 소개와 설치 방법[오픈소스컨설팅] EFK Stack 소개와 설치 방법
[오픈소스컨설팅] EFK Stack 소개와 설치 방법
 
Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021Developing Terraform Modules at Scale - HashiTalks 2021
Developing Terraform Modules at Scale - HashiTalks 2021
 
Hadoop on ec2
Hadoop on ec2Hadoop on ec2
Hadoop on ec2
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introduction
 
Building Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker SwarmBuilding Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker Swarm
 
Zookeeper In Action
Zookeeper In ActionZookeeper In Action
Zookeeper In Action
 
WebCamp 2016: DevOps. Ярослав Погребняк: Gobetween - новый лоад балансер для ...
WebCamp 2016: DevOps. Ярослав Погребняк: Gobetween - новый лоад балансер для ...WebCamp 2016: DevOps. Ярослав Погребняк: Gobetween - новый лоад балансер для ...
WebCamp 2016: DevOps. Ярослав Погребняк: Gobetween - новый лоад балансер для ...
 
Drupaljam 2017 - Deploying Drupal 8 onto Hosted Kubernetes in Google Cloud
Drupaljam 2017 - Deploying Drupal 8 onto Hosted Kubernetes in Google CloudDrupaljam 2017 - Deploying Drupal 8 onto Hosted Kubernetes in Google Cloud
Drupaljam 2017 - Deploying Drupal 8 onto Hosted Kubernetes in Google Cloud
 
Kafka ops-new
Kafka ops-newKafka ops-new
Kafka ops-new
 
Terraform day03
Terraform day03Terraform day03
Terraform day03
 

Viewers also liked

Dynamic Scheduling - Federated clusters in mesos
Dynamic Scheduling - Federated clusters in mesosDynamic Scheduling - Federated clusters in mesos
Dynamic Scheduling - Federated clusters in mesosAaron Carey
 
Strata SC 2014: Apache Mesos as an SDK for Building Distributed Frameworks
Strata SC 2014: Apache Mesos as an SDK for Building Distributed FrameworksStrata SC 2014: Apache Mesos as an SDK for Building Distributed Frameworks
Strata SC 2014: Apache Mesos as an SDK for Building Distributed FrameworksPaco Nathan
 
MesosCon EU - HTTP API Framework
MesosCon EU - HTTP API FrameworkMesosCon EU - HTTP API Framework
MesosCon EU - HTTP API FrameworkMarco Massenzio
 
Getting Started Hacking OpenNebula - Fosdem-2013
Getting Started Hacking OpenNebula - Fosdem-2013Getting Started Hacking OpenNebula - Fosdem-2013
Getting Started Hacking OpenNebula - Fosdem-2013OpenNebula Project
 
Meson: Building a Machine Learning Orchestration Framework on Mesos
Meson: Building a Machine Learning Orchestration Framework on MesosMeson: Building a Machine Learning Orchestration Framework on Mesos
Meson: Building a Machine Learning Orchestration Framework on MesosAntony Arokiasamy
 
Meson: Heterogeneous Workflows with Spark at Netflix
Meson: Heterogeneous Workflows with Spark at NetflixMeson: Heterogeneous Workflows with Spark at Netflix
Meson: Heterogeneous Workflows with Spark at NetflixAntony Arokiasamy
 
DC/OS: The definitive platform for modern apps
DC/OS: The definitive platform for modern appsDC/OS: The definitive platform for modern apps
DC/OS: The definitive platform for modern appsDatio Big Data
 
Deploying Docker Containers at Scale with Mesos and Marathon
Deploying Docker Containers at Scale with Mesos and MarathonDeploying Docker Containers at Scale with Mesos and Marathon
Deploying Docker Containers at Scale with Mesos and MarathonDiscover Pinterest
 
Apache Kafka, HDFS, Accumulo and more on Mesos
Apache Kafka, HDFS, Accumulo and more on MesosApache Kafka, HDFS, Accumulo and more on Mesos
Apache Kafka, HDFS, Accumulo and more on MesosJoe Stein
 
TDC2016POA | Trilha Infraestrutura - Apache Mesos & Marathon: gerenciando rem...
TDC2016POA | Trilha Infraestrutura - Apache Mesos & Marathon: gerenciando rem...TDC2016POA | Trilha Infraestrutura - Apache Mesos & Marathon: gerenciando rem...
TDC2016POA | Trilha Infraestrutura - Apache Mesos & Marathon: gerenciando rem...tdc-globalcode
 
Container Orchestration Wars (Micro Edition)
Container Orchestration Wars (Micro Edition)Container Orchestration Wars (Micro Edition)
Container Orchestration Wars (Micro Edition)Karl Isenberg
 
CI/CD with Docker, DC/OS, and Jenkins
CI/CD with Docker, DC/OS, and JenkinsCI/CD with Docker, DC/OS, and Jenkins
CI/CD with Docker, DC/OS, and JenkinsKarl Isenberg
 
Piloter un loadbalancer pour exposer les microservoces de mon cluster Mesos/M...
Piloter un loadbalancer pour exposer les microservoces de mon cluster Mesos/M...Piloter un loadbalancer pour exposer les microservoces de mon cluster Mesos/M...
Piloter un loadbalancer pour exposer les microservoces de mon cluster Mesos/M...Kodo Kojo
 
Container Orchestration Wars
Container Orchestration WarsContainer Orchestration Wars
Container Orchestration WarsKarl Isenberg
 
Understanding Kubernetes
Understanding KubernetesUnderstanding Kubernetes
Understanding KubernetesTu Pham
 
"On-premises" FaaS on Kubernetes
"On-premises" FaaS on Kubernetes"On-premises" FaaS on Kubernetes
"On-premises" FaaS on KubernetesAlex Casalboni
 

Viewers also liked (20)

Dynamic Scheduling - Federated clusters in mesos
Dynamic Scheduling - Federated clusters in mesosDynamic Scheduling - Federated clusters in mesos
Dynamic Scheduling - Federated clusters in mesos
 
Strata SC 2014: Apache Mesos as an SDK for Building Distributed Frameworks
Strata SC 2014: Apache Mesos as an SDK for Building Distributed FrameworksStrata SC 2014: Apache Mesos as an SDK for Building Distributed Frameworks
Strata SC 2014: Apache Mesos as an SDK for Building Distributed Frameworks
 
MesosCon EU - HTTP API Framework
MesosCon EU - HTTP API FrameworkMesosCon EU - HTTP API Framework
MesosCon EU - HTTP API Framework
 
Mesos sys adminday
Mesos sys admindayMesos sys adminday
Mesos sys adminday
 
Getting Started Hacking OpenNebula - Fosdem-2013
Getting Started Hacking OpenNebula - Fosdem-2013Getting Started Hacking OpenNebula - Fosdem-2013
Getting Started Hacking OpenNebula - Fosdem-2013
 
Meson: Building a Machine Learning Orchestration Framework on Mesos
Meson: Building a Machine Learning Orchestration Framework on MesosMeson: Building a Machine Learning Orchestration Framework on Mesos
Meson: Building a Machine Learning Orchestration Framework on Mesos
 
Meson: Heterogeneous Workflows with Spark at Netflix
Meson: Heterogeneous Workflows with Spark at NetflixMeson: Heterogeneous Workflows with Spark at Netflix
Meson: Heterogeneous Workflows with Spark at Netflix
 
Mesos framework API v1
Mesos framework API v1Mesos framework API v1
Mesos framework API v1
 
DC/OS: The definitive platform for modern apps
DC/OS: The definitive platform for modern appsDC/OS: The definitive platform for modern apps
DC/OS: The definitive platform for modern apps
 
Deploying Docker Containers at Scale with Mesos and Marathon
Deploying Docker Containers at Scale with Mesos and MarathonDeploying Docker Containers at Scale with Mesos and Marathon
Deploying Docker Containers at Scale with Mesos and Marathon
 
Apache Kafka, HDFS, Accumulo and more on Mesos
Apache Kafka, HDFS, Accumulo and more on MesosApache Kafka, HDFS, Accumulo and more on Mesos
Apache Kafka, HDFS, Accumulo and more on Mesos
 
TDC2016POA | Trilha Infraestrutura - Apache Mesos & Marathon: gerenciando rem...
TDC2016POA | Trilha Infraestrutura - Apache Mesos & Marathon: gerenciando rem...TDC2016POA | Trilha Infraestrutura - Apache Mesos & Marathon: gerenciando rem...
TDC2016POA | Trilha Infraestrutura - Apache Mesos & Marathon: gerenciando rem...
 
Container Orchestration Wars (Micro Edition)
Container Orchestration Wars (Micro Edition)Container Orchestration Wars (Micro Edition)
Container Orchestration Wars (Micro Edition)
 
CI/CD with Docker, DC/OS, and Jenkins
CI/CD with Docker, DC/OS, and JenkinsCI/CD with Docker, DC/OS, and Jenkins
CI/CD with Docker, DC/OS, and Jenkins
 
Mesos introduction
Mesos introductionMesos introduction
Mesos introduction
 
Piloter un loadbalancer pour exposer les microservoces de mon cluster Mesos/M...
Piloter un loadbalancer pour exposer les microservoces de mon cluster Mesos/M...Piloter un loadbalancer pour exposer les microservoces de mon cluster Mesos/M...
Piloter un loadbalancer pour exposer les microservoces de mon cluster Mesos/M...
 
Container Orchestration Wars
Container Orchestration WarsContainer Orchestration Wars
Container Orchestration Wars
 
How to deploy Apache Spark 
to Mesos/DCOS
How to deploy Apache Spark 
to Mesos/DCOSHow to deploy Apache Spark 
to Mesos/DCOS
How to deploy Apache Spark 
to Mesos/DCOS
 
Understanding Kubernetes
Understanding KubernetesUnderstanding Kubernetes
Understanding Kubernetes
 
"On-premises" FaaS on Kubernetes
"On-premises" FaaS on Kubernetes"On-premises" FaaS on Kubernetes
"On-premises" FaaS on Kubernetes
 

Similar to Creating a Mesos python framework

RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Fullstack conf 2017 - Basic dev pipeline end-to-end
Fullstack conf 2017 - Basic dev pipeline end-to-endFullstack conf 2017 - Basic dev pipeline end-to-end
Fullstack conf 2017 - Basic dev pipeline end-to-endEzequiel Maraschio
 
Writing Redis in Python with asyncio
Writing Redis in Python with asyncioWriting Redis in Python with asyncio
Writing Redis in Python with asyncioJames Saryerwinnie
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...bobmcwhirter
 
mu.semte.ch - A journey from TenForce's perspective - SEMANTICS2016
mu.semte.ch - A journey from TenForce's perspective - SEMANTICS2016mu.semte.ch - A journey from TenForce's perspective - SEMANTICS2016
mu.semte.ch - A journey from TenForce's perspective - SEMANTICS2016Aad Versteden
 
Alex Casalboni - Configuration management and service discovery - Codemotion ...
Alex Casalboni - Configuration management and service discovery - Codemotion ...Alex Casalboni - Configuration management and service discovery - Codemotion ...
Alex Casalboni - Configuration management and service discovery - Codemotion ...Codemotion
 
Introduction to Apache Mesos
Introduction to Apache MesosIntroduction to Apache Mesos
Introduction to Apache MesosJoe Stein
 
DevOps Enabling Your Team
DevOps Enabling Your TeamDevOps Enabling Your Team
DevOps Enabling Your TeamGR8Conf
 
An intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECSAn intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECSYevgeniy Brikman
 
Aad Versteden | State-of-the-art web applications fuelled by Linked Data awar...
Aad Versteden | State-of-the-art web applications fuelled by Linked Data awar...Aad Versteden | State-of-the-art web applications fuelled by Linked Data awar...
Aad Versteden | State-of-the-art web applications fuelled by Linked Data awar...semanticsconference
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
maXbox Starter 42 Multiprocessing Programming
maXbox Starter 42 Multiprocessing Programming maXbox Starter 42 Multiprocessing Programming
maXbox Starter 42 Multiprocessing Programming Max Kleiner
 
SCons an Introduction
SCons an IntroductionSCons an Introduction
SCons an Introductionslantsixgames
 
MongoDB Days Silicon Valley: Introducing MongoDB 3.2
MongoDB Days Silicon Valley: Introducing MongoDB 3.2MongoDB Days Silicon Valley: Introducing MongoDB 3.2
MongoDB Days Silicon Valley: Introducing MongoDB 3.2MongoDB
 
node.js, javascript and the future
node.js, javascript and the futurenode.js, javascript and the future
node.js, javascript and the futureJeff Miccolis
 
Nsq & python worker
Nsq & python workerNsq & python worker
Nsq & python workerFelinx Lee
 

Similar to Creating a Mesos python framework (20)

RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Fullstack conf 2017 - Basic dev pipeline end-to-end
Fullstack conf 2017 - Basic dev pipeline end-to-endFullstack conf 2017 - Basic dev pipeline end-to-end
Fullstack conf 2017 - Basic dev pipeline end-to-end
 
Writing Redis in Python with asyncio
Writing Redis in Python with asyncioWriting Redis in Python with asyncio
Writing Redis in Python with asyncio
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Lec7
Lec7Lec7
Lec7
 
mu.semte.ch - A journey from TenForce's perspective - SEMANTICS2016
mu.semte.ch - A journey from TenForce's perspective - SEMANTICS2016mu.semte.ch - A journey from TenForce's perspective - SEMANTICS2016
mu.semte.ch - A journey from TenForce's perspective - SEMANTICS2016
 
Alex Casalboni - Configuration management and service discovery - Codemotion ...
Alex Casalboni - Configuration management and service discovery - Codemotion ...Alex Casalboni - Configuration management and service discovery - Codemotion ...
Alex Casalboni - Configuration management and service discovery - Codemotion ...
 
Introduction to Apache Mesos
Introduction to Apache MesosIntroduction to Apache Mesos
Introduction to Apache Mesos
 
DevOps Enabling Your Team
DevOps Enabling Your TeamDevOps Enabling Your Team
DevOps Enabling Your Team
 
An intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECSAn intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECS
 
Aad Versteden | State-of-the-art web applications fuelled by Linked Data awar...
Aad Versteden | State-of-the-art web applications fuelled by Linked Data awar...Aad Versteden | State-of-the-art web applications fuelled by Linked Data awar...
Aad Versteden | State-of-the-art web applications fuelled by Linked Data awar...
 
Streams
StreamsStreams
Streams
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
maXbox Starter 42 Multiprocessing Programming
maXbox Starter 42 Multiprocessing Programming maXbox Starter 42 Multiprocessing Programming
maXbox Starter 42 Multiprocessing Programming
 
SCons an Introduction
SCons an IntroductionSCons an Introduction
SCons an Introduction
 
MongoDB Days Silicon Valley: Introducing MongoDB 3.2
MongoDB Days Silicon Valley: Introducing MongoDB 3.2MongoDB Days Silicon Valley: Introducing MongoDB 3.2
MongoDB Days Silicon Valley: Introducing MongoDB 3.2
 
node.js, javascript and the future
node.js, javascript and the futurenode.js, javascript and the future
node.js, javascript and the future
 
Nsq & python worker
Nsq & python workerNsq & python worker
Nsq & python worker
 
Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
 

Recently uploaded

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 

Recently uploaded (20)

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 

Creating a Mesos python framework

  • 1. Mesos Python framework O. Sallou, DevExp 2016 CC-BY-SA 3.0
  • 2. Interacting with Mesos, 2 choices Python API: - not compatible with Python 3 - Easy to implement - Bindings over C API HTTP API: - HTTP calls with persistent connection and streaming - Recent - Language independent,
  • 3. Workflow Register => Listen for offer => accept/decline offer => listen for job status Messages use Protobuf [0], HTTP interface also supports JSON. See Mesos protobuf definition [1] to read or create messages. [0] https://developers.google.com/protocol-buffers/ [1] https://github.com/apache/mesos/blob/master/include/mesos/mesos.proto
  • 5. Register framework = mesos_pb2.FrameworkInfo() # mesos_pb2.XXX() read/use/write protobuf Mesos objects framework.user = "" # Have Mesos fill in the current user. framework.name = "Example Mesos framework" framework.failover_timeout = 3600 * 24*7 # 1 week # Optionally, restart from a previous run mesos_framework_id = mesos_pb2.FrameworkID() mesos_framework_id.value = XYZ framework.id.MergeFrom(mesos_framework_id) framework.principal = "godocker-mesos-framework" # We will create our scheduler class MesosScheduler in next slide mesosScheduler = MesosScheduler(1, executor) # Let’s declare a framework, with a scheduler to manage offers driver = mesos.native.MesosSchedulerDriver( mesosScheduler, framework, ‘zk://127.0.01:2881’) driver.start() executor = mesos_pb2.ExecutorInfo() executor.executor_id.value = "sample" executor.name = "Example executor"
  • 6. When scheduler ends... When scheduler stops, Mesos will kill any remaining tasks after “failover_timeout” value. One can set FrameworkID to restart framework and keep same context. Mesos will keep tasks, and send status messages to framework.
  • 7. Scheduler skeleton class MesosScheduler(mesos.interface.Scheduler): def registered(self, driver, frameworkId, masterInfo): logging.info("Registered with framework ID %s" % frameworkId.value) self.frameworkId = frameworkId.value def resourceOffers(self, driver, offers): ''' Receive offers, an offer defines a node with available resources (cpu, mem, etc.) ''' for offer in offers: logging.debug('Mesos:Offer:Decline) driver.declineOffer(offer.id) def statusUpdate(self, driver, update): ''' Receive status info from submitted tasks (switch to running, failure of node, etc.) ''' logging.debug("Task %s is in state %s" % (update.task_id.value, mesos_pb2.TaskState.Name (update.state))) def frameworkMessage(self, driver, executorId, slaveId, message): logging.debug("Received framework message") # usually, nothing to do here
  • 8. Messages are asynchronous Status updates and offers are asynchronous callbacks. Scheduler run in a separate thread. You’re never the initiator of the requests (except registration), but you will receive callback messages when something change on Mesos side (job switch to running, node failure, …)
  • 9. Submit a task for offer in offers: # Get available cpu and mem for this offer offerCpus = 0 offerMem = 0 for resource in offer.resources: if resource.name == "cpus": offerCpus += resource.scalar.value elif resource.name == "mem": offerMem += resource.scalar.value # We could chek for other resources here logging.debug("Mesos:Received offer %s with cpus: %s and mem: %s" % (offer.id.value, offerCpus, offerMem)) # We should check that offer has enough resources sample_task = create_a_sample_task(offer) array_of_task = [ sample_task ] driver.launchTasks(offer.id, array_of_task) Mesos support any custom resource definition on nodes (gpu, slots, disk, …), using scalar or range values When a task is launched, requested resources will be removed from available resources for the selected node. Next offers won’t propose thoses resources again until task is over (or killed).
  • 10. Define a task def create_a_sample_task(offer): task = mesos_pb2.TaskInfo() # The container part (native or docker) container = mesos_pb2.ContainerInfo() container.type = 1 # mesos_pb2.ContainerInfo.Type.DOCKER # Let’s add a volume volume = container.volumes.add() volume.container_path = “/tmp/test” volume.host_path = “/tmp/incontainer” volume.mode = 1 # mesos_pb2.Volume.Mode.RW # The command to execute, if not using entrypoint command = mesos_pb2.CommandInfo() command.value = “echo hello world” task.command.MergeFrom(command) # Unique identifier (or let mesos assign one) task.task_id.value = XYZ_UNIQUE_IDENTIFIER # the slave where task is executed task.slave_id.value = offer.slave_id.value task.name = “my_sample_task” # The resources/requirements # Resources have names, cpu, mem and ports are available # by default, one can define custom ones per slave node # and get them by their name here cpus = task.resources.add() cpus.name = "cpus" cpus.type = mesos_pb2.Value.SCALAR cpus.scalar.value = 2 mem = task.resources.add() mem.name = "mem" mem.type = mesos_pb2.Value.SCALAR mem.scalar.value = 3000 #3 Go
  • 11. Define a task (next) # Now the Docker part docker = mesos_pb2.ContainerInfo.DockerInfo() docker.image = “debian:latest” docker.network = 2 # mesos_pb2.ContainerInfo.DockerInfo.Network.BRIDGE docker.force_pull_image = True container.docker.MergeFrom(docker) # Let’s map some ports, ports are resources like cpu and mem # We will map container port 80 to an available host port # Let’s pick the first available port for this offer, for simplicity # we will skip here controls and suppose there is at least one port offer_port = None for resource in offer.resources: if resource.name == "ports": for mesos_range in resource.ranges.range: offer_port = mesos_range.begin break # We map port 80 to offer_port in container docker_port = docker.port_mappings.add() docker_port.host_port = 80 docker_port.container_port = offer_port # We tell mesos that we reserve this port # Mesos will remove it from next offers until task completion mesos_ports = task.resources.add() mesos_ports.name = "ports" mesos_ports.type = mesos_pb2.Value.RANGES port_range = mesos_ports.ranges.range.add() port_range.begin = offer_port port_range.end = offer_port task.container.MergeFrom(container) return task
  • 12. Task status def statusUpdate(self, driver, update): ''' Receive status info from submitted tasks (switch to running, failure of node, etc.) ''' logging.debug("Task %s is in state %s" % (update.task_id.value, mesos_pb2.TaskState.Name(update.state))) if int(update.state= == 1: #Switched to RUNNING container_info = json.loads(update.data) if int(update.state) in [2,3,4,5,7]: # Over or failure logging.error(“Task is over or failed”)
  • 13. Want to kill a task? def resourceOffers(self, driver, offers): …. task_id = mesos_pb2.TaskID() task_id.value = my_unique_task_id driver.killTask(task_id)
  • 14. A framework Quite easy to setup Many logs on Mesos side for debug Share the same resources with other frameworks Different executors (docker, native, …) In a few lines of code