Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
vithalreddy committed Aug 30, 2019
0 parents commit 74d90f9
Show file tree
Hide file tree
Showing 23 changed files with 627 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .editorconfig
@@ -0,0 +1,15 @@
# http://editorconfig.org
root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
max_line_length = 80
trim_trailing_whitespace = true

[*.md]
max_line_length = 0
trim_trailing_whitespace = false
3 changes: 3 additions & 0 deletions .github/CONTRIBUTING.md
@@ -0,0 +1,3 @@
# Example Contributing Guidelines

This is an example of GitHub's contributing guidelines file. Check out GitHub's [CONTRIBUTING.md help center article](https://help.github.com/articles/setting-guidelines-for-repository-contributors/) for more information.
11 changes: 11 additions & 0 deletions .github/ISSUE_TEMPLATE.md
@@ -0,0 +1,11 @@
* **I'm submitting a ...**
[ ] bug report
[ ] feature request
[ ] question about the decisions made in the repository
[ ] question about how to use this project

* **Summary**



* **Other information** (e.g. detailed explanation, stacktraces, related issues, suggestions how to fix, links for us to have context, eg. StackOverflow, personal fork, etc.)
13 changes: 13 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,13 @@
* **What kind of change does this PR introduce?** (Bug fix, feature, docs update, ...)



* **What is the current behavior?** (You can also link to an open issue here)



* **What is the new behavior (if this is a feature change)?**



* **Other information**:
12 changes: 12 additions & 0 deletions .gitignore
@@ -0,0 +1,12 @@
node_modules
build
test
src/**.js
.idea/*

coverage
.nyc_output
*.log

yarn.lock
package-lock.json
14 changes: 14 additions & 0 deletions .npmignore
@@ -0,0 +1,14 @@
src
test
tsconfig.json
tsconfig.module.json
tslint.json
.travis.yml
.github
.prettierignore
.vscode
build/docs
**/*.spec.*
coverage
.nyc_output
*.log
5 changes: 5 additions & 0 deletions CHANGELOG.md
@@ -0,0 +1,5 @@
# Changelog

All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

### 1.0.1 (2019-08-30)
21 changes: 21 additions & 0 deletions LICENSE
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Vithal Reddy

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.
34 changes: 34 additions & 0 deletions README.md
@@ -0,0 +1,34 @@
# cloud-detect-js

`cloud-detect-js` is a Node.JS module that determines a host's cloud provider. Highly inspired by the Go based [Satellite](https://github.com/banzaicloud/satellite), `cloud-detect-js` uses the same techniques (file systems and provider metadata) to properly identify cloud providers. Currently Supports AWS, GCP, Azure, Alibaba, Oracle, and Digital Ocean Cloud Providers.

## Installation

Via NPM:

```bash
npm install --save cloud-detect-js
```

Via Yarn:

```bash
yarn add cloud-detect-js
```

## Usage

```javascript
const { cloudProvider } = require('cloud-detect-js');

(async () => {
await cloudProvider();
// wil return one of 'aws', 'gcp', 'azure', 'oracle', 'alibaba', 'do' or 'unknown'

await cloudProvider();
// 'gcp'

await cloudProvider((excluded = ['aws', 'oracle']));
// 'unknown'
})();
```
50 changes: 50 additions & 0 deletions package.json
@@ -0,0 +1,50 @@
{
"name": "cloud-detect-js",
"version": "1.0.1",
"description": "Detect's host's cloud provider",
"main": "build/index.js",
"typings": "build/index.d.ts",
"repository": "git+https://github.com/vithalreddy/cloud-detect-js.git",
"license": "MIT",
"keywords": [],
"scripts": {
"build": "run-s clean && run-p build:*",
"build:main": "tsc -p tsconfig.json",
"fix": "run-s fix:*",
"fix:prettier": "prettier \"src/**/*.ts\" --write",
"fix:tslint": "tslint --fix --project .",
"watch": "run-s clean build:main && run-p \"build:main -- -w\"",
"version": "standard-version",
"reset": "git clean -dfx && git reset --hard && npm i",
"clean": "trash build",
"prepare-release": "run-s reset version"
},
"engines": {
"node": ">=8.9"
},
"dependencies": {
"@types/debug": "^4.1.5",
"axios": "^0.19.0",
"debug": "^4.1.1"
},
"devDependencies": {
"cz-conventional-changelog": "^2.1.0",
"gh-pages": "^2.0.1",
"npm-run-all": "^4.1.5",
"prettier": "^1.18.2",
"standard-version": "^6.0.1",
"trash-cli": "^3.0.0",
"tslint": "^5.18.0",
"tslint-config-prettier": "^1.18.0",
"tslint-immutable": "^6.0.1",
"typescript": "^3.5.3"
},
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
}
},
"prettier": {
"singleQuote": true
}
}
46 changes: 46 additions & 0 deletions src/index.ts
@@ -0,0 +1,46 @@
import {
AlibabaProvider,
AWSProvider,
AzureProvider,
DOProvider,
GCPProvider,
OracleProvider
} from './lib/providers';

