Skip to content

Commit

Permalink
refactor: ♻️ Upgrading to terraform template
Browse files Browse the repository at this point in the history
  • Loading branch information
carolmsl committed Apr 14, 2022
1 parent a68931e commit 78c5434
Show file tree
Hide file tree
Showing 28 changed files with 2,311 additions and 196 deletions.
3 changes: 3 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@ updates:
directory: '/'
schedule:
interval: 'weekly'
ignore:
- dependency-name: 'request'
versions: '2.x'
2 changes: 1 addition & 1 deletion .github/workflows/codacy-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:

# Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis
- name: Run Codacy Analysis CLI
uses: codacy/codacy-analysis-cli-action@3.0.0
uses: codacy/codacy-analysis-cli-action@4.0.0
with:
# Check https://github.com/codacy/codacy-analysis-cli#project-token to get your project token from your Codacy repository
# You can also omit the token and run the tools that support default configurations
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/format-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ jobs:
- uses: actions/checkout@v2
with:
ref: ${{ github.head_ref }}
- uses: actions/setup-node@v2.1.5
- uses: actions/setup-node@v2.4.1
with:
node-version: '12.x'
- name: Install dependencies
Expand Down
5 changes: 2 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
name: Release
on:
push:
branches:
- master
branches: [master, main]
jobs:
release:
name: Release
Expand All @@ -13,7 +12,7 @@ jobs:
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v2.1.5
uses: actions/setup-node@v2.4.1
with:
node-version: 12
- name: Install dependencies
Expand Down
34 changes: 34 additions & 0 deletions .github/workflows/terraform.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: Terraform Validate

on: ['push']

jobs:
terraform-actions:
name: Terraform build
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./terraform
steps:
- name: Checkout Repository
uses: actions/checkout@master

- name: HashiCorp - Setup Terraform
uses: hashicorp/[email protected]
with:
terraform_version: 0.14.6

- name: Terraform Init
id: init
run: terraform init
continue-on-error: true

- name: Terraform Fmt
id: fmt
run: terraform fmt -check -diff
continue-on-error: true

