Skip to content

Commit

Permalink
feat: support no migration deploy
Browse files Browse the repository at this point in the history
  • Loading branch information
yugasun committed Dec 4, 2020
1 parent eb2f187 commit 9670f55
Show file tree
Hide file tree
Showing 11 changed files with 126 additions and 101 deletions.
134 changes: 72 additions & 62 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,71 +1,71 @@
[![Serverless PHP Laravel Tencent Cloud](https://img.serverlesscloud.cn/20191226/1577347087676-website_%E9%95%BF.png)](http://serverless.com)

# 腾讯云 Laravel Serverless Component

## 简介
<br/>

腾讯云 [Laravel](https://github.com/laravel/laravel) Serverless Component, 支持 `Laravel >= 6.0`

## 目录
<br/>

0. [准备](#0-准备)
1. [安装](#1-安装)
1. [配置](#2-配置)
1. [部署](#3-部署)
1. [移除](#4-移除)
特性介绍:

### 0. 准备
- [x] **按需付费** - 按照请求的使用量进行收费,没有请求时无需付费
- [x] **"0"配置** - 只需要关心项目代码,之后部署即可,Serverless Framework 会搞定所有配置。
- [x] **极速部署** - 仅需几秒,部署你的整个 laravel 应用。
- [x] **便捷协作** - 通过云端的状态信息和部署日志,方便的进行多人协作开发。
- [x] **自定义域名** - 支持配置自定义域名及 HTTPS 访问

#### 初始化 Laravel 项目
<br/>

在使用此组件之前,你需要先自己初始化一个 `laravel` 项目
快速开始:

```bash
composer create-project --prefer-dist laravel/laravel serverless-laravel
```
1. [**安装**](#1-安装)
2. [**创建**](#2-创建)
3. [**部署**](#3-部署)
4. [**配置**](#4-配置)
5. [**查看状态**](#5-查看状态)
6. [**移除**](#6-移除)

> 注意:Laravel 使用 Coposer 管理依赖的,所以你需要先自行安装 Composer,请参考 [官方安装文档](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-macos)
更多资源:

#### 修改 Laravel 项目
- [**架构说明**](#架构说明)
- [**账号配置**](#账号配置)

由于云函数在执行时,只有 `/tmp` 可读写的,所以我们需要将 `laravel` 框架运行时的 `storage` 目录写到该目录下,为此需要修改 `bootstrap/app.php` 文件,在 `$app = new Illuminate\Foundation\Application` 后添加:
&nbsp;

```php
$app->useStoragePath(env('APP_STORAGE', '/tmp'));
```
### 1. 安装

然后在根目录下的 `.env` 文件中新增如下配置:
通过 npm 安装最新版本的 Serverless Framework

```dotenv
# 视图文件编译路径
VIEW_COMPILED_PATH=/tmp/storage/framework/views
```bash
$ npm install -g serverless
```

# 由于是无服务函数,所以没法存储 session 在硬盘上,如果不需要 sessions,可以使用 array
# 如果需要你可以将 session 存储到 cookie 或者数据库中
SESSION_DRIVER=array
### 2. 创建

# 建议将错误日志输出到控制台,方便云端去查看
LOG_CHANNEL=stderr
通过如下命令和模板链接,快速创建一个 laravel 应用:

# 应用的 storage 目录必须为 /tmp
APP_STORAGE=/tmp
```bash
$ serverless init laravel-starter --name serverless-laravel
$ cd example
```

### 1. 安装
### 3. 部署

通过 npm 全局安装 [serverless cli](https://github.com/serverless/serverless)
`serverless.yml` 文件所在的项目根目录,运行以下指令进行部署:

```bash
$ npm install -g serverless
$ serverless deploy
```

### 2. 配置
部署时需要进行身份验证,如您的账号未 [登陆](https://cloud.tencent.com/login)[注册](https://cloud.tencent.com/register) 腾讯云,您可以直接通过 `微信` 扫描命令行中的二维码进行授权登陆和注册。

在项目根目录,创建 `serverless.yml` 文件,在其中进行如下配置
> 注意: 如果希望查看更多部署过程的信息,可以通过`serverless deploy --debug` 命令查看部署过程中的实时日志信息。
```bash
$ touch serverless.yml
```
### 4. 配置

laravel 组件支持 0 配置部署,也就是可以直接通过配置文件中的默认值进行部署。但你依然可以修改更多可选配置来进一步开发该 laravel 项目。

以下是 laravel 组件的 `serverless.yml`配置示例:

```yml
# serverless.yml
Expand All @@ -77,7 +77,9 @@ app: appDemo
stage: dev

inputs:
src: ./
src:
src: ./
functionName: laravelDemo
region: ap-guangzhou
runtime: Php7
apigatewayConf:
Expand All @@ -87,50 +89,58 @@ inputs:
environment: release
```
- [更多配置](https://github.com/serverless-components/tencent-laravel/tree/master/docs/configure.md)
点此查看[全量配置及配置说明](https://github.com/serverless-components/tencent-laravel/tree/master/docs/configure.md)
### 3. 部署
当你根据该配置文件更新配置字段后,再次运行 `serverless deploy` 或者 `serverless` 就可以更新配置到云端。

### 5. 查看状态

在`serverless.yml`文件所在的目录下,通过如下命令查看部署状态:

> 注意:**在部署前,你需要先清理本地运行的配置缓存,执行 `php artisan config:clear` 即可。**
```
$ serverless info
```
如您的账号未 [登陆](https://cloud.tencent.com/login) 或 [注册](https://cloud.tencent.com/register) 腾讯云,您可以直接通过 `微信` 扫描命令行中的二维码进行授权登陆和注册。
### 6. 移除
通过 `sls` 命令进行部署,并可以添加 `--debug` 参数查看部署过程中的信息
在`serverless.yml`文件所在的目录下,通过以下命令移除部署的 laravel 服务。移除后该组件会对应删除云上部署时所创建的所有相关资源。
```bash
$ sls deploy
```
$ serverless remove
```
> 注意: `sls` 是 `serverless` 命令的简写
和部署类似,支持通过 `serverless remove --debug` 命令查看移除过程中的实时日志信息
### 4. 移除
## 架构说明
通过以下命令移除部署的 Laravel 服务。
laravel 组件将在腾讯云账户中使用到如下 Serverless 服务:
```bash
$ sls remove
```
- [x] **API 网关** - API 网关将会接收外部请求并且转发到 SCF 云函数中。
- [x] **SCF 云函数** - 云函数将承载 laravel.js 应用。
- [x] **CAM 访问控制** - 该组件会创建默认 CAM 角色用于授权访问关联资源。
- [x] **COS 对象存储** - 为确保上传速度和质量,云函数压缩并上传代码时,会默认将代码包存储在特定命名的 COS 桶中。
- [x] **SSL 证书服务** - 如果你在 yaml 文件中配置了 `apigatewayConf.customDomains` 字段,需要做自定义域名绑定并开启 HTTPS 时,也会用到证书管理服务和域名服务。Serverless Framework 会根据已经备案的域名自动申请并配置 SSL 证书。
### 账号配置(可选)
## 账号配置
当前默认支持 CLI 扫描二维码登录,如您希望配置持久的环境变量/秘钥信息,也可以本地创建 `.env` 文件
```console
$ touch .env # 腾讯云的配置信息
```

`.env` 文件中配置腾讯云的 SecretId 和 SecretKey 信息并保存

如果没有腾讯云账号,可以在此 [注册新账号](https://cloud.tencent.com/register)。
如果没有腾讯云账号,可以在此[注册新账号](https://cloud.tencent.com/register)

如果已有腾讯云账号,可以在 [API 密钥管理](https://console.cloud.tencent.com/cam/capi) 中获取 `SecretId` 和`SecretKey`.
如果已有腾讯云账号,可以在[API 密钥管理](https://console.cloud.tencent.com/cam/capi)中获取 `SecretId``SecretKey`.

```text
```
# .env
TENCENT_SECRET_ID=123
TENCENT_SECRET_KEY=123
```

### 更多组件

可以在 [Serverless Components](https://github.com/serverless/components/blob/master/README.cn.md) repo 中查询更多组件的信息。

## License

MIT License
Expand Down
23 changes: 9 additions & 14 deletions tests/integration.test.js → __tests__/index.test.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
const { generateId, getServerlessSdk } = require('./utils')
const execSync = require('child_process').execSync
const path = require('path')
const { generateId, getServerlessSdk } = require('./lib/utils')
const axios = require('axios')

// set enough timeout for deployment to finish
jest.setTimeout(600000)

// the yaml file we're testing against
const instanceYaml = {
org: 'orgDemo',
app: 'appDemo',
component: 'laravel',
component: 'laravel@dev',
name: `laravel-integration-tests-${generateId()}`,
stage: 'dev',
inputs: {
Expand All @@ -20,16 +14,17 @@ const instanceYaml = {
}
}

// get credentials from process.env but need to init empty credentials object
const credentials = {
tencent: {}
tencent: {
SecretId: process.env.TENCENT_SECRET_ID,
SecretKey: process.env.TENCENT_SECRET_KEY
}
}

// get serverless construct sdk
const sdk = getServerlessSdk(instanceYaml.org)

it('should successfully deploy laravel app', async () => {
const instance = await sdk.deploy(instanceYaml, { tencent: {} })
it('should deploy success', async () => {
const instance = await sdk.deploy(instanceYaml, credentials)

expect(instance).toBeDefined()
expect(instance.instanceName).toEqual(instanceYaml.name)
Expand All @@ -44,7 +39,7 @@ it('should successfully deploy laravel app', async () => {
expect(response.data.includes('Laravel')).toBeTruthy()
})

it('should successfully remove laravel app', async () => {
it('should remove success', async () => {
await sdk.remove(instanceYaml, credentials)
result = await sdk.getInstance(
instanceYaml.org,
Expand Down
File renamed without changes.
15 changes: 0 additions & 15 deletions example/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,6 @@ PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"


# views compiled path
VIEW_COMPILED_PATH=/tmp/storage/framework/views

# We cannot store sessions to disk: if you don't need sessions (e.g. API)
# then use `array`, else store sessions in database or cookies
SESSION_DRIVER=array

# Logging to stderr allows the logs to end up in Cloudwatch
LOG_CHANNEL=stderr

# app storage dir must be /tmp
APP_STORAGE=/tmp


# tencent crendential
TENCENT_SECRET_ID=xxx
TENCENT_SECRET_KEY=xxx
2 changes: 0 additions & 2 deletions example/bootstrap/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

$app->useStoragePath(env('APP_STORAGE', '/tmp'));

/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
Expand Down
7 changes: 4 additions & 3 deletions example/serverless.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
component: laravel
name: laravelDemo
org: orgDemo
app: appDemo
stage: dev
component: laravel
name: laravelDemo

inputs:
src: ./ # (optional) path to the source folder. default is a hello world app.
src:
src: ./
region: ap-guangzhou
runtime: Php7
apigatewayConf:
Expand Down
14 changes: 14 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const { join } = require('path')
require('dotenv').config({ path: join(__dirname, '.env.test') })

const config = {
verbose: true,
silent: false,
testTimeout: 60000,
testEnvironment: 'node',
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(js|ts)$',
testPathIgnorePatterns: ['/node_modules/', '/__tests__/lib/'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
}

module.exports = config
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
"access": "public"
},
"scripts": {
"int-test": "jest ./tests/integration.test.js --testEnvironment node",
"test": "npm run lint && npm run prettier && npm run int-test",
"test": "jest",
"commitlint": "commitlint -f HEAD@{15}",
"lint": "eslint --ext .js,.ts,.tsx .",
"lint:fix": "eslint --fix --ext .js,.ts,.tsx .",
Expand Down
2 changes: 1 addition & 1 deletion serverless.component.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: laravel
version: 0.0.9
version: 0.1.0
author: 'Tencent Cloud, Inc'
org: 'Tencent Cloud, Inc'
description: Deploy a serverless Laravel application on Tencent SCF and API Gateway.
Expand Down
8 changes: 7 additions & 1 deletion src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@ const CONFIGS = {
timeout: 3,
memorySize: 128,
namespace: 'default',
description: 'Created by Serverless Component'
description: 'Created by Serverless Component',
envs: {
VIEW_COMPILED_PATH: '/tmp/storage/framework/views',
SESSION_DRIVER: 'array',
LOG_CHANNEL: 'stderr',
APP_STORAGE: '/tmp'
}
}

module.exports = CONFIGS
19 changes: 18 additions & 1 deletion src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,25 @@ const prepareInputs = async (instance, credentials, inputs = {}) => {
functionConf.needSetTraffic = inputs.traffic !== undefined && functionConf.lastVersion

if (tempFunctionConf.environment) {
functionConf.environment = inputs.functionConf.environment
functionConf.environment = tempFunctionConf.environment
functionConf.environment.variables = functionConf.environment.variables || {}
functionConf.environment.variables.SERVERLESS = '1'
functionConf.environment.variables.VIEW_COMPILED_PATH = CONFIGS.envs.VIEW_COMPILED_PATH
functionConf.environment.variables.SESSION_DRIVER = CONFIGS.envs.SESSION_DRIVER
functionConf.environment.variables.LOG_CHANNEL = CONFIGS.envs.LOG_CHANNEL
functionConf.environment.variables.APP_STORAGE = CONFIGS.envs.APP_STORAGE
} else {
functionConf.environment = {
variables: {
SERVERLESS: '1',
VIEW_COMPILED_PATH: CONFIGS.envs.VIEW_COMPILED_PATH,
SESSION_DRIVER: CONFIGS.envs.SESSION_DRIVER,
LOG_CHANNEL: CONFIGS.envs.LOG_CHANNEL,
APP_STORAGE: CONFIGS.envs.APP_STORAGE
}
}
}

if (tempFunctionConf.vpcConfig) {
functionConf.vpcConfig = inputs.functionConf.vpcConfig
}
Expand Down

0 comments on commit 9670f55

Please sign in to comment.