diff --git a/package.json b/package.json index 5d07fa5..cbf7694 100644 --- a/package.json +++ b/package.json @@ -4,26 +4,21 @@ "description": "Node.js sample app for OpenShift 3", "main": "server.js", "dependencies": { - "express": "*" - }, - "devDependencies": { - "nodemon": "*" + "express": "*", + "mongodb": "*", + "ejs": "*" }, "engine": { "node": "*", "npm": "*" }, "scripts": { - "dev": "nodemon --ignore node_modules/ server.js", "start": "node server.js" }, "repository": { "type": "git", "url": "http://github.com/openshift/nodejs-ex.git" }, - "keywords": [ - "Echo" - ], "author": "Steve Speicher ", "license": "", "bugs": { diff --git a/server.js b/server.js index 828fefc..49f989d 100644 --- a/server.js +++ b/server.js @@ -1,53 +1,86 @@ -var util = require('util'); -var url = require('url'); -var qs = require('querystring'); -var os = require('os') -var port = process.env.PORT || process.env.port || process.env.OPENSHIFT_NODEJS_PORT || 8080; -var ip = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0'; -var nodeEnv = process.env.NODE_ENV || 'unknown'; - +// OpenShift sample Node application var express = require('express'); -var app = express(); +var fs = require('fs'); +var app = express(); +var eps = require('ejs'); -app.use(function(req, res, next) { - var url_parts = url.parse(req.url, true); +app.engine('html', require('ejs').renderFile); - var body = ''; - req.on('data', function (data) { - body += data; - }); - req.on('end', function () { - var formattedBody = qs.parse(body); +var port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080; +var ip = process.env.IP || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0'; +var mongoURL = process.env.OPENSHIFT_MONGODB_DB_URL || process.env.MONGO_URL; +var mongoURLLabel = ""; +if (mongoURL == null && process.env.DATABASE_SERVICE_NAME) { + var mongoServiceName = process.env.DATABASE_SERVICE_NAME.toUpperCase(); + var mongoHost = process.env[mongoServiceName + "_SERVICE_HOST"]; + var mongoPort = process.env[mongoServiceName + "_SERVICE_PORT"]; + var mongoUser = process.env.MONGODB_USER + if (mongoHost && mongoPort && process.env.MONGODB_DATABASE) { + mongoURLLabel = mongoURL = 'mongodb://'; + if (process.env.MONGODB_USER && process.env.MONGODB_PASSWORD) { + mongoURL += process.env.MONGODB_USER + ':' + process.env.MONGODB_PASSWORD + '@'; + } + // Provide UI label that excludes user id and pw - res.writeHead(200, {'Content-Type': 'text/plain'}); + mongoURLLabel += mongoHost + ':' + mongoPort + '/' + process.env.MONGODB_DATABASE; + mongoURL += mongoHost + ':' + mongoPort + '/' + process.env.MONGODB_DATABASE; + } +} +var db = null; +var dbDetails = new Object(); - res.write('Hello OpenShift World! This is a Node.js-based sample application.\n'); - res.write('Host: ' + req.headers.host + '\n'); - res.write('\n'); - res.write('node.js Production Mode: ' + (nodeEnv == 'production' ? 'yes' : 'no') + '\n'); - res.write('\n'); - res.write('HTTP/' + req.httpVersion +'\n'); - res.write('Request headers:\n'); - res.write(util.inspect(req.headers, null) + '\n'); - res.write('Request query:\n'); - res.write(util.inspect(url_parts.query, null) + '\n'); - res.write('Request body:\n'); - res.write(util.inspect(formattedBody, null) + '\n'); - res.write('\n'); - res.write('Host: ' + os.hostname() + '\n'); - res.write('OS Type: ' + os.type() + '\n'); - res.write('OS Platform: ' + os.platform() + '\n'); - res.write('OS Arch: ' + os.arch() + '\n'); - res.write('OS Release: ' + os.release() + '\n'); - res.write('OS Uptime: ' + os.uptime() + '\n'); - res.write('OS Free memory: ' + os.freemem() / 1024 / 1024 + 'mb\n'); - res.write('OS Total memory: ' + os.totalmem() / 1024 / 1024 + 'mb\n'); - res.write('OS CPU count: ' + os.cpus().length + '\n'); - res.write('OS CPU model: ' + os.cpus()[0].model + '\n'); - res.write('OS CPU speed: ' + os.cpus()[0].speed + 'mhz\n'); - res.end('\n'); - }); - next(); +var initDb = function(callback) { + if (mongoURL == null) return; + + var mongodb = require('mongodb'); + if (mongodb == null) return; + + mongodb.connect(mongoURL, function(err, conn) { + if (err) { + callback(err); + return; + } + + db = conn; + dbDetails.databaseName = db.databaseName; + dbDetails.url = mongoURLLabel; + dbDetails.type = 'MongoDB'; + + console.log("Connected to MongoDB at: " + mongoURL); + }); +}; + +app.get('/', function (req, res) { + if (db) { + var col = db.collection('counts'); + // Create a document with request IP and current time of request + col.insert({ip: req.ip, date: Date.now()}); + col.count(function(err, count){ + res.render('index.html', { pageCountMessage : count, dbInfo: dbDetails }); + }); + } else { + res.render('index.html', { pageCountMessage : null}); + } +}); + +app.get('/pagecount', function (req, res) { + if (db) { + db.collection('counts').count(function(err, count ){ + res.send('{ pageCount: ' + count +'}'); + }); + } else { + res.send('{ pageCount: -1 }'); + } +}); + +// error handling +app.use(function(err, req, res, next){ + console.error(err.stack); + res.status(500).send('Something bad happened!'); +}); + +initDb(function(err){ + console.log('Error connecting to Mongo. Message:\n'+err); }); app.listen(port, ip); diff --git a/views/index.html b/views/index.html new file mode 100644 index 0000000..3c1cadc --- /dev/null +++ b/views/index.html @@ -0,0 +1,306 @@ + + + + + + Welcome to OpenShift + + + + + + + +
+
+

Welcome to your Node.js application on OpenShift

+
+ + +
+
+
+

How to use this example application

+

For instrutions on how to use this application with OpenShift, start with reading the Developer Guide.

+ +

Deploying code changes

+

+ The source code for this application is available to be forked from the OpenShift GitHub repository. + You can configure a webhook in your repository to make OpenShift automatically start a build whenever you push your code: +

+ +
    +
  1. From the Web Console homepage, navigate to your project
  2. +
  3. Click on Browse > Builds
  4. +
  5. From the view for your Build click on the button to copy your GitHub webhook
  6. +
  7. Navigate to your repository on GitHub and click on repository settings > webhooks
  8. +
  9. Paste your webhook URL provided by OpenShift — that's it!
  10. +
+

After you save your webhook, if you refresh your settings page you can see the status of the ping that Github sent to OpenShift to verify it can reach the server.

+

Note: adding a webhook requires your OpenShift server to be reachable from GitHub.

+ +

Working in your local Git repository

+

If you forked the application from the OpenShift GitHub example, you'll need to manually clone the repository to your local system. Copy the application's source code Git URL and then run:

+ +
$ git clone <git_url> <directory_to_create>
+
+# Within your project directory
+# Commit your changes and push to OpenShift
+
+$ git commit -a -m 'Some commit message'
+$ git push
+ +

After pushing changes, you'll need to manually trigger a build if you did not setup a webhook as described above.

+ +
+ +
+
+ +

Managing your application

+ +

Documentation on how to manage your application from the Web Console or Command Line is available at the Developer Guide.

+ +

Web Console

+

You can use the Web Console to view the state of your application components and launch new builds.

+ +

Command Line

+

With the OpenShift command line interface (CLI), you can create applications and manage projects from a terminal.

+ +

Development Resources

+ + +

Request information

+

Page view count: + <% if (pageCountMessage) { %> + <%=pageCountMessage%> +

+

DB Connection Info:

+ + + +
Type:<%= dbInfo.type %>
URL:<%= dbInfo.url %>
+
+ <% } else { %> + No database configured +

+ <%} %> +
+
+ + +
+ +