温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎样快速搭建serverless网盘服务

发布时间:2021-12-13 11:02:50 来源:亿速云 阅读:154 作者:柒染 栏目:云计算

本篇文章为大家展示了怎样快速搭建serverless网盘服务,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

前言

函数计算支持以无服务器架构快速构建企业和开发者的软件系统,以其全托管事件触发模式、超弹性伸缩以及低廉的计费方式,相对于传统服务器架构,在开发效能和运维模式上都取得了明显优势。另外还提供了各种服务间的触发功能,作为云端各种产品的黏合剂,适用于各种应用场景。

将带领大家利用函数计算,快速搭建一个功能完整的网盘服务。

网盘服务简介

功能

网盘服务功能详细介绍请参考文章网盘服务系统和相应的项目 repo 。

本文重点不是介绍网盘功能,所以,请大家通过已经搭建好的网盘 demo 自行体验,这里不做过多赘述。

网盘系统无服务器架构

怎样快速搭建serverless网盘服务

网盘服务功能集较多,这里就以上传文件功能为例,展现其网盘的实现架构。

网盘服务自身模块以及资源依赖

网盘服务的模块实现分为三个部分,如下图所示:

怎样快速搭建serverless网盘服务

  • apis : 提供了网盘的 API 接口功能,这部分功能是 serverless 架构实现的核心,使用 FC+API Gateway 架构模式实现主体功能,如上图无服务器架构图中展现的。

  • Site : 提供了网盘实例的管理控制台,还有对应的网盘宣传、使用文档以及 api 文档等。

  • UI : 提供用户使用和维护网盘的客户端。

这里,Site 和 UI 这两个子模块的实现都是静态网站模式,可以直接使用 OSS bucket 的 website 特性实现。为了简化整个部署流程和自动化资源编排过程,将 Site 和 UI 的部署方式也整合到 FC 中统一维护,见下面的详细的部署流程描述。

网盘服务功能后台依赖资源罗列如下:

怎样快速搭建serverless网盘服务

fun 介绍

fun 是 have Fun with Serverless 的缩写,是一款 Serverless 应用开发的工具,可以帮助用户定义函数计算、API 网关、日志服务等资源,旨在与阿里云 ROS 兼容(尽管到目前为止 ROS 还不支持函数计算。但是,fun 作为 ROS 的子集是我们的目标)。

使用 fun 能够解决复杂服务的资源依赖维护问题,能够快速部署、更新,简化资源编排运维。针对该网盘服务的众多资源依赖,使用 fun 能够很方便、迅速的解决各种资源的搭建和维护过程。下面我们将演示如何使用 fun 部署网盘服务系统。

具体部署过程

网盘服务目前实现了三种身份登录验证功能: 钉钉、支付宝和特殊账号密码(用于测试)。
因为钉钉、支付宝登录方式需要走一些申请流程获取对应的 appID 和 appSecret ,这里为了简化流程,我们仅仅使用特殊账号密码方式。

部署的具体步骤如下:

  1. 准备工作:

    • 云账号准备

    • 代码准备

    • fun 下载和配置

  2. 配置 fun 的 template.yml

  3. 部署 template.yml 定义资源,获取二级域名等信息

  4. 更新 apis function

  5. 部署 Site ,创建 groupID 实例

  6. 部署 UI,配置 storage 实例

准备工作

云账号准备

首先,准备一个能够登录阿里云官网的云账号, 登录控制台获取这个账号的 UID ( accountID )、 accessKeyID 和 accessKeySecret 。部署演示使用的资源全部在华东 2 ( cn-shanghai )。也可以使用其他 region 资源,但是必须保证所有的服务都在同一个 region 中。

然后开通如下服务:
怎样快速搭建serverless网盘服务

代码准备

函数计算支持多种代码上传方式,这里统一打包成 zip 文件,并上传到该云账号的某个 bucket 上(用户自行在华东 2 创建即可)。参考代码如下连接:

  • apis.zip

    • 注意: apis 使用 nodejs 实现,在打包之前需要执行 tnpm i 命令安装项目依赖。

    • 解压后目录结构如下:

        |-- controllers # 控制层,主要逻辑
      
        |-- routes        # api路由
      
        |-- services     # 公共方法,包含调用各个云产品的方法
      
        |-- utils    
      
        |-- models
      
        |-- node_modules   # 项目依赖
      
        |-- index.js     # 服务入口
      
        |-- conf.js       # config 配置
      
        |-- package.json
  • site.zip

        |-- deploy.py   # 部署函数
    
        |-- site             # site代码目录
    
       |-- 404.html  
    
       |-- index.html    
    
       |-- docs
    
       |-- static
    • 解压后文件结构如下:

  • ui.zip

        |-- deploy.py   # 部署函数
    
        |-- ui                # ui代码目录
    
       |-- 404.html  
    
       |-- index.html    
    
       |-- static
    • 解压后文件结构如下:

fun 下载和配置

如果您的系统已经安装有 node 8 及以上的环境配置,那么可以直接执行如下命令进行 fun 的安装