export async function cloudProvider(
excluded: CloudProviders[] = []
): Promise<CloudProviders> {
if (!excluded.includes('aws')) {
const aws = new AWSProvider();
if (await aws.identify()) {
return 'aws';
}
} else if (!excluded.includes('gcp')) {
const gcp = new GCPProvider();
if (await gcp.identify()) {
return 'gcp';
}
} else if (!excluded.includes('azure')) {
const azure = new AzureProvider();
if (await azure.identify()) {
return 'azure';
}
} else if (!excluded.includes('do')) {
const digitalOcean = new DOProvider();
if (await digitalOcean.identify()) {
return 'do';
}
} else if (!excluded.includes('alibaba')) {
const alibaba = new AlibabaProvider();
if (await alibaba.identify()) {
return 'alibaba';
}
} else if (!excluded.includes('oracle')) {
const oracle = new OracleProvider();
if (await oracle.identify()) {
return 'oracle';
}
}

return 'unknown';
}
34 changes: 34 additions & 0 deletions src/lib/constants.ts
@@ -0,0 +1,34 @@
export const AWS = {
metaDataUrl:
'http://169.254.169.254/latest/dynamic/instance-identity/document',
vendorFile: '/sys/class/dmi/id/product_version'
};

export const GCP = {
headers: { 'Metadata-Flavor': 'Google' },
metaDataUrl:
'http://metadata.google.internal/computeMetadata/v1/instance/tags',
vendorFile: '/sys/class/dmi/id/product_name'
};

export const AZURE = {
headers: { Metadata: 'true' },
metaDataUrl:
'http://169.254.169.254/metadata/instance?api-version=2017-12-01',
vendorFile: '/sys/class/dmi/id/sys_vendor'
};

export const DO = {
metaDataUrl: 'http://169.254.169.254/metadata/v1.json',
vendorFile: '/sys/class/dmi/id/sys_vendor'
};

export const ORACLE = {
metaDataUrl: 'http://169.254.169.254/opc/v1/instance/metadata/',
vendorFile: '/sys/class/dmi/id/chassis_asset_tag'
};

export const ALIBABA = {
metaDataUrl: 'http://100.100.100.200/latest/meta-data/instance/instance-type',
vendorFile: '/sys/class/dmi/id/product_name'
};
3 changes: 3 additions & 0 deletions src/lib/logger.ts
@@ -0,0 +1,3 @@
import debug from 'debug';

export default debug('cloud-detect');
47 changes: 47 additions & 0 deletions src/lib/providers/alibaba.ts
@@ -0,0 +1,47 @@
import axios from 'axios';
import path from 'path';

import { existsSync, readFileSync } from 'fs';

import { ALIBABA } from '../constants';
import debugLog from '../logger';

export default class AlibabaProvider implements CloudProvider {
public async identify() {
const result =
(await this.checkMetadataServer()) || (await this.checkVendorFile());
return result;
}

public async checkMetadataServer() {
try {
const response = await axios.get(ALIBABA.metaDataUrl);
const data = response.data || {};

if (data && data.toString().startsWith('ecs.')) {
return true;
}
} catch (error) {
debugLog(error);
}
return false;
}

public async checkVendorFile() {
try {
const filePath = path.resolve(ALIBABA.vendorFile);
const fileExists = existsSync(filePath);

if (fileExists) {
const fileContent: string = readFileSync(filePath, 'utf8');
if (fileContent.indexOf('Alibaba Cloud') > -1) {
return true;
}
}
} catch (error) {
debugLog(error);
}

return false;
}
}
51 changes: 51 additions & 0 deletions src/lib/providers/aws.ts
@@ -0,0 +1,51 @@
import axios from 'axios';
import path from 'path';

import { existsSync, readFileSync } from 'fs';

import { AWS } from '../constants';
import debugLog from '../logger';

export default class AWSProvider implements CloudProvider {
public async identify() {
const result =
(await this.checkMetadataServer()) || (await this.checkVendorFile());
return result;
}

private async checkMetadataServer() {
try {
const response = await axios.get(AWS.metaDataUrl);
const data = response.data || {};

const { ImageID, InstanceID } = data;
if (ImageID && ImageID.startsWith('ami-')) {
return true;
}
if (InstanceID && InstanceID.startsWith('i-')) {
return true;
}
} catch (error) {
debugLog(error);
}
return false;
}

private async checkVendorFile() {
try {
const filePath = path.resolve(AWS.vendorFile);
const fileExists = existsSync(filePath);

if (fileExists) {
const fileContent: string = readFileSync(filePath, 'utf8');
if (fileContent.indexOf('amazon') > -1) {
return true;
}
}
} catch (error) {
debugLog(error);
}

return false;
}
}

0 comments on commit 74d90f9

Please sign in to comment.