העברת הגדרות של Cloud Foundry ל-Cloud Run

כדי לפרוס ולהריץ אפליקציות של Cloud Foundry ב-Cloud Run, אתם יכולים להעביר את הגדרות הפריסה להגדרות שירות דקלרטיביות שתואמות ל-Knative. התהליך הזה כולל המרה של manifest.yaml ב-Cloud Foundry ל-service.yaml ב-Cloud Run, צירוף שירותים תומכים ופריסה של שירות Cloud Run.

לפני שמתחילים

כדי להשלים את ההעברה, צריכה להיות לכם גישה לקוד המקור של האפליקציה ולתצורת ה-build.

המרת manifest.yaml ל-service.yaml

צריך להמיר מניפסט של Cloud Foundry ו/או דגלים של cf CLI לקובץ YAML מקביל של הגדרת שירות ב-Cloud Run.

ב-Cloud Run, לכל אפליקציה צריך להיות קובץ YAML נפרד משלה לשירות. כדי להעביר אפליקציה מקובץ המניפסט של Cloud Foundry לקובץ YAML של שירות:

  1. אוספים את המאפיינים שמופיעים בטבלה הבאה עבור האפליקציה. יכול להיות שהגדרות גלובליות של פלטפורמת Cloud Foundry ביטלו מאפיינים שלא שונו ברמת האפליקציה. כדי לקבל את הערכים בפועל, עיינו במסמכי התיעוד שסופקו על ידי מנהלי הפלטפורמה.

    מאפיין של האפליקציה ‫cf דגלים של CLI v6 תיאור
    name ארגומנט אחד (NAME) השם הייחודי של האפליקציה ב-Cloud Foundry.
    command -c פקודה שתופעל ב-/bin/sh או ב-/bin/bash
    disk_quota -k נפח הדיסק שיוקצה לאפליקציה.

    היחידות התקינות הן: M,‏ MB,‏ G,‏ r B

    ברירת מחדל סבירה: 1G

    docker.image --docker-image, -o התמונה שמכילה את האפליקציה שרוצים להפעיל.
    health-check-http-endpoint לא רלוונטי נקודת הקצה (endpoint) שמשמשת לקביעת התקינות של HTTP אם סוג בדיקת התקינות הוא HTTP.

    ברירת מחדל: /

    health-check-invocation-timeout לא רלוונטי הזמן בשניות בין בדיקות תקינות נפרדות שמבוססות על יציאות ו-HTTP.

    ברירת מחדל: 1

    health-check-type --health-check-type, -u סוג בדיקת התקינות שצריך לבצע באפליקציה. הערכים התקינים הם: port,‏ http,‏ none,‏ process.

    ברירת מחדל: port

    instances -i מספר המכונות של האפליקציה ש-Cloud Foundry יריץ.

    ברירת מחדל: 1

    memory -m מגבלת הזיכרון לכל מכונה של האפליקציה.

    היחידות התקינות הן: M,‏ MB,‏ G או GB

    ברירת מחדל סבירה: 1G

    timeout -t מספר השניות המותרות בין הפעלת האפליקציה לבין בדיקת התקינות הראשונה.

    ברירת המחדל הסבירה: 60

  2. אוספים את הפרטים הבאים על הפרויקט ב- Google Cloud ועל ההגדרה של Cloud Run:

    מאפיין (property) תיאור
    project_number מספר הפרויקט בענן של Google Cloud שבו רוצים לפרוס.
    region האזור שבו רוצים לפרוס את האפליקציה.
    vpc-access-connector שם מחבר ה-VPC שהאדמין של הפלטפורמה רוצה שהאפליקציות יהיו בו.
    vpc-access-egress שם תעבורת הנתונים היוצאת של ה-VPC שמנהל הפלטפורמה רוצה שהאפליקציות יהיו בו.
    custom-audiences קהלים בהתאמה אישית שיכולים לבצע אימות באפליקציה.
    serviceAccountName הזהות שהאפליקציה תפעל בשמה ב-Google Cloud.
    image קובץ האימג' של האפליקציה שיצרתם בשלב הקודם.
  3. ממלאים את התבנית הבאה בקובץ service.yaml בתיקיית הבסיס של הפרויקט.

apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  # Set this to be the name of your app
  name: "APP_NAME"
  # Set this to be the project number of the project you're deploying to.
  namespace: "PROJECT_NUMBER"
  labels:
    # Set this to be the region you're deploying in.
    cloud.googleapis.com/location: REGION
    migrated-from: cloud-foundry
  annotations:
    run.googleapis.com/ingress: internal-and-cloud-load-balancing
spec:
  template:
    metadata:
      annotations:
        # Set to the greater of 1 or the `instances` attribute.
        autoscaling.knative.dev/minScale: '1'
        # Set to the greater of 1 or the `instances` attribute.
        autoscaling.knative.dev/maxScale: '1'
        run.googleapis.com/cpu-throttling: CPU_ALLOCATION
        run.googleapis.com/startup-cpu-boost: 'true'
        # Set to true if you rely on sticky sessions. These will be turned
        # on in Cloud Foundry if the server sends a JSESSIONID cookie back
        # on responses.
        run.googleapis.com/sessionAffinity: 'false'
        run.googleapis.com/execution-environment: gen2
        # Set the following values to match what your platform administrator recommends.
        run.googleapis.com/vpc-access-connector: ADMINISTRATOR_PROVIDED
        run.googleapis.com/vpc-access-egress: ADMINISTRATOR_PROVIDED
        run.googleapis.com/custom-audiences: ADMINISTRATOR_PROVIDED
    spec:
      # CF doesn't limit, but CR has a max of 1000.
      containerConcurrency: 1000
      # Default value for gorouter in PCF.
      timeoutSeconds: 900
      # Set the following value to match what your platform administrator recommends.
      serviceAccountName: ADMINISTRATOR_PROVIDED
      containers:
      - name: user-container
        # Set the following value to either:
        # - The image you built for your application in the last section of the guide.
        # - The docker.image attribute of your app's configuration if it's a Docker app.
        image: IMAGE
        # Set `command` based on the following rules:
        # - If your app has no `command` attribute: null.
        # - If your app has a docker.image attribute: ['/bin/sh', '-c']
        # - Otherwise: ['/bin/bash', '-c']
        command: null
        # Set `args` based on the following rules:
        # - If your app has no `command` attribute: null.
        # - If your app has a `command` attribute: ['value of command']
        args: null
        ports:
          # Set name based on the following rules:
          # - If your app is HTTP/2 or gRPC: "h2c"
          # - Else: "http1"
        - name: HTTP1_OR_H2C
          containerPort: 8080
        env:
          # For each key/value pair in your space's running environment variable groups,
          # which can be retried by running `cf running-environment-variable-group`,
          # add the following:
        - name: KEY
          value: VALUE
          # For each key/value pair in your manifest's `env` map, add the following:
        - name: KEY
          value: VALUE
          # Populate MEMORY_LIMIT with the amount of memory supplied to this instance
          # in MiB with 'M' as a suffix.
        - name: MEMORY_LIMIT
          value: '0M'
          # Set the following values in the JSON below:
          # - `application_name` and `name` to match metadata.name in this file.
          # - `application_uris` and `uris` to be the URI you want to assign the app on the
          #    load balancer.
          # - `limits.disk` to be the amount (in MiB) of disk assigned to your app.
          #   The amount will be in the `disk_quota` attribute of the CF manifest, or a
          #   default value for your cluster, typically 1GiB.
          # - `limits.mem` to be the amount (in MiB) of memory assigned to your app.
          #   The amount will be in your `memory` attribute of the CF manifest, or a
          #   default value for your cluster, typically 1GiB.
          # - `space_name` to be the value of metadata.space in this file.
        - name: VCAP_APPLICATION
          value: |-
                  {
                    "application_id": "00000000-0000-0000-0000-000000000000",
                    "application_name": "app-name",
                    "application_uris": [],
                    "limits": {
                      "disk": 1024,
                      "mem": 256
                    },
                    "name": "app-name",
                    "process_id": "00000000-0000-0000-0000-000000000000",
                    "process_type": "web",
                    "space_name": "none",
                    "uris": []
                  }
        resources:
          limits:
            # Set memory limit to be the sum of the memory and disk assigned to your app in CF.
            # 
            # Disk amount will be in the `disk_quota` attribute of the CF manifest, or a
            # default value for your cluster, typically 1GiB.
            #
            # Memory will be in your `memory` attribute of the CF manifest, or a
            # default value for your cluster, typically 1GiB.
            memory: MEMORY_LIMIT
            # Set cpu according to the following calculation:
            #
            # 1. Take the amount of memory in your `memory` attribute of the CF
            #    manifest, or a default value for your cluster, typically 1GiB.
            # 2. Divide that by the total amount of memory on the underlying BOSH VM.
            # 3. Multiply that by the total number of CPUs on the BOSH VM.
            # 4. Find the nearest valid value based on the rules in:
            #    https://docs.cloud.google.com/run/docs/configuring/services/cpu#setting
            cpu: CPU_LIMIT
        # If `health-check-type` is "process" or "none", delete the startupProbe section.
        startupProbe:
          # If `health-check-type` is "port" or blank, delete the httpGet section.
          httpGet:
            # Set to be the value of `health-check-http-endpoint` or / if blank.
            path: CHECK_PATH
            port: 8080
          # If `health-check-type` is "http", delete the tcpSocket section.
          tcpSocket:
            port: 8080
          # Set to the value of `health-check-invocation-timeout` or 1
          timeoutSeconds: 1
          # Set failure threshold to be the following calculation:
          #
          # 1. Take the `timeout` from the CF manifest, use 60 if unset.
          # 2. Divide by 2.
          # 3. Round up to the nearest integer.
          failureThreshold: 1
          successThreshold: 1
          periodSeconds: 2
        # If `health-check-type` is "process" or "none", delete the livenessProbe section.
        livenessProbe:
          # If `health-check-type` is "port" or blank, delete the httpGet section.
          httpGet:
            # Set to be the value of `health-check-http-endpoint` or / if blank.
            path: CHECK_PATH
            port: 8080
          # If `health-check-type` is "http", delete the tcpSocket section.
          tcpSocket:
            port: 8080
          # Set to the value of `health-check-invocation-timeout` or 1.
          timeoutSeconds: 1
          failureThreshold: 1
          successThreshold: 1
          periodSeconds: 30
  traffic:
  - percent: 100
    latestRevision: true

צירוף שירותים תומכים

צריך ליצור משתנה סביבה של VCAP_SERVICES כדי לאפשר הזרקת שירות וגילוי על ידי אפליקציית Cloud Foundry, כמו Spring או Steeltoe. צריך לעשות את זה לכל אפליקציה שמעבירים. למידע נוסף, קראו את המאמר Cloud Foundry VCAP_SERVICES.

אם האפליקציה שלכם כבר פועלת ב-Cloud Foundry ואתם רוצים לצרף אותה לאותם שירותים ב-Cloud Run, אתם יכולים להשתמש במשתנה הסביבה הקיים. אחרת, תצטרכו ליצור VCAP_SERVICES חדש.

כדי להגדיר את משתנה הסביבה VCAP_SERVICES:

  1. ב-VCAP_SERVICES קיים:

    1. כדי לקבל את משתנה הסביבה VCAP_SERVICES, מריצים את הפקודה cf env APP_NAME.
    2. אם זה לא עובד:
      1. מתחברים לאפליקציה ב-Cloud Foundry: ‏cf ssh APP_NAME
      2. מריצים את הפקודה env ומקבלים את הפלט של VCAP_SERVICES.
      3. מריצים את הפקודה exit כדי לצאת מסשן ה-SSH.
    3. שומרים את הערך של VCAP_SERVICES בקובץ חדש בשם vcap.json.
  2. אם רוצים להוסיף שירותים או להתחבר לשירותים שונים מאלה שב-Cloud Foundry, צריך ליצור VCAP_SERVICES חדש:

    1. בכלי לעריכת טקסט, יוצרים מפת JSON ריקה {}
    2. לכל שירות שרוצים להוסיף, מבצעים את הפעולות הבאות:
    3. כדי להבין איך הספרייה מזהה את הקישור, עיינו במסמכי התיעוד של הספרייה שבה האפליקציה משתמשת כדי לנתח את VCAP_SERVICES לפי הסוג שאתם רוצים להוסיף.
    4. מוסיפים למפה מפתח עם השם של ספק השירות, אם הוא עדיין לא קיים. בדרך כלל זה משהו כמו mysql,‏ postgresql או elasticsearch. מגדירים את הערך כמערך ריק:
    5. מוסיפים אובייקט למערך עם המאפיינים הבאים:

      1. מטא-נתונים שבדרך כלל לא משמשים לגילוי או לקישור של שירותים:

        • ‫binding_name, מחרוזת שמייצגת את המשאב שמעניק לאפליקציה הרשאות בשירות. זה יכול להיות שם משתמש של מסד נתונים, כלל של חומת אש, שם של חשבון שירות או משהו אחר.
        • ‫instance_name, מחרוזת שמייצגת את השם של השירות התומך. זה יכול להיות השם של מסד הנתונים, ערך אקראי או ערך זקיף (sentinel) לשירות גלובלי.
        • ‫name, binding_name אם הוא קיים, אחרת instance_name. הערך הזה בדרך כלל לא חשוב.
        • ‫label, הערך של המפתח במפה VCAP_SERVICES שהקישור הזה נמצא בתוכה.
        • ‫plan, שם חבילת השירות. לדוגמה: "user-provided",‏ "high-availability".
      2. ערכים שמשמשים לעיתים קרובות לגילוי או לקישור של שירותים:

        • tags רשימת תגים שעוזרת לספריות למצוא שירותים תואמים. לרוב, השם הזה כולל את השם הנפוץ של השירות, למשל mysql ל-MySQL ול-MariaDB,‏ redis ל-Redis או ל-Cloud Memorystore, או postgres למסדי נתונים שתואמים ל-Postgres.
        • ‫credentials אובייקט שמכיל את פרטי הכניסה שבהם ספריית הלקוח משתמשת כדי לבצע את החיבור. רוב ספריות הלקוח מסתמכות על שדה uri שמכיל את ה-URI הרגיל של השירות או את פורמט ה-JDBC.
    6. שומרים את התוכן בשם vcap.json.

צירוף פרטי כניסה למשאב ב-Cloud Run

כדי לצרף פרטי כניסה:

  1. יוצרים סוד שיכיל את התוכן של משתנה הסביבה VCAP_SERVICES, ורושמים את הגרסה שהפקודה מחזירה:

    gcloud secrets create APP_NAME-vcap \
      --replication-policy="automatic" \
      --data-file=vcap.json
    
  2. נותנים לחשבון השירות של האפליקציה הרשאה לקרוא את הסוד:

    gcloud secrets add-iam-policy-binding APP_NAME-vcap \
      --member="serviceaccount:app-service-account" \
      --role="roles/secretmanager.secretAccessor"
    
  3. מוסיפים את משתנה הסביבה הבא לאפליקציה service.yaml ב-spec.template.spec.containers[0].env array :

    - name: VCAP_SERVICES
      valueFrom: 
        secretKeyRef:
          key: Version output by step 1
          name: APP_NAME-vcap
    

תבניות לשירותים תומכים נפוצים

בקטעים הבאים מפורט מידע על שירותים תומכים נפוצים

MySQL

ספריות MySQL בדרך כלל מצפות לתג mysql. מקובל לכלול את המפתחות הבאים ב-credentials:

  • תבנית uri: mysql://username:password@host:port/dbname. במסמכי התיעוד של MySQL מוסבר איך ליצור מחרוזת URI. היציאה היא בדרך כלל 3306.
  • ‫username שם המשתמש של החיבור, שנדרש על ידי ספריות מסוימות גם אם הוא נכלל ב-uri
  • password סיסמת החיבור, שנדרשת על ידי ספריות מסוימות גם אם היא כלולה ב-uri

Redis

ספריות Redis בדרך כלל מצפות לתג redis. בדרך כלל כוללים את המפתחות הבאים ב-credentials:

  • uri תבנית: redis://:password@host:port/dbunumber.

המסמכים של IANA בנושא Redis URI יכולים לעזור לכם ליצור מחרוזת URI. היציאה היא בדרך כלל 6379.

RabbitMQ

בדרך כלל, ספריות RabbitMQ מצפות לתג rabbitmq ולמפתחות הבאים ב-credentials:

  • uri תבנית: amqp://username:password@host:port/vhost?query.

במסמכי התיעוד של RabbitMQ מוסבר איך ליצור מחרוזת URI. היציאה היא בדרך כלל 5672.

שירותים שהמשתמשים מספקים

שירותים שסופקו על ידי המשתמש הם סוג מיוחד של שירות ב-Cloud Foundry שמאפשר להזין כל פרטי כניסה. התווית היא תמיד user-provided. התגים הם הערכים שמועברים אל cf create-user-provided-service באמצעות הדגל -t, ופרטי הכניסה הם התוכן של הדגל -p.

פריסת האפליקציה

כדי לפרוס את האפליקציה שהועברה במלואה מ-Cloud Foundry לשירות Cloud Run:

  1. אם עדיין לא עשיתם זאת, הגדירו את סביבת Cloud Run.

  2. מריצים את הפקודה

    gcloud run services replace service.yaml
    

    מחכים כמה רגעים עד שהפריסה תסתיים. אם הפעולה מצליחה, כתובת ה-URL של השירות מוצגת בשורת הפקודה.

  3. כדי להיכנס לשירות שפרסתם, פותחים את כתובת ה-URL של השירות בדפדפן אינטרנט.

כל הכבוד! העברתם את האפליקציה שלכם מ-Cloud Foundry ל-Cloud Run.