- name: Terraform Validate
id: validate
run: terraform validate -no-color
continue-on-error: false
6 changes: 0 additions & 6 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,6 @@ jobs:
run: npm run test
- name: Run coverage
run: npm run coverage
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v1
with:
token: ${{ secrets.CODECOV_TOKEN }}
flags: unittests,integrationtest
name: codecov-nyc
- name: Upload coverage to Codacy
run: export CODACY_PROJECT_TOKEN=${{ secrets.CODACY_PROJECT_TOKEN }} && bash <(curl -Ls https://coverage.codacy.com/get.sh) report -r coverage/*
continue-on-error: true
37 changes: 37 additions & 0 deletions .terraform.lock.hcl

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

109 changes: 102 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Media Quality
# template-js-cloudfunction-with-terraform

<div align="center">
<img src="https://raw.githubusercontent.com/DP6/templates-centro-de-inovacoes/main/public/images/centro_de_inovacao_dp6.png" height="100px" />
Expand All @@ -8,12 +8,12 @@
<a href="#badge">
<img alt="semantic-release" src="https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg">
</a>
<a href="https://www.codacy.com/gh/DP6/{{token-codacy}}/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=DP6/{{repo}}&amp;utm_campaign=Badge_Coverage"><img alt="Code coverage" src="https://app.codacy.com/project/badge/Coverage/{{token-codacy}}"/></a>
<a href="https://www.codacy.com/gh/DP6/9716857fbc5e46afae4724fd6ffc1709/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=DP6/template-js-cloudfunction-with-terraform&amp;utm_campaign=Badge_Coverage"><img alt="Code coverage" src="https://app.codacy.com/project/badge/Coverage/9716857fbc5e46afae4724fd6ffc1709"/></a>
<a href="#badge">
<img alt="Test" src="https://github.com/dp6/media-quality/actions/workflows/test.yml/badge.svg">
<img alt="Test" src="https://github.com/dp6/template-js-cloudfunction-with-terraform/actions/workflows/test.yml/badge.svg">
</a>
<a href="https://www.codacy.com/gh/DP6/media-quality/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=DP6/media-quality&amp;utm_campaign=Badge_Grade">
<img alt="Code quality" src="https://app.codacy.com/project/badge/Grade/{{token-codacy}}">
<a href="https://www.codacy.com/gh/DP6/template-js-cloudfunction-with-terraform/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=DP6/template-js-cloudfunction-with-terraform&amp;utm_campaign=Badge_Grade">
<img alt="Code quality" src="https://app.codacy.com/project/badge/Grade/9716857fbc5e46afae4724fd6ffc1709">
</a>
</p>

Expand All @@ -36,9 +36,104 @@
</p>
-->

{{Texto introdutorio}}

<!-- Remover essa parte a partir desse comentário -->

Respositório template para CF utilizando

- Deploy com terraform de (Arquivos para GCS, Tabelas BQ e CF)
- Arquivo de configuração dinamico para CF
- Testes unitários
- Teste de integração
- Formatação de código
- Geração de documentação das funcões javascrip
- Criação de release automatica
- Cobertura de código
- Analise de qualidade de código
- Github pages com template do github.dp6.io

# Preparando o repositório

Crie seu projeto baseado nesse repositório.

<img src="https://raw.githubusercontent.com/DP6/templates-centro-de-inovacoes/main/public/images/create-new-reposotory-from-template.png"/>

(Passo a passo github)[https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-repository-on-github/creating-a-repository-from-a-template]

## Variáveis de ambiente no github (secrets)

Primeiro é necessário conectar o repositório do Github com o (coday.com)[https://app.codacy.com/organizations/gh/DP6/repositories] (referência para conexão)[https://docs.codacy.com/organizations/managing-repositories/#adding-a-repository].

Necessário criar a screte CODACY_PROJECT_TOKEN nas configurações do seu repositório no Github em Settings > Secret > New repository Secret

<img src="https://raw.githubusercontent.com/DP6/templates-centro-de-inovacoes/main/public/images/step-input-secret.png"/>

<img src="https://raw.githubusercontent.com/DP6/templates-centro-de-inovacoes/main/public/images/step-creat-secret-CODACY.png"/>

## Renomeando os arquivos

- Substituir o nome `template-js-cloudfunction-with-terraform` pelo nome do novo repositório criado no arquivo package.json
- Substituir a chave `{{nome_projeto}}` no arquivo `_config.yml` com o nome do projeto em linguagem natural, para ser usado como titulo da página no site.
- As variáveis do terraform e e arquivos de exemplo para criação das tabelas no BQ usa a vável `project_name` que pode ser alterado a critério do usuário.
- No README.md as chaves `{{token-codacy}}` e `{{repo}}` localizada no cabecalho do documento dentro do comentário nas linhas 20-37 deve ser substituida pelo token do projeto no codacy.io e novo nome do repositório.

## Entendendo o terraform

É recomendo a leitura da documentação oficial do (terraform para Google)[https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/getting_started]

<!-- Remover a parte introdutoria até esse comentário -->

## Entendendo os running do NPM

- **unit-test**: Realiza uma bateria de testes unitários dos arquivos de js presentes na pasta test/unit;
- **integration-test**: Realiza uma bateria de testes de integração dos arquivos de js presentes na pasta test/integration;
- **all-test**:Realiza uma bateria de todos os testes presentes na pasta test/;
- **test**: alias para o comando `all-test`;
- **lint-md**: Submete o código a markdown a uma avaliação do `remark`;
- **lint-prettier**: Submete o código a uma avaliação utilizando o [Prettier](https://prettier.io/), de acordo com a configuração descrita no arquivo .prettierrc;,
- **lint**: Alias para executar todos os lints;
- **format**: Formata todo o código do projeto, utilizando o [Prettier](https://prettier.io/), de acordo com a configuração descrita no arquivo .prettierrc;
- **coverage**: Análise da cobertura dos testes;
- **local**: Executa a cloud function localmente utilizando o functions-frameworks;
- **coverage**: "nyc --reporter=lcov --reporter=cobertura npm run unit-test",
- **docs**: Gera a documentção do código fonte seguindo o padrão do `jsdoc2md` aplicado no arquivo index.js, a doc é armanezada em docs/index.md",

## 1. Requisitos para utilização

- Node
### 1.1 Produtos do GCP

- BigQuery
- Cloud Storage
- Cloud Function
- Service account

### 1.2 Dependências ambiente local

1. [Google Cloud SDK ](https://cloud.google.com/sdk/docs/install?hl=pt-br)
2. Pacotes zip, unzip e curl
3. [Criar service Account](https://cloud.google.com/iam/docs/creating-managing-service-accounts) com as permissões (Storage Object Admin, Cloud Functions Admin, BigQuery Admin e Service Account User)
4. Variável [GOOGLE_APPLICATION_CREDENTIALS](https://cloud.google.com/docs/authentication/getting-started#setting_the_environment_variable)
5. Instalar o [Terraform](https://www.terraform.io/downloads.html)
6. Habilitar os produtos no GCP Cloud Function, BigQuery, Cloud Build API, Cloud Resource Manager API, BigQuery Data Transfer API e Cloud Storage, para uso do BigQuery é necessário ter um billing ativo
7. _Importante_ o usuário que executar o script do terraform precisa ter a permissão de owner no projeto do GCP.

_Observação:_ Utilizando o ambiente no [Google Cloud Shell](https://cloud.google.com/shell/docs) não é necessário fazer os **1**, **2**, **4** e **5**

## 2. Instalando

Clone o projeto do github para sua máquina local ou Cloud Shell

```console
git clone https://github.com/DP6/{{repo}}.git
```

Para fazer deploy no GCP usando o Terraform, o utilize o shell script terraform_deploy

```console
cd {{repo}}
sh terraform_deploy.sh
```

## Como contribuir

Expand All @@ -52,7 +147,7 @@ Só serão aceitas contribuições que estiverem seguindo os seguintes requisito

### Api Docs

- [Index.js](https://github.com/dp6/media-quality/blob/master/docs/index.md)
- [Index.js](https://github.com/dp6/template-js-cloudfunction-with-terraform/blob/master/docs/index.md)

## Suporte:

Expand Down
2 changes: 1 addition & 1 deletion _config.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
title: DP6 - Centro de inovações
initiative: 'Media Quality'
initiative: '{{nome_projeto}}'

markdown: kramdown
remote_theme: dp6/dp6.github.io
Expand Down
26 changes: 17 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
const fs = require('fs');
const { BigQuery } = require('@google-cloud/bigquery');
const { Storage } = require('@google-cloud/storage');
const BUCKET_GCS = process.env.PROJECT_BUCKET_GCS;
const PROJECT_FOLDER = 'project-name';
let projectConfig = {};
let debugging = false;

Expand Down Expand Up @@ -39,7 +42,7 @@ const templateCf = async (req, res) => {
);

trace('RESULT VALID', result);
insertRowsAsStream(result);
insertRowsAsStream(result, projectConfig.BQ_SCHEMA_RAWDATA, projectConfig.BQ_TABLE_ID_RAWDATA);
res.status(200).send(debugging ? { debugging: debugging, result: result } : 'sucesso!');
}
};
Expand Down Expand Up @@ -78,21 +81,20 @@ function addTimestamp(data) {
/**
* Realiza a persistências dos dados por Stream no BigQuery
* @param {Array} data Dados estruturados no padrão de persistência do BQ
* @param {String} schema Schema da tabela do BQ
* @param {String} tableId Nome da tabela do BQ
*/
async function insertRowsAsStream(data) {
async function insertRowsAsStream(data, schema, tableId) {
const bigquery = new BigQuery();
const options = {
schema: projectConfig.BQ_SCHEMA_RAWDATA,
schema: schema,
skipInvalidRows: true,
ignoreUnknownValues: true,
};

trace(data);
// Insert data into a table
await bigquery
.dataset(projectConfig.BQ_DATASET_ID)
.table(projectConfig.BQ_TABLE_ID_RAWDATA)
.insert(data, options, insertHandler);
await bigquery.dataset(projectConfig.BQ_DATASET_ID).table(tableId).insert(data, options, insertHandler);

console.log(`Inserted ${data.length} rows`);
}
Expand All @@ -101,7 +103,13 @@ async function insertRowsAsStream(data) {
* Carrega o arquivo de configuração armazenado no GCS
*/
async function loadProjectConfig() {
return JSON.parse(fs.readFileSync('./config.json'));
const storage = new Storage();
const bucket = storage.bucket(BUCKET_GCS);

let file = bucket.file(`${PROJECT_FOLDER}/config.json`);
let projectConfig = (await file.download())[0].toString();

return JSON.parse(projectConfig);
}

function insertHandler(err, apiResponse) {
Expand Down
Loading

0 comments on commit 78c5434

Please sign in to comment.