<commit_before>package mesos

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"path"
	"strconv"
	"strings"
	"text/template"
	"time"

	"github.com/docker/docker/pkg/namesgenerator"
	"github.com/spf13/viper"

	"github.com/ovh/cds/engine/log"
	"github.com/ovh/cds/sdk"
	"github.com/ovh/cds/sdk/hatchery"
)

var hatcheryMesos *HatcheryMesos

type marathonPOSTAppParams struct {
	DockerImage    string
	APIEndpoint    string
	WorkerKey      string
	WorkerName     string
	WorkerModelID  int64
	HatcheryID     int64
	MarathonID     string
	MarathonVHOST  string
	MarathonLabels string
	Memory         int
	WorkerTTL      int
}

const marathonPOSTAppTemplate = `
{
    "container": {
        "docker": {
            "forcePullImage": false,
            "image": "{{.DockerImage}}",
            "network": "BRIDGE",
					  "portMapping": []
				},
        "type": "DOCKER"
    },
		"cmd": "rm -f worker && curl ${CDS_API}/download/worker/$(uname -m) -o worker &&  chmod +x worker && exec ./worker",
		"cpus": 0.5,
    "env": {
        "CDS_API": "{{.APIEndpoint}}",
        "CDS_KEY": "{{.WorkerKey}}",
        "CDS_NAME": "{{.WorkerName}}",
        "CDS_MODEL": "{{.WorkerModelID}}",
        "CDS_HATCHERY": "{{.HatcheryID}}",
        "CDS_SINGLE_USE": "1",
		"CDS_TTL" : "{{.WorkerTTL}}"
    },
    "id": "{{.MarathonID}}/{{.WorkerName}}",
    "instances": 1,
	"ports": [],
	"mem": {{.Memory}},
	"labels": {{.MarathonLabels}}
}
`

// HatcheryMesos implements HatcheryMode interface for mesos mode
type HatcheryMesos struct {
	hatch *sdk.Hatchery

	token string

	marathonHost         string
	marathonID           string
	marathonVHOST        string
	marathonUser         string
	marathonPassword     string
	marathonLabelsString string
	marathonLabels       map[string]string

	defaultMemory int
	workerTTL     int
}

// ID must returns hatchery id
func (m *HatcheryMesos) ID() int64 {
	if m.hatch == nil {
		return 0
	}
	return m.hatch.ID
}

//Hatchery returns hatchery instance
func (m *HatcheryMesos) Hatchery() *sdk.Hatchery {
	return m.hatch
}

// KillWorker deletes an application on mesos via marathon
func (m *HatcheryMesos) KillWorker(worker sdk.Worker) error {
	appID := path.Join(hatcheryMesos.marathonID, worker.Name)
	log.Notice("KillWorker> Killing %s\n", appID)
	return deleteApp(hatcheryMesos.marathonHost, hatcheryMesos.marathonUser, hatcheryMesos.marathonPassword, appID)
}

// CanSpawn return wether or not hatchery can spawn model
// requirements are not supported
func (m *HatcheryMesos) CanSpawn(model *sdk.Model, req []sdk.Requirement) bool {
	if model.Type != sdk.Docker {
		return false
	}
	if len(req) > 0 {
		return false
	}
	return true
}

// SpawnWorker creates an application on mesos via marathon
// requirements are not supported
func (m *HatcheryMesos) SpawnWorker(model *sdk.Model, req []sdk.Requirement) error {
	if model.Type != sdk.Docker {
		return fmt.Errorf("Model not handled")
	}

	log.Notice("Spawning worker %s (%s)\n", model.Name, model.Image)

	// Do not DOS marathon, if deployment queue is longer than 10, wait
	deployments, err := getDeployments(hatcheryMesos.marathonHost, hatcheryMesos.marathonUser, hatcheryMesos.marathonPassword)
	if err != nil {<commit_msg>fix (hatchery): mesos support memory requirement (#128)<commit_after>package mesos

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"path"
	"strconv"
	"strings"
	"text/template"
	"time"

	"github.com/docker/docker/pkg/namesgenerator"
	"github.com/spf13/viper"

	"github.com/ovh/cds/engine/log"
	"github.com/ovh/cds/sdk"
	"github.com/ovh/cds/sdk/hatchery"
)

var hatcheryMesos *HatcheryMesos

type marathonPOSTAppParams struct {
	DockerImage    string
	APIEndpoint    string
	WorkerKey      string
	WorkerName     string
	WorkerModelID  int64
	HatcheryID     int64
	MarathonID     string
	MarathonVHOST  string
	MarathonLabels string
	Memory         int
	WorkerTTL      int
}

const marathonPOSTAppTemplate = `
{
    "container": {
        "docker": {
            "forcePullImage": false,
            "image": "{{.DockerImage}}",
            "network": "BRIDGE",
					  "portMapping": []
				},
        "type": "DOCKER"
    },
		"cmd": "rm -f worker && curl ${CDS_API}/download/worker/$(uname -m) -o worker &&  chmod +x worker && exec ./worker",
		"cpus": 0.5,
    "env": {
        "CDS_API": "{{.APIEndpoint}}",
        "CDS_KEY": "{{.WorkerKey}}",
        "CDS_NAME": "{{.WorkerName}}",
        "CDS_MODEL": "{{.WorkerModelID}}",
        "CDS_HATCHERY": "{{.HatcheryID}}",
        "CDS_SINGLE_USE": "1",
		"CDS_TTL" : "{{.WorkerTTL}}"
    },
    "id": "{{.MarathonID}}/{{.WorkerName}}",
    "instances": 1,
	"ports": [],
	"mem": {{.Memory}},
	"labels": {{.MarathonLabels}}
}
`

// HatcheryMesos implements HatcheryMode interface for mesos mode
type HatcheryMesos struct {
	hatch *sdk.Hatchery

	token string

	marathonHost         string
	marathonID           string
	marathonVHOST        string
	marathonUser         string
	marathonPassword     string
	marathonLabelsString string
	marathonLabels       map[string]string

	defaultMemory int
	workerTTL     int
}

// ID must returns hatchery id
func (m *HatcheryMesos) ID() int64 {
	if m.hatch == nil {
		return 0
	}
	return m.hatch.ID
}

//Hatchery returns hatchery instance
func (m *HatcheryMesos) Hatchery() *sdk.Hatchery {
	return m.hatch
}

// KillWorker deletes an application on mesos via marathon
func (m *HatcheryMesos) KillWorker(worker sdk.Worker) error {
	appID := path.Join(hatcheryMesos.marathonID, worker.Name)
	log.Notice("KillWorker> Killing %s\n", appID)
	return deleteApp(hatcheryMesos.marathonHost, hatcheryMesos.marathonUser, hatcheryMesos.marathonPassword, appID)
}

// CanSpawn return wether or not hatchery can spawn model
// requirements services are not supported
func (m *HatcheryMesos) CanSpawn(model *sdk.Model, req []sdk.Requirement) bool {
	if model.Type != sdk.Docker {
		return false
	}
	//Service requirement are not supported
	for _, r := range req {
		if r.Type == sdk.ServiceRequirement {
			return false
		}
	}

	return true
}

// SpawnWorker creates an application on mesos via marathon
// requirements services are not supported
func (m *HatcheryMesos) SpawnWorker(model *sdk.Model, req []sdk.Requirement) error {
	if model.Type != sdk.Docker {
		return fmt.Errorf("Model not handled")
	}

	log.Notice("Spawning worker %s (%s)\n", model.Name, model.Image)

	// Do not DOS marathon, if deployment queue is longer than 10, wait
	deployments, err := getDeployments(hatcheryMesos.marathonHost, hatcheryMesos.marathonUser, hatcheryMesos.marathonPassword)
	if err != nil {
{'fraction_non_alphanumeric': 0.13028329041054384, 'fraction_numerical': 0.005150734737161036, 'mean_word_length': 3.4042695130086726, 'pattern_counts': {'":': 42, '<': 3, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '337384', 'n_tokens_mistral': 2484, 'n_tokens_neox': 2406, 'n_words': 561}