Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions pkg/template/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Package template transforms project templates into api objects recognized
// by Kubernetes. It generates parameter values based on their input
// expressions and substitutes parameters found in the container env vars
// with their corresponding values.
package template
184 changes: 184 additions & 0 deletions pkg/template/example/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
{
"id": "example1",
"name": "my-awesome-php-app",
"description": "Example PHP application with PostgreSQL database",
"buildConfigs": [
{
"name": "mfojtik/nginx-php-app",
"type": "docker",
"sourceUri": "https://raw.githubusercontent.com/mfojtik/phpapp/master/Dockerfile",
"imageRepository": "mfojtik/nginx-php-app"
},
{
"name": "postgres",
"type": "docker",
"sourceUri": "https://raw.githubusercontent.com/docker-library/postgres/docker/9.2/Dockerfile",
"imageRepository": "postgres"
}
],
"imageRepositories": [
{
"name": "mfojtik/nginx-php-app",
"url": "internal.registry.com:5000/mfojtik/phpapp"
},
{
"name": "postgres",
"url": "registry.hub.docker.com/postgres"
}
],
"parameters": [
{
"name": "DB_PASSWORD",
"description": "PostgreSQL admin user password",
"type": "string",
"generate": "[a-zA-Z0-9]{8}"
},
{
"name": "DB_USER",
"description": "PostgreSQL username",
"type": "string",
"generate": "admin[a-zA-Z0-9]{4}"
},
{
"name": "DB_NAME",
"description": "PostgreSQL database name",
"type": "string",
"value": "mydb"
},
{
"name": "REMOTE_KEY",
"description": "Example of remote key",
"type": "string",
"value": "[GET:http://custom.url.int]"
}
],
"services": [
{
"id": "database",
"kind": "Service",
"apiVersion": "v1beta1",
"port": 5432,
"selector": {
"name": "database"
}
},
{
"id": "frontend",
"kind": "Service",
"apiVersion": "v1beta1",
"port": 8080,
"selector": {
"name": "frontend"
}
}
],
"deploymentConfigs": [
{
"kind": "DeploymentConfig",
"apiVersion": "v1beta1",
"labels": {
"name": "database"
},
"desiredState": {
"replicas": 2,
"replicaSelector": {
"name": "database"
},
"podTemplate": {
"kind": "Pod",
"apiVersion": "v1beta1",
"id": "database",
"desiredState": {
"manifest": {
"version": "v1beta1",
"id": "database",
"containers": [{
"name": "postgresql",
"image": "postgres",
"env": [
{
"name": "PGPASSWORD",
"value": "${DB_PASSWORD}"
},
{
"name": "PGUSER",
"value": "${DB_USER}"
},
{
"name": "PGDATABASE",
"value": "${DB_NAME}"
},
{
"name": "FOO",
"value": "${BAR}"
}
],
"ports": [
{
"containerPort": 5432
}
]
}
]
}
},
"labels": {
"name": "database"
}
}
}
},
{
"kind": "DeploymentConfig",
"apiVersion": "v1beta1",
"labels": {
"name": "frontend"
},
"desiredState": {
"replicas": 2,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this will be turned into a replicationcontroller definition as part of the processing into a config file?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The deployment config controller does that post creation - dconfigs indicate a desire for the described resources to exist but it's their responsibility to create those resources.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, what/where is the deployment config controller?

my current mental model is:
project.json -> env variable generator -> project.json(variables resolved) -> k8s config generator -> config.json(consisting of k8s api objects, basically looks like @mfojtik 's "stapled together objects" config.json) -> calls to k8s apiserver

Where does the deployment config controller fit into that?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, talked to clayton and he got me straightened out: deployment config will be a k8s api object.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bparees @smarterclayton so just to clarify, the workflow @bparees proposed above is correct?

I mean, the steps are:

"replicaSelector": {
"name": "frontend"
},
"podTemplate": {
"kind": "Pod",
"apiVersion": "v1beta1",
"id": "frontend",
"desiredState": {
"manifest": {
"version": "v1beta1",
"id": "frontend",
"containers": [{
"name": "frontend",
"image": "mfojtik/nginx-php-app",
"env": [
{
"name": "PGPASSWORD",
"value": "${DB_PASSWORD}"
},
{
"name": "PGUSER",
"value": "${DB_USER}"
},
{
"name": "PGDATABASE",
"value": "${DB_NAME}"
}
],
"ports": [
{
"containerPort": 9292,
"hostPort": 8080
}
]
}
]
}
},
"labels": {
"name": "frontend"
}
}
}
}
]
}
3 changes: 3 additions & 0 deletions pkg/template/generator/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Package generator defines GeneratorInterface interface
// and implements several random value generators
package generator
124 changes: 124 additions & 0 deletions pkg/template/generator/expression_value.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package generator

import (
"fmt"
"math/rand"
"regexp"
"strconv"
"strings"
)

// ExpressionValueGenerator generates random string based on the input
// expression. The input expression is a string, which may contain
// generator constructs matching "[a-zA-Z0-9]{length}" expression.
//
// Examples:
// - "test[0-9]{1}x" => "test7x"
// - "[0-1]{8}" => "01001100"
// - "0x[A-F0-9]{4}" => "0xB3AF"
// - "[a-zA-Z0-9]{8}" => "hW4yQU5i"
type ExpressionValueGenerator struct {
seed *rand.Rand
}

const (
Alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Numerals = "0123456789"
Ascii = Alphabet + Numerals + "~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:`"
)

var (
rangeExp = regexp.MustCompile(`([\\]?[a-zA-Z0-9]\-?[a-zA-Z0-9]?)`)
generatorsExp = regexp.MustCompile(`\[([a-zA-Z0-9\-\\]+)\](\{([0-9]+)\})`)
)

func init() {
RegisterGenerator(generatorsExp, func(seed *rand.Rand) (GeneratorInterface, error) { return newExpressionValueGenerator(seed) })
}

func newExpressionValueGenerator(seed *rand.Rand) (ExpressionValueGenerator, error) {
return ExpressionValueGenerator{seed: seed}, nil
}

func (g ExpressionValueGenerator) GenerateValue(expression string) (interface{}, error) {
genMatches := generatorsExp.FindAllStringIndex(expression, -1)
for _, r := range genMatches {
ranges, length, err := rangesAndLength(expression[r[0]:r[1]])
if err != nil {
return "", err
}
positions := findExpressionPos(ranges)
err = replaceWithGenerated(&expression, expression[r[0]:r[1]], positions, length, g.seed)
if err != nil {
return "", err
}
}
return expression, nil
}

func alphabetSlice(from, to byte) (string, error) {
leftPos := strings.Index(Ascii, string(from))
rightPos := strings.LastIndex(Ascii, string(to))
if leftPos > rightPos {
return "", fmt.Errorf("Invalid range specified: %s-%s", string(from), string(to))
}
return Ascii[leftPos:rightPos], nil
}

func replaceWithGenerated(s *string, expression string, ranges [][]byte, length int, seed *rand.Rand) error {
var alphabet string
for _, r := range ranges {
switch string(r[0]) + string(r[1]) {
case `\w`:
alphabet += Ascii
case `\d`:
alphabet += Numerals
case `\a`:
alphabet += Alphabet + Numerals
default:
if slice, err := alphabetSlice(r[0], r[1]); err != nil {
return err
} else {
alphabet += slice
}
}
}
if len(alphabet) == 0 {
return fmt.Errorf("Empty range in expression: %s", expression)
}
result := make([]byte, length)
for i := 0; i < length; i++ {
result[i] = alphabet[seed.Intn(len(alphabet))]
}
*s = strings.Replace(*s, expression, string(result), 1)
return nil
}

func findExpressionPos(s string) [][]byte {
matches := rangeExp.FindAllStringIndex(s, -1)
result := make([][]byte, len(matches))
for i, r := range matches {
result[i] = []byte{s[r[0]], s[r[1]-1]}
}
return result
}

func parseLength(s string) (int, error) {
lengthStr := string(s[strings.LastIndex(s, "{")+1 : len(s)-1])
if l, err := strconv.Atoi(lengthStr); err != nil {
return 0, fmt.Errorf("Unable to parse length from %v", s)
} else {
return l, nil
}
}

func rangesAndLength(s string) (string, int, error) {
l := strings.LastIndex(s, "{")
if l > 0 {
expr := s[0:strings.LastIndex(s, "{")]
length, err := parseLength(s)
return expr, length, err
} else {
return "", 0, fmt.Errorf("Unable to parse length from %v", s)
}
}
59 changes: 59 additions & 0 deletions pkg/template/generator/generator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package generator
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of these packages need a properly formatted doc.go file with a package comment.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resolved


import (
"fmt"
"math/rand"
"regexp"
"sync"
)

// GeneratorInterface is an abstract interface for generating
// random values from an input expression
type GeneratorInterface interface {
GenerateValue(expression string) (interface{}, error)
}

// Generator implements GeneratorInterface
type Generator struct {
seed *rand.Rand
}

func New(seed *rand.Rand) (Generator, error) {
return Generator{seed: seed}, nil
}

// GenerateValue loops over registered generators and tries to find the
// one matching the input expression. If match is found, it then generates
// value using that matching generator
func (g *Generator) GenerateValue(expression string) (interface{}, error) {
if len(generators) <= 0 {
return expression, fmt.Errorf("No registered generators.")
}

for regexp, generatorFactory := range generators {
if regexp.FindStringIndex(expression) != nil {
generator, err := generatorFactory(g.seed)
if err != nil {
return expression, err
}
return generator.GenerateValue(expression)
}
}

return expression, fmt.Errorf("No matching generators found.")
}

// GeneratorFactory is an abstract factory for creating generators
// (objects that implement GeneratorInterface interface)
type GeneratorFactory func(*rand.Rand) (GeneratorInterface, error)

// generators stores registered generators
var generators = make(map[*regexp.Regexp]GeneratorFactory)
var generatorsMutex sync.Mutex

// RegisterGenerator registers new generator for a certain input expression
func RegisterGenerator(r *regexp.Regexp, f GeneratorFactory) {
generatorsMutex.Lock()
defer generatorsMutex.Unlock()
generators[r] = f
}
Loading