Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
rrequero committed Nov 16, 2017
0 parents commit 5d38c3a
Show file tree
Hide file tree
Showing 34 changed files with 745 additions and 0 deletions.
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
23 changes: 23 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# EditorConfig is awesome: http://EditorConfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

# Matches multiple files with brace expansion notation
# Set default charset
[*.js]
charset = utf-8

# 2 space indentation
[**/*.js]
indent_style = space
indent_size = 2

[*.yml]
indent_style = space
indent_size = 2
48 changes: 48 additions & 0 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
extends: airbnb
env:
node: true
es6: true
parser: babel-eslint
parserOptions:
sourceType: module
ecmaVersion: 6
globals:
describe: true
it: true
before: true
after: true
rules:
max-len: [1, 200, 2, {"ignoreUrls":true}]
curly: [2, "multi-line"]
comma-dangle: [0, always-multiline]
no-underscore-dangle: 0
eqeqeq: [2, "allow-null"]
global-require: 0
no-shadow: 1
no-param-reassign: [2, { "props": false }]
indent: [2, 4]
padded-blocks: [2, { "switches": "always", "classes": "always" }]
quotes:
- 2
- single
- allowTemplateLiterals: true
settings:
import/resolver:
node:
extensions:
# if unset, default is just '.js', but it must be re-added explicitly if set
- .js
- .jsx
- .es6
- .coffee

paths:
# an array of absolute paths which will also be searched
# think NODE_PATH
- /usr/local/share/global_modules

# this is technically for identifying `node_modules` alternate names
moduleDirectory:
- node_modules # defaults to 'node_modules', but...
- app/src
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/
.env
/.vscode
npm-debug.log

28 changes: 28 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
FROM node:9.1-alpine
MAINTAINER [email protected]

ENV NAME doc-writter
ENV USER doc-writter

RUN apk update && apk upgrade && \
apk add --no-cache --update bash git openssh python alpine-sdk

RUN addgroup $USER && adduser -s /bin/bash -D -G $USER $USER

RUN npm install -g grunt-cli bunyan

RUN mkdir -p /opt/$NAME
COPY package.json /opt/$NAME/package.json
RUN cd /opt/$NAME && npm install

COPY entrypoint.sh /opt/$NAME/entrypoint.sh
COPY config /opt/$NAME/config

WORKDIR /opt/$NAME

COPY ./app /opt/$NAME/app
RUN chown $USER:$USER /opt/$NAME

USER $USER

ENTRYPOINT ["./entrypoint.sh"]
137 changes: 137 additions & 0 deletions Jenkinsfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
#!groovy

node {

// Actions
def forceCompleteDeploy = false
try {
timeout(time: 15, unit: 'SECONDS') {
forceCompleteDeploy = input(
id: 'Proceed0', message: 'Force COMPLETE Deployment', parameters: [
[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you want to recreate services and deployments']
])
}
}
catch(err) { // timeout reached or input false
// nothing
}

// Variables
def tokens = "${env.JOB_NAME}".tokenize('/')
def appName = tokens[0]
def dockerUsername = "${DOCKER_USERNAME}"
def imageTag = "${dockerUsername}/${appName}:${env.BRANCH_NAME}.${env.BUILD_NUMBER}"

currentBuild.result = "SUCCESS"

checkout scm
properties([pipelineTriggers([[$class: 'GitHubPushTrigger']])])

try {

stage ('Build docker') {
sh("docker -H :2375 build -t ${imageTag} .")
sh("docker -H :2375 build -t ${dockerUsername}/${appName}:latest .")
}

stage ('Run Tests') {
sh('docker-compose -H :2375 -f docker-compose-test.yml build')
sh('docker-compose -H :2375 -f docker-compose-test.yml run --rm test')
sh('docker-compose -H :2375 -f docker-compose-test.yml stop')
}

stage('Push Docker') {
withCredentials([usernamePassword(credentialsId: 'Vizzuality Docker Hub', usernameVariable: 'DOCKER_HUB_USERNAME', passwordVariable: 'DOCKER_HUB_PASSWORD')]) {
sh("docker -H :2375 login -u ${DOCKER_HUB_USERNAME} -p ${DOCKER_HUB_PASSWORD}")
sh("docker -H :2375 push ${imageTag}")
sh("docker -H :2375 push ${dockerUsername}/${appName}:latest")
sh("docker -H :2375 rmi ${imageTag}")
}
}

stage ("Deploy Application") {
switch ("${env.BRANCH_NAME}") {

// Roll out to staging
case "develop":
sh("echo Deploying to STAGING cluster")
sh("kubectl config use-context gke_${GCLOUD_PROJECT}_${GCLOUD_GCE_ZONE}_${KUBE_STAGING_CLUSTER}")
def service = sh([returnStdout: true, script: "kubectl get deploy ${appName} || echo NotFound"]).trim()
if ((service && service.indexOf("NotFound") > -1) || (forceCompleteDeploy)){
sh("sed -i -e 's/{name}/${appName}/g' k8s/services/*.yaml")
sh("sed -i -e 's/{name}/${appName}/g' k8s/staging/*.yaml")
sh("kubectl apply -f k8s/services/")
sh("kubectl apply -f k8s/staging/")
}
sh("kubectl set image deployment ${appName} ${appName}=${imageTag} --record")
break

// Roll out to production
case "master":
def userInput = true
def didTimeout = false
try {
timeout(time: 60, unit: 'SECONDS') {
userInput = input(
id: 'Proceed1', message: 'Confirm deployment', parameters: [
[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this deployment']
])
}
}
catch(err) { // timeout reached or input false
sh("echo Aborted by user or timeout")
if('SYSTEM' == user.toString()) { // SYSTEM means timeout.
didTimeout = true
} else {
userInput = false
}
}
if (userInput == true && !didTimeout){
sh("echo Deploying to PROD cluster")
sh("kubectl config use-context gke_${GCLOUD_PROJECT}_${GCLOUD_GCE_ZONE}_${KUBE_PROD_CLUSTER}")
def service = sh([returnStdout: true, script: "kubectl get deploy ${appName} || echo NotFound"]).trim()
if ((service && service.indexOf("NotFound") > -1) || (forceCompleteDeploy)){
sh("sed -i -e 's/{name}/${appName}/g' k8s/services/*.yaml")
sh("sed -i -e 's/{name}/${appName}/g' k8s/production/*.yaml")
sh("kubectl apply -f k8s/services/")
sh("kubectl apply -f k8s/production/")
}
sh("kubectl set image deployment ${appName} ${appName}=${imageTag} --record")
} else {
sh("echo NOT DEPLOYED")
currentBuild.result = 'SUCCESS'
}
break

// Default behavior?
default:
echo "Default -> do nothing"
currentBuild.result = "SUCCESS"
}
}

// Notify Success
slackSend (color: '#00FF00', channel: '#the-new-api', message: "SUCCESSFUL: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")
emailext (
subject: "SUCCESSFUL: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: """<p>SUCCESSFUL: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
<p>Check console output at "<a href="${env.BUILD_URL}">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>"</p>""",
recipientProviders: [[$class: 'DevelopersRecipientProvider']]
)


} catch (err) {

currentBuild.result = "FAILURE"
// Notify Error
slackSend (color: '#FF0000', channel: '#the-new-api', message: "FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")
emailext (
subject: "FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: """<p>FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
<p>Check console output at "<a href="${env.BUILD_URL}">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>"</p>""",
recipientProviders: [[$class: 'DevelopersRecipientProvider']]
)
throw err
}

}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 control-tower

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Node Skeleton Microservice


This repository is the node skeleton microservice to create node microservice for WRI API

1. [Getting Started](#getting-started)

## Getting Started

### OS X

**First, make sure that you have the [API gateway running
locally](https://github.com/control-tower/control-tower).**

We're using Docker which, luckily for you, means that getting the
application running locally should be fairly painless. First, make sure
that you have [Docker Compose](https://docs.docker.com/compose/install/)
installed on your machine.

```
git clone https://github.com/Vizzuality/node-skeleton
cd node-skeleton
./service.sh develop
./service.sh test
```text
You can now access the microservice through the CT gateway.
```

### Configuration

It is necessary to define these environment variables:

* CT_URL => Control Tower URL
* NODE_ENV => Environment (prod, staging, dev)
72 changes: 72 additions & 0 deletions app/Gruntfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@

module.exports = (grunt) => {

grunt.file.setBase('..');
require('load-grunt-tasks')(grunt);

grunt.initConfig({

express: {
dev: {
options: {
script: 'app/index.js',
node_env: 'dev',
output: 'started'
}
},
test: {
options: {
script: 'app/index.js',
node_env: 'test',
port: 5000,
output: 'started'
}
}
},

mochaTest: {
e2e: {
options: {
reporter: 'spec',
quiet: false,
clearRequireCache: true,
},
src: ['app/test/e2e/**/*.spec.js']
}
},

watch: {
options: {
livereload: 35730
},
jssrc: {
files: [
'app/src/**/*.js',
],
tasks: ['express:dev'],
options: {
spawn: false
}
},
e2eTest: {
files: [
'app/test/e2e/**/*.spec.js',
],
tasks: ['express:test', 'mochaTest:e2e'],
options: {
spawn: true
}
},

}
});

grunt.registerTask('e2eTest', ['express:test', 'mochaTest:e2e']);

grunt.registerTask('e2eTest-watch', ['watch:e2eTest']);

grunt.registerTask('serve', ['express:dev', 'watch']);

grunt.registerTask('default', 'serve');

};
1 change: 1 addition & 0 deletions app/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
require('app');
1 change: 1 addition & 0 deletions app/microservice/public-swagger.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
11 changes: 11 additions & 0 deletions app/microservice/register.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "node-skeleton",
"endpoints": [{
"path": "/v1/service/hi",
"method": "GET",
"redirect": {
"method": "GET",
"path": "/api/v1/service/hi"
}
}]
}
1 change: 1 addition & 0 deletions app/microservice/swagger.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
Loading

0 comments on commit 5d38c3a

Please sign in to comment.