npm install @alicloud/fun -g

如果您不想安装 node 运行环境,那么可以直接下载 fun 的 binary 执行,参考各种环境 fun 的 release binary 。

然后设置 accountID、accessKeyID 和 accessKeySecret 以及 region,请使用准备步骤中的已经申请的云账号的参数进行配置,本示例中 region 选择 cn-shanghai :

# 如果是 binary ,执行 ./${binary_name} configfun config

template.yml 配置

template.yml 模板配置是本部署中最重要的部分,因为网盘服务依赖的资源项比较多(主要是 API网关资源和表格存储资源), 建议下载参考模板直接修改,需要修改的内容已经使用 "TODO" 标识。

template.yml 的语法规范参考 fun 规范文档。

这面具体介绍配置中的相关部分:

ROSTemplateFormatVersion: '2015-09-01'Transform: 'Aliyun::Serverless-2018-04-03'Resources:

  apsaradrivefc:

    Type: 'Aliyun::Serverless::Service'

    Properties:

      Description: apsara drive

      Policies:

        - AliyunOTSFullAccess

        - AliyunSTSAssumeRoleAccess

        - AliyunOTSFullAccess

        - AliyunLogFullAccess

        - AliyunFCInvocationAccess

      LogConfig:

        Project: log-yunpan # TODO replace sls project name

        Logstore: fclog

    apis:

      Type: 'Aliyun::Serverless::Function'

      Properties:

        Description: apis

        Runtime: nodejs8

        Timeout: 30

        MemorySize: 128

        Handler: index.handler

        CodeUri: oss://apsaradrive-ui/download/apis.zip # TODO replaced the code location

        EnvironmentVariables: # TODO replace all the values which has 'TODO' tag

          ENV_CONFIG: '...'

    DeploySite: # function name which deploys site

         Type: 'Aliyun::Serverless::Function'

         Properties:

            Handler: 'deploy.my_handler'

            Runtime: 'python2.7'

            Description: 'function to deploy site'

            MemorySize: 128

            Timeout: 30

            CodeUri: 'oss://apsaradrive-ui/download/site.zip' # TODO replaced by the code location

    DeployUI: # function name witch deploys ui

         Type: 'Aliyun::Serverless::Function'

         Properties:

            Handler: 'deploy.my_handler'

            Runtime: 'python2.7'

            Description: 'function to deploy ui'

            MemorySize: 128

            Timeout: 30

            CodeUri: 'oss://apsaradrive-ui/download/ui.zip' # TODO replaced by the code location

  apsaradriveapis:

    Type: 'Aliyun::Serverless::Api'

    ...


  ts-yunpan: # TODO replace ots instance name

    Type: 'Aliyun::Serverless::TableStore'

    Properties:

      ClusterType: HYBRID

      Description: for apsaradrive

     ...  log-yunpan: # TODO replace sls project name

    Type: 'Aliyun::Serverless::Log'

    Properties:

      Description: log

    fclog:

      Type: 'Aliyun::Serverless::Log::Logstore'

      Properties:

        TTL: 10

        ShardCount: 1

上面定义的 yaml 文件主要做了以下几件事情:

  1. 创建一个名为 'apsaradrivefc' 的 Service , 并且为这个 Service 创建一个具有 AliyunOTSFullAccess 、AliyunSTSAssumeRoleAccess 、 AliyunOTSFullAccess 、 AliyunLogFullAccess 和AliyunFCInvocationAccess 这几大权限的 Service Role。然后在这个 Service 下面创建三个 Function ,分别名为 'apis', 'DeploySite' 和 'DeployUI' 。

  2. 创建一个 LOG Project名为 'log-yunpan' , 然后在这个LOG Project 下面创建一个名为 'fclog' 的 Logstore ,作为 apsaradrivefc 这个 Service 下 Function 执行的日志收集 store 。

  3. 创建一个名为 'ts-yunpan' 的 OTS Instance , 并且在这面生成各种 Table 。

  4. 创建一个 API 网关分组: apsaradriveapis ,以及其下的各种 API 定义。

需要修改的内容:

  1. OTS Instance name: 全局有三处地方需要修改,请统一,因为 OTS Instance 在 region 范围全局唯一,尽量保持命名唯一性,注意: OTS Instance 命名规范。

  2. LOG Project name: 全局有两处地方需要修改,请统一,因为 LOG Project在region范围全局唯一,尽量保持命名唯一性,注意: LOG Project 命名规范。

  3. 三处 CodeUri ,分别是 apis ,Site 和 UI 三个模块的代码位置,目前 template.yml 中的默认配置可用,可以不修改。

  4. apis 这个 Function 中的 EnvironmentVariables 属性内部需要配置 API 网关分组的二级域名,因为当前步骤还没有生成这个参数,这里先不修改。

部署 template.yml 定义资源

直接执行如下命令:

# 在 template.yml 所在目录执行# 如果是 binary ,执行 ./${binary_name} configfun deploy

这个时候,你可以在 OTS、SLS、RAM、API 网关和 FC 的控制台上分别看到 fun 为网盘服务创建的各种资源,如下图:

怎样快速搭建serverless网盘服务

怎样快速搭建serverless网盘服务

怎样快速搭建serverless网盘服务

怎样快速搭建serverless网盘服务

更新 apis function

从上一步 fun 的部署输出日志中可以找到对应的 API 网关分组的二级域名,如下:
怎样快速搭建serverless网盘服务

修改 apis 这个 Function 中的 EnvironmentVariables 属性内部需要配置 API 网关分组的二级域名,如下图位置:

怎样快速搭建serverless网盘服务

仍然执行如下命令,进行function的环境变量更新

fun deploy

至此,apis 模块部署完毕。

部署 Site ,创建 groupID 实例

Site 模块的实现其实就是一个静态网站,我们可以利用 OSS 的静态网站功能实现,步骤如下:

  1. 修改 static/global.js 中的 endpoint ( apis 的二级域名)和 ui_endpoint (如果在华东2, 那么就是 ${uid}-ui.oss-cn-shanghai.aliyuncs.com )

  2. 创建 ${uid}-site 这个 bucket ,并设置为 public-read ACL

  3. 设置这个 bucket 的 website 的默认首页和 404 页面

  4. 上传整个代码目录

将所有的步骤按照函数计算编程模型封装如下,并创建为 Function: DeploySite 。封装的 Function 实现如下所示:

import oss2import loggingimport jsonimport shutilimport osimport sys

reload(sys)
sys.setdefaultencoding('utf8')from oss2.models import BucketWebsitedef delete_file(filePath):

    if os.path.exists(filePath):        for fileList in os.walk(filePath):            for name in fileList[2]:

                os.remove(os.path.join(fileList[0],name))

        shutil.rmtree(filePath)def my_handler(event, context):

    # event is json string, parse it

    evt = json.loads(event)

    logger = logging.getLogger()

    endpoint = 'oss-cn-shanghai-internal.aliyuncs.com'

    creds = context.credentials

    auth = oss2.StsAuth(creds.accessKeyId, creds.accessKeySecret, creds.securityToken)    # create bucket for site named ${uid}-site, and set the ACL to public read

    bucket_name = '%s-site' % (evt['uid'])

    bucket = oss2.Bucket(auth, endpoint, bucket_name)    try:

        bucket.create_bucket(permission=oss2.BUCKET_ACL_PUBLIC_READ)    except oss2.exceptions.BucketAlreadyExists:

        logger.info("Bucket %s is already exist" % bucket_name)    # set static website

    bucket.put_bucket_website(BucketWebsite('index.html', '404.html'))   # modify the config for site

    code_dir = '/tmp/site/'

    delete_file(code_dir)

    shutil.copytree('/code/site/', code_dir)

    data = u''

    with open(os.path.join(code_dir, 'static/global.js')) as f:        for line in f.readlines():            if line.startswith('var endpoint = '):

                line = u'var endpoint = \'%s\';\n' % (evt['endpoint'])            elif line.startswith('var ui_endpoint = '):

                line = u'var ui_endpoint = \'http://%s.oss-cn-shanghai.aliyuncs.com\';\n' % (bucket_name)

            data += line    with open(os.path.join(code_dir, '/tmp/site/static/global.js'), "w") as f:

        f.writelines(data)    # put all the static code to the bucket

    for root,dirs,files in os.walk(code_dir):        for filespath in files:

            full_file_name = os.path.join(root,filespath)

            bucket.put_object_from_file(full_file_name[len(code_dir):], full_file_name)

所以,只需要 Invoke 这个 Function 就能够完成 Site 模块的部署。接下来演示一下 Invoke 的过程。

登录函数计算控制台,找到对应的 Function: DeploySite ,修改触发事件,然后点击执行:

怎样快速搭建serverless网盘服务

{  "uid": "replace with you accountID",  "endpoint": "replace with the SLD"}

然后打开 Site 页面(如果 uid 为 apsaradrive 的话,那么 Site 的 URL 为: http://apsaradrive-site.oss-cn-shanghai.aliyuncs.com ),登录之后(使用默认的 username: admin, password: 1234 登录),创建 group 实例。

怎样快速搭建serverless网盘服务

部署 UI,配置 storage 实例

部署 UI 的过程和 Site 类似,同样在控制台上找到 DeployUI,修改触发事件,注意事件格式定义如下:

{  "uid": "replace with you accountID",  "group_id": "replace with the group_id you just create in the Site web"

  "endpoint": "replace with the SLD"}

点击执行之后,就可以通过刚刚 Site 页面的 Group 入口进入 UI 页面:
怎样快速搭建serverless网盘服务

在 UI 页面配置相关的 Storage :

怎样快速搭建serverless网盘服务

接下来,您就可以对您的网盘进行各种文件操作了。
怎样快速搭建serverless网盘服务
怎样快速搭建serverless网盘服务

上述内容就是怎样快速搭建serverless网盘服务,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI