hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 0, "code_window": [ " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/arm64/docker-compose.yml", "type": "replace", "edit_start_line_idx": 99 }
version: '3.5' # Example Docker Compose config file for PhotoPrism (Windows / AMD64) # # Note: # - Running PhotoPrism on a server with less than 4 GB of swap space or setting a memory/swap limit can cause unexpected # restarts ("crashes"), for example, when the indexer temporarily needs more memory to process large files. # - Windows Pro users should disable the WSL 2 based engine in Docker Settings > General so that # they can mount drives other than C:. This will enable Hyper-V, which Microsoft doesn't offer # to its Windows Home customers. Docker Desktop uses dynamic memory allocation with WSL 2. # It's important to explicitly increase the Docker memory limit to 4 GB or more when using Hyper-V. # The default of 2 GB may reduce indexing performance and cause unexpected restarts. # - If you install PhotoPrism on a public server outside your home network, please always run it behind a secure # HTTPS reverse proxy such as Traefik or Caddy. Your files and passwords will otherwise be transmitted # in clear text and can be intercepted by anyone, including your provider, hackers, and governments: # https://docs.photoprism.app/getting-started/proxies/traefik/ # # Documentation : https://docs.photoprism.app/getting-started/docker-compose/ # Docker Hub URL: https://hub.docker.com/r/photoprism/photoprism/ # # DOCKER COMPOSE COMMAND REFERENCE # see https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index services: photoprism: ## Use photoprism/photoprism:preview for testing preview builds: image: photoprism/photoprism:latest depends_on: - mariadb ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors # restart: unless-stopped security_opt: - seccomp:unconfined - apparmor:unconfined ports: - "2342:2342" # HTTP port (host:container) environment: PHOTOPRISM_ADMIN_PASSWORD: "insecure" # !!! PLEASE CHANGE YOUR INITIAL "admin" PASSWORD !!! PHOTOPRISM_SITE_URL: "http://localhost:2342/" # public server URL incl http:// or https:// and /path, :port is optional PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "gzip" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_DEBUG: "false" # run in debug mode, shows additional log messages PHOTOPRISM_PUBLIC: "false" # no authentication required, disables password protection PHOTOPRISM_READONLY: "false" # do not modify originals folder; disables import, upload, and delete PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables settings UI and API PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive (requires TensorFlow) PHOTOPRISM_UPLOAD_NSFW: "true" # allows uploads that MAY be offensive PHOTOPRISM_DATABASE_DRIVER: "mysql" # use MariaDB 10.5+ or MySQL 8+ instead of SQLite for improved performance PHOTOPRISM_DATABASE_SERVER: "mariadb:3306" # MariaDB or MySQL database server hostname (:port is optional) PHOTOPRISM_DATABASE_NAME: "photoprism" # MariaDB or MySQL database schema name PHOTOPRISM_DATABASE_USER: "photoprism" # MariaDB or MySQL database user name PHOTOPRISM_DATABASE_PASSWORD: "insecure" # MariaDB or MySQL database user password PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" HOME: "/photoprism" working_dir: "/photoprism" ## Storage Folders: use "/" not "\" as separator, "~" is a shortcut for C:/user/{username}, "." for the current directory volumes: # "C:/user/username/folder:/photoprism/folder" # example - "~/Pictures:/photoprism/originals" # original media files (photos and videos) # - "D:/example/family:/photoprism/originals/family" # *additional* media folders can be mounted like this # - "E:/:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) ## Database Server (recommended) ## see https://docs.photoprism.app/getting-started/faq/#should-i-use-sqlite-mariadb-or-mysql mariadb: ## If MariaDB gets stuck in a restart loop, this points to a memory or filesystem issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors restart: unless-stopped image: mariadb:10.7 security_opt: - seccomp:unconfined - apparmor:unconfined ## --lower-case-table-names=1 stores tables in lowercase and compares names in a case-insensitive manner ## see https://mariadb.com/kb/en/server-system-variables/#lower_case_table_names command: mysqld --innodb-buffer-pool-size=128M --lower-case-table-names=1 --transaction-isolation=READ-COMMITTED --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --max-connections=512 --innodb-rollback-on-timeout=OFF --innodb-lock-wait-timeout=120 volumes: - "database:/var/lib/mysql" # important, do not remove; named volume "database" is defined at the bottom environment: MARIADB_AUTO_UPGRADE: "1" MARIADB_INITDB_SKIP_TZINFO: "1" MARIADB_DATABASE: "photoprism" MARIADB_USER: "photoprism" MARIADB_PASSWORD: "insecure" MARIADB_ROOT_PASSWORD: "insecure" ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower # # watchtower: # restart: unless-stopped # image: containrrr/watchtower # environment: # WATCHTOWER_CLEANUP: "true" # WATCHTOWER_POLL_INTERVAL: 7200 # checks for updates every two hours # volumes: # - "/var/run/docker.sock:/var/run/docker.sock" # - "~/.docker/config.json:/config.json" # optional, for authentication if you have a Docker Hub account ## Create named volumes, advanced users may remove this if they mount a regular host folder ## for the database or use SQLite instead (never remove otherwise) volumes: database: driver: local
docker/examples/windows/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.3662495017051697, 0.055764175951480865, 0.0001629540929570794, 0.007842342369258404, 0.10671042650938034 ]
{ "id": 0, "code_window": [ " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/arm64/docker-compose.yml", "type": "replace", "edit_start_line_idx": 99 }
package sanitize import ( "regexp" "strings" ) // spaced returns the string padded with a space left and right. func spaced(s string) string { return Space + s + Space } // replace performs a case-insensitive string replacement. func replace(subject string, search string, replace string) string { return regexp.MustCompile("(?i)"+search).ReplaceAllString(subject, replace) } // SearchString replaces search operator with default symbols. func SearchString(s string) string { if s == "" || reject(s, MaxLength) { return Empty } // Normalize. s = strings.ReplaceAll(s, "%%", "%") s = strings.ReplaceAll(s, "%", "*") s = strings.ReplaceAll(s, "**", "*") // Trim. return strings.Trim(s, "|\\<>\n\r\t") } // SearchQuery replaces search operator with default symbols. func SearchQuery(s string) string { if s == "" || reject(s, MaxLength) { return Empty } // Normalize. s = replace(s, spaced(EnOr), Or) s = replace(s, spaced(EnOr), Or) s = replace(s, spaced(EnAnd), And) s = replace(s, spaced(EnWith), And) s = replace(s, spaced(EnIn), And) s = replace(s, spaced(EnAt), And) s = strings.ReplaceAll(s, SpacedPlus, And) s = strings.ReplaceAll(s, "%%", "%") s = strings.ReplaceAll(s, "%", "*") s = strings.ReplaceAll(s, "**", "*") // Trim. return strings.Trim(s, "|${}\\<>: \n\r\t") }
pkg/sanitize/search.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00017282794578932226, 0.00016912887804210186, 0.00016310706268996, 0.00017000132356770337, 0.0000035374653180042515 ]
{ "id": 0, "code_window": [ " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/arm64/docker-compose.yml", "type": "replace", "edit_start_line_idx": 99 }
#!/bin/bash PATH="/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/scripts" # abort if not executed as root if [[ $(id -u) != "0" ]]; then echo "Usage: run ${0##*/} as root" 1>&2 exit 1 fi # fail on errors set -eu # disable user interactions export DEBIAN_FRONTEND="noninteractive" export TMPDIR="/tmp" apt-get -y update apt-get -y dist-upgrade apt-get -y autoremove echo "Done."
scripts/dist/dist-upgrade.sh
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0003075013810303062, 0.00021446200844366103, 0.00016516950563527644, 0.00017071512411348522, 0.00006582772039109841 ]
{ "id": 0, "code_window": [ " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/arm64/docker-compose.yml", "type": "replace", "edit_start_line_idx": 99 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path d="M14 325.3c2.3-4.2 5.2-4.9 9.7-2.5 10.4 5.6 20.6 11.4 31.2 16.7a595.88 595.88 0 00127.4 46.3 616.61 616.61 0 0063.2 11.8 603.33 603.33 0 0095 5.2c17.4-.4 34.8-1.8 52.1-3.8a603.66 603.66 0 00163.3-42.8c2.9-1.2 5.9-2 9.1-1.2 6.7 1.8 9 9 4.1 13.9a70 70 0 01-9.6 7.4c-30.7 21.1-64.2 36.4-99.6 47.9a473.31 473.31 0 01-75.1 17.6 431 431 0 01-53.2 4.8 21.3 21.3 0 00-2.5.3H308a21.3 21.3 0 00-2.5-.3c-3.6-.2-7.2-.3-10.7-.4a426.3 426.3 0 01-50.4-5.3A448.4 448.4 0 01164 420a443.33 443.33 0 01-145.6-87c-1.8-1.6-3-3.8-4.4-5.7zM172 65.1l-4.3.6a80.92 80.92 0 00-38 15.1c-2.4 1.7-4.6 3.5-7.1 5.4a4.29 4.29 0 01-.4-1.4c-.4-2.7-.8-5.5-1.3-8.2-.7-4.6-3-6.6-7.6-6.6h-11.5c-6.9 0-8.2 1.3-8.2 8.2v209.3c0 1 0 2 .1 3 .2 3 2 4.9 4.9 5 7 .1 14.1.1 21.1 0 2.9 0 4.7-2 5-5 .1-1 .1-2 .1-3v-72.4c1.1.9 1.7 1.4 2.2 1.9 17.9 14.9 38.5 19.8 61 15.4 20.4-4 34.6-16.5 43.8-34.9 7-13.9 9.9-28.7 10.3-44.1.5-17.1-1.2-33.9-8.1-49.8-8.5-19.6-22.6-32.5-43.9-36.9-3.2-.7-6.5-1-9.8-1.5-2.8-.1-5.5-.1-8.3-.1zM124.6 107a3.48 3.48 0 011.7-3.3c13.7-9.5 28.8-14.5 45.6-13.2 14.9 1.1 27.1 8.4 33.5 25.9 3.9 10.7 4.9 21.8 4.9 33 0 10.4-.8 20.6-4 30.6-6.8 21.3-22.4 29.4-42.6 28.5-14-.6-26.2-6-37.4-13.9a3.57 3.57 0 01-1.7-3.3c.1-14.1 0-28.1 0-42.2s.1-28 0-42.1zm205.7-41.9c-1 .1-2 .3-2.9.4a148 148 0 00-28.9 4.1c-6.1 1.6-12 3.8-17.9 5.8-3.6 1.2-5.4 3.8-5.3 7.7.1 3.3-.1 6.6 0 9.9.1 4.8 2.1 6.1 6.8 4.9 7.8-2 15.6-4.2 23.5-5.7 12.3-2.3 24.7-3.3 37.2-1.4 6.5 1 12.6 2.9 16.8 8.4 3.7 4.8 5.1 10.5 5.3 16.4.3 8.3.2 16.6.3 24.9a7.84 7.84 0 01-.2 1.4c-.5-.1-.9 0-1.3-.1a180.56 180.56 0 00-32-4.9c-11.3-.6-22.5.1-33.3 3.9-12.9 4.5-23.3 12.3-29.4 24.9-4.7 9.8-5.4 20.2-3.9 30.7 2 14 9 24.8 21.4 31.7 11.9 6.6 24.8 7.4 37.9 5.4 15.1-2.3 28.5-8.7 40.3-18.4a7.36 7.36 0 011.6-1.1c.6 3.8 1.1 7.4 1.8 11 .6 3.1 2.5 5.1 5.4 5.2 5.4.1 10.9.1 16.3 0a4.84 4.84 0 004.8-4.7 26.2 26.2 0 00.1-2.8v-106a80 80 0 00-.9-12.9c-1.9-12.9-7.4-23.5-19-30.4-6.7-4-14.1-6-21.8-7.1-3.6-.5-7.2-.8-10.8-1.3-3.9.1-7.9.1-11.9.1zm35 127.7a3.33 3.33 0 01-1.5 3c-11.2 8.1-23.5 13.5-37.4 14.9-5.7.6-11.4.4-16.8-1.8a20.08 20.08 0 01-12.4-13.3 32.9 32.9 0 01-.1-19.4c2.5-8.3 8.4-13 16.4-15.6a61.33 61.33 0 0124.8-2.2c8.4.7 16.6 2.3 25 3.4 1.6.2 2.1 1 2.1 2.6-.1 4.8 0 9.5 0 14.3s-.2 9.4-.1 14.1zm259.9 129.4c-1-5-4.8-6.9-9.1-8.3a88.42 88.42 0 00-21-3.9 147.32 147.32 0 00-39.2 1.9c-14.3 2.7-27.9 7.3-40 15.6a13.75 13.75 0 00-3.7 3.5 5.11 5.11 0 00-.5 4c.4 1.5 2.1 1.9 3.6 1.8a16.2 16.2 0 002.2-.1c7.8-.8 15.5-1.7 23.3-2.5 11.4-1.1 22.9-1.8 34.3-.9a71.64 71.64 0 0114.4 2.7c5.1 1.4 7.4 5.2 7.6 10.4.4 8-1.4 15.7-3.5 23.3-4.1 15.4-10 30.3-15.8 45.1a17.6 17.6 0 00-1 3c-.5 2.9 1.2 4.8 4.1 4.1a10.56 10.56 0 004.8-2.5 145.91 145.91 0 0012.7-13.4c12.8-16.4 20.3-35.3 24.7-55.6.8-3.6 1.4-7.3 2.1-10.9v-17.3zM493.1 199q-19.35-53.55-38.7-107.2c-2-5.7-4.2-11.3-6.3-16.9-1.1-2.9-3.2-4.8-6.4-4.8-7.6-.1-15.2-.2-22.9-.1-2.5 0-3.7 2-3.2 4.5a43.1 43.1 0 001.9 6.1q29.4 72.75 59.1 145.5c1.7 4.1 2.1 7.6.2 11.8-3.3 7.3-5.9 15-9.3 22.3-3 6.5-8 11.4-15.2 13.3a42.13 42.13 0 01-15.4 1.1c-2.5-.2-5-.8-7.5-1-3.4-.2-5.1 1.3-5.2 4.8q-.15 5 0 9.9c.1 5.5 2 8 7.4 8.9a108.18 108.18 0 0016.9 2c17.1.4 30.7-6.5 39.5-21.4a131.63 131.63 0 009.2-18.4q35.55-89.7 70.6-179.6a26.62 26.62 0 001.6-5.5c.4-2.8-.9-4.4-3.7-4.4-6.6-.1-13.3 0-19.9 0a7.54 7.54 0 00-7.7 5.2c-.5 1.4-1.1 2.7-1.6 4.1l-34.8 100c-2.5 7.2-5.1 14.5-7.7 22.2-.4-1.1-.6-1.7-.9-2.4z"/></svg>
assets/static/brands/amazon-pay.svg
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00046211236622184515, 0.00046211236622184515, 0.00046211236622184515, 0.00046211236622184515, 0 ]
{ "id": 1, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/arm64/docker-compose.yml", "type": "replace", "edit_start_line_idx": 105 }
version: '3.5' # Example Docker Compose config file for PhotoPrism (Linux / AMD64) # Includes Ophelia, a docker job scheduler: https://github.com/mcuadros/ofelia # # Note: # - Running PhotoPrism on a server with less than 4 GB of swap space or setting a memory/swap limit can cause unexpected # restarts ("crashes"), for example, when the indexer temporarily needs more memory to process large files. # - If you install PhotoPrism on a public server outside your home network, please always run it behind a secure # HTTPS reverse proxy such as Traefik or Caddy. Your files and passwords will otherwise be transmitted # in clear text and can be intercepted by anyone, including your provider, hackers, and governments: # https://docs.photoprism.app/getting-started/proxies/traefik/ # # Documentation : https://docs.photoprism.app/getting-started/docker-compose/ # Docker Hub URL: https://hub.docker.com/r/photoprism/photoprism/ # # DOCKER COMPOSE COMMAND REFERENCE # see https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index # # All commands may have to be prefixed with "sudo" when not running as root. # This will point the home directory shortcut ~ to /root in volume mounts. services: photoprism: # Use photoprism/photoprism:preview for testing preview builds: image: photoprism/photoprism:latest container_name: photoprism depends_on: - mariadb ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors # restart: unless-stopped security_opt: - seccomp:unconfined - apparmor:unconfined ports: - "2342:2342" # HTTP port (host:container) environment: PHOTOPRISM_ADMIN_PASSWORD: "insecure" # !!! PLEASE CHANGE YOUR INITIAL "admin" PASSWORD !!! PHOTOPRISM_SITE_URL: "http://localhost:2342/" # public server URL incl http:// or https:// and /path, :port is optional PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "gzip" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_DEBUG: "false" # run in debug mode (shows additional log messages) PHOTOPRISM_PUBLIC: "false" # no authentication required (disables password protection) PHOTOPRISM_READONLY: "false" # do not modify originals directory (reduced functionality) PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables settings UI and API PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive (requires TensorFlow) PHOTOPRISM_UPLOAD_NSFW: "true" # allows uploads that MAY be offensive # PHOTOPRISM_DATABASE_DRIVER: "sqlite" # SQLite is an embedded database that doesn't require a server PHOTOPRISM_DATABASE_DRIVER: "mysql" # use MariaDB 10.5+ or MySQL 8+ instead of SQLite for improved performance PHOTOPRISM_DATABASE_SERVER: "mariadb:3306" # MariaDB or MySQL database server (hostname:port) PHOTOPRISM_DATABASE_NAME: "photoprism" # MariaDB or MySQL database schema name PHOTOPRISM_DATABASE_USER: "photoprism" # MariaDB or MySQL database user name PHOTOPRISM_DATABASE_PASSWORD: "insecure" # MariaDB or MySQL database user password PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clitools, clean): # PHOTOPRISM_INIT: "gpu tensorflow" ## Run as a specific user, group, or with a custom umask (does not work together with "user:") # PHOTOPRISM_UID: 1000 # PHOTOPRISM_GID: 1000 # PHOTOPRISM_UMASK: 0000 HOME: "/photoprism" ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user) # user: "1000:1000" working_dir: "/photoprism" ## Storage Folders: "~" is a shortcut for your home directory, "." for the current directory volumes: # "/host/folder:/photoprism/folder" # example - "~/Pictures:/photoprism/originals" # original media files (photos and videos) # - "/example/family:/photoprism/originals/family" # *additional* media folders can be mounted like this # - "~/Import:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) ## Database Server (recommended) ## see https://docs.photoprism.app/getting-started/faq/#should-i-use-sqlite-mariadb-or-mysql mariadb: restart: unless-stopped image: mariadb:10.7 container_name: mariadb security_opt: - seccomp:unconfined - apparmor:unconfined command: mysqld --innodb-buffer-pool-size=128M --transaction-isolation=READ-COMMITTED --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --max-connections=512 --innodb-rollback-on-timeout=OFF --innodb-lock-wait-timeout=120 ## Never store database files on an unreliable device such as a USB flash drive, an SD card, or a shared network folder: volumes: - "./database:/var/lib/mysql" # important, do not remove environment: MARIADB_AUTO_UPGRADE: "1" MARIADB_INITDB_SKIP_TZINFO: "1" MARIADB_DATABASE: "photoprism" MARIADB_USER: "photoprism" MARIADB_PASSWORD: "insecure" MARIADB_ROOT_PASSWORD: "insecure" ## Ofelia Job Runner (recommended for running background jobs) ## see https://github.com/mcuadros/ofelia ofelia: restart: unless-stopped image: mcuadros/ofelia:latest container_name: ofelia volumes: - "/var/run/docker.sock:/var/run/docker.sock:ro" - "./jobs.ini:/etc/ofelia/config.ini" ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower # # watchtower: # restart: unless-stopped # image: containrrr/watchtower # environment: # WATCHTOWER_CLEANUP: "true" # WATCHTOWER_POLL_INTERVAL: 7200 # checks for updates every two hours # volumes: # - "/var/run/docker.sock:/var/run/docker.sock" # - "~/.docker/config.json:/config.json" # optional, for authentication if you have a Docker Hub account
docker/examples/scheduler/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.9475938677787781, 0.06470906734466553, 0.00016258379037026316, 0.0004300685541238636, 0.23598697781562805 ]
{ "id": 1, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/arm64/docker-compose.yml", "type": "replace", "edit_start_line_idx": 105 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M0 32h214.6v214.6H0V32zm233.4 0H448v214.6H233.4V32zM0 265.4h214.6V480H0V265.4zm233.4 0H448V480H233.4V265.4z"/></svg>
assets/static/brands/microsoft.svg
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0001701724686427042, 0.0001701724686427042, 0.0001701724686427042, 0.0001701724686427042, 0 ]
{ "id": 1, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/arm64/docker-compose.yml", "type": "replace", "edit_start_line_idx": 105 }
 Open Sans Semibold 2816-3071
assets/static/font/Open Sans Semibold/2816-3071.pbf
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00016470493574161083, 0.00016470493574161083, 0.00016470493574161083, 0.00016470493574161083, 0 ]
{ "id": 1, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/arm64/docker-compose.yml", "type": "replace", "edit_start_line_idx": 105 }
package api import ( "encoding/json" "net/http" "net/http/httptest" "os" "strings" "testing" "github.com/photoprism/photoprism/internal/form" "github.com/gin-gonic/gin" "github.com/photoprism/photoprism/internal/config" "github.com/photoprism/photoprism/internal/service" "github.com/sirupsen/logrus" ) // NewApiTest returns new API test helper. func NewApiTest() (app *gin.Engine, router *gin.RouterGroup, conf *config.Config) { gin.SetMode(gin.TestMode) app = gin.New() router = app.Group("/api/v1") return app, router, service.Config() } // AuthenticateAdmin Register session routes and returns valid SessionId. // Call this func after registering other routes and before performing other requests. func AuthenticateAdmin(app *gin.Engine, router *gin.RouterGroup) (sessId string) { return AuthenticateUser(app, router, "admin", "photoprism") } // AuthenticateUser Register session routes and returns valid SessionId. // Call this func after registering other routes and before performing other requests. func AuthenticateUser(app *gin.Engine, router *gin.RouterGroup, username string, password string) (sessId string) { CreateSession(router) f := form.Login{ UserName: username, Password: password, } loginStr, err := json.Marshal(f) if err != nil { log.Fatal(err) } r0 := PerformRequestWithBody(app, http.MethodPost, "/api/v1/session", string(loginStr)) sessId = r0.Header().Get("X-Session-ID") return } // Executes an API request with an empty request body. // See https://medium.com/@craigchilds94/testing-gin-json-responses-1f258ce3b0b1 func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder { req, _ := http.NewRequest(method, path, nil) w := httptest.NewRecorder() r.ServeHTTP(w, req) return w } // Performs authenticated API request with empty request body. func AuthenticatedRequest(r http.Handler, method, path, sess string) *httptest.ResponseRecorder { req, _ := http.NewRequest(method, path, nil) req.Header.Add("X-Session-ID", sess) w := httptest.NewRecorder() r.ServeHTTP(w, req) return w } // Executes an API request with the request body as a string. func PerformRequestWithBody(r http.Handler, method, path, body string) *httptest.ResponseRecorder { reader := strings.NewReader(body) req, _ := http.NewRequest(method, path, reader) w := httptest.NewRecorder() r.ServeHTTP(w, req) return w } // Performs an authenticated API request containing the request body as a string. func AuthenticatedRequestWithBody(r http.Handler, method, path, body string, sessionId string) *httptest.ResponseRecorder { reader := strings.NewReader(body) req, _ := http.NewRequest(method, path, reader) req.Header.Add("X-Session-ID", sessionId) w := httptest.NewRecorder() r.ServeHTTP(w, req) return w } func TestMain(m *testing.M) { log = logrus.StandardLogger() log.SetLevel(logrus.TraceLevel) c := config.NewTestConfig("api") service.SetConfig(c) code := m.Run() _ = c.CloseDb() os.Exit(code) }
internal/api/api_test.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0011816786136478186, 0.0003518833254929632, 0.00016059128392953426, 0.0001671202917350456, 0.00037267940933816135 ]
{ "id": 2, "code_window": [ " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/armv7/docker-compose.yml", "type": "replace", "edit_start_line_idx": 92 }
version: '3.5' # Example Docker Compose config file for PhotoPrism (Raspberry Pi 3/4 and other ARM64-based devices) # # Note: # - You have to boot your Raspberry Pi 3/4 with the parameter "arm_64bit=1" in config.txt to use our ARM64 (64-bit) image. # An "exec format" error will occur otherwise. # - Try explicitly pulling the ARM64 version if you've booted your device with the "arm_64bit=1" flag and you see # the "no matching manifest" error on Raspberry Pi OS (Raspbian). See documentation for details. # - Use https://dl.photoprism.app/docker/armv7/docker-compose.yml to run PhotoPrism and MariaDB on ARMv7-based devices # as well as Raspberry Pi OS (Raspbian) installations without 64-bit support. # - Running PhotoPrism on a server with less than 4 GB of swap space or setting a memory/swap limit can cause unexpected # restarts ("crashes"), for example, when the indexer temporarily needs more memory to process large files. # - In case you see Docker errors related to "cgroups", try adding the following parameters to /boot/firmware/cmdline.txt # or /boot/cmdline.txt (file location depends on the OS in use): cgroup_enable=cpuset cgroup_enable=memory cgroup_memory=1 # - If you install PhotoPrism on a public server outside your home network, please always run it behind a secure # HTTPS reverse proxy such as Traefik or Caddy. Your files and passwords will otherwise be transmitted # in clear text and can be intercepted by anyone, including your provider, hackers, and governments: # https://docs.photoprism.app/getting-started/proxies/traefik/ # # Documentation : https://docs.photoprism.app/getting-started/raspberry-pi/ # Docker Hub URL: https://hub.docker.com/r/photoprism/photoprism/ # # DOCKER COMPOSE COMMAND REFERENCE # see https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index # # All commands may have to be prefixed with "sudo" when not running as root. # This will point the home directory shortcut ~ to /root in volume mounts. services: photoprism: ## Use photoprism/photoprism:preview-arm64 for testing preview builds: image: photoprism/photoprism:arm64 depends_on: - mariadb ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors # restart: unless-stopped security_opt: - seccomp:unconfined - apparmor:unconfined ports: - "2342:2342" # HTTP port (host:container) environment: PHOTOPRISM_ADMIN_PASSWORD: "insecure" # !!! PLEASE CHANGE YOUR INITIAL "admin" PASSWORD !!! PHOTOPRISM_SITE_URL: "http://localhost:2342/" # public server URL incl http:// or https:// and /path, :port is optional PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "none" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_WORKERS: 2 # limits the number of indexing workers to reduce system load PHOTOPRISM_DEBUG: "false" # run in debug mode (shows additional log messages) PHOTOPRISM_PUBLIC: "false" # no authentication required (disables password protection) PHOTOPRISM_READONLY: "false" # do not modify originals directory (reduced functionality) PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables Settings in Web UI PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) # PHOTOPRISM_FFMPEG_ENCODER: "h264_v4l2m2m" # FFmpeg AVC encoder for video transcoding (default: libx264) # PHOTOPRISM_FFMPEG_BUFFERS: "64" # FFmpeg capture buffers (default: 32) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive PHOTOPRISM_UPLOAD_NSFW: "true" # allow uploads that MAY be offensive # PHOTOPRISM_DATABASE_DRIVER: "sqlite" # SQLite is an embedded database that doesn't require a server PHOTOPRISM_DATABASE_DRIVER: "mysql" # use MariaDB 10.5+ or MySQL 8+ instead of SQLite for improved performance PHOTOPRISM_DATABASE_SERVER: "mariadb:3306" # MariaDB or MySQL database server (hostname:port) PHOTOPRISM_DATABASE_NAME: "photoprism" # MariaDB or MySQL database schema name PHOTOPRISM_DATABASE_USER: "photoprism" # MariaDB or MySQL database user name PHOTOPRISM_DATABASE_PASSWORD: "insecure" # MariaDB or MySQL database user password PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clean): # PHOTOPRISM_INIT: "update clean" ## Run as a specific user, group, or with a custom umask (does not work together with "user:") # PHOTOPRISM_UID: 1000 # PHOTOPRISM_GID: 1000 # PHOTOPRISM_UMASK: 0000 HOME: "/photoprism" ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user) # user: "1000:1000" ## Share hardware devices with FFmpeg and TensorFlow (optional): # devices: # - "/dev/video11:/dev/video11" # Video4Linux (h264_v4l2m2m) working_dir: "/photoprism" ## Storage Folders: "~" is a shortcut for your home directory, "." for the current directory volumes: # "/host/folder:/photoprism/folder" # example - "~/Pictures:/photoprism/originals" # original media files (photos and videos) # - "/example/family:/photoprism/originals/family" # *additional* media folders can be mounted like this # - "~/Import:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) ## Database Server (recommended) ## see https://docs.photoprism.app/getting-started/faq/#should-i-use-sqlite-mariadb-or-mysql mariadb: ## If MariaDB gets stuck in a restart loop, this points to a memory or filesystem issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors restart: unless-stopped image: arm64v8/mariadb:10.7 # this mariadb image runs on ARM64-based devices only security_opt: - seccomp:unconfined - apparmor:unconfined command: mysqld --innodb-buffer-pool-size=128M --transaction-isolation=READ-COMMITTED --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --max-connections=512 --innodb-rollback-on-timeout=OFF --innodb-lock-wait-timeout=120 ## Never store database files on an unreliable device such as a USB flash drive, an SD card, or a shared network folder: volumes: - "./database:/var/lib/mysql" # important, do not remove environment: MARIADB_AUTO_UPGRADE: "1" MARIADB_INITDB_SKIP_TZINFO: "1" MARIADB_DATABASE: "photoprism" MARIADB_USER: "photoprism" MARIADB_PASSWORD: "insecure" MARIADB_ROOT_PASSWORD: "insecure" ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower # # watchtower: # restart: unless-stopped # image: containrrr/watchtower # environment: # WATCHTOWER_CLEANUP: "true" # WATCHTOWER_POLL_INTERVAL: 7200 # checks for updates every two hours # volumes: # - "/var/run/docker.sock:/var/run/docker.sock" # - "~/.docker/config.json:/config.json" # optional, for authentication if you have a Docker Hub account
docker/examples/arm64/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.4902443289756775, 0.07478730380535126, 0.00018179125618189573, 0.002228948287665844, 0.14169777929782867 ]
{ "id": 2, "code_window": [ " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/armv7/docker-compose.yml", "type": "replace", "edit_start_line_idx": 92 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M224 122.8c-72.7 0-131.8 59.1-131.9 131.8 0 24.9 7 49.2 20.2 70.1l3.1 5-13.3 48.6 49.9-13.1 4.8 2.9c20.2 12 43.4 18.4 67.1 18.4h.1c72.6 0 133.3-59.1 133.3-131.8 0-35.2-15.2-68.3-40.1-93.2-25-25-58-38.7-93.2-38.7zm77.5 188.4c-3.3 9.3-19.1 17.7-26.7 18.8-12.6 1.9-22.4.9-47.5-9.9-39.7-17.2-65.7-57.2-67.7-59.8-2-2.6-16.2-21.5-16.2-41s10.2-29.1 13.9-33.1c3.6-4 7.9-5 10.6-5 2.6 0 5.3 0 7.6.1 2.4.1 5.7-.9 8.9 6.8 3.3 7.9 11.2 27.4 12.2 29.4s1.7 4.3.3 6.9c-7.6 15.2-15.7 14.6-11.6 21.6 15.3 26.3 30.6 35.4 53.9 47.1 4 2 6.3 1.7 8.6-1 2.3-2.6 9.9-11.6 12.5-15.5 2.6-4 5.3-3.3 8.9-2 3.6 1.3 23.1 10.9 27.1 12.9s6.6 3 7.6 4.6c.9 1.9.9 9.9-2.4 19.1zM400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zM223.9 413.2c-26.6 0-52.7-6.7-75.8-19.3L64 416l22.5-82.2c-13.9-24-21.2-51.3-21.2-79.3C65.4 167.1 136.5 96 223.9 96c42.4 0 82.2 16.5 112.2 46.5 29.9 30 47.9 69.8 47.9 112.2 0 87.4-72.7 158.5-160.1 158.5z"/></svg>
assets/static/brands/whatsapp-square.svg
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.002819906920194626, 0.002819906920194626, 0.002819906920194626, 0.002819906920194626, 0 ]
{ "id": 2, "code_window": [ " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/armv7/docker-compose.yml", "type": "replace", "edit_start_line_idx": 92 }
package query import ( "github.com/photoprism/photoprism/internal/entity" ) type Cell struct { ID string PlaceID string } type Cells []Cell // CellIDs returns all known S2 cell ids as Cell slice. func CellIDs() (result Cells, err error) { tableName := entity.Cell{}.TableName() var count int64 if err = UnscopedDb().Table(tableName).Where("id <> 'zz'").Count(&count).Error; err != nil { return result, err } result = make(Cells, 0, count) err = UnscopedDb().Table(tableName).Select("id, place_id").Where("id <> 'zz'").Order("id").Scan(&result).Error return result, err } // PurgePlaces removes unused entries from the places table. func PurgePlaces() error { query := "DELETE FROM places WHERE id NOT IN (SELECT DISTINCT place_id FROM cells)" + " AND id NOT IN (SELECT DISTINCT place_id FROM photos)" return Db().Exec(query).Error }
internal/query/places.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.003664258634671569, 0.00104197533801198, 0.00016342668095603585, 0.00017010790179483593, 0.001513978815637529 ]
{ "id": 2, "code_window": [ " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/armv7/docker-compose.yml", "type": "replace", "edit_start_line_idx": 92 }
package search import ( "testing" "github.com/photoprism/photoprism/internal/form" "github.com/stretchr/testify/assert" ) func TestPhotosQueryRaw(t *testing.T) { var f0 form.SearchPhotos f0.Query = "raw:true" f0.Merged = true photos0, _, err := Photos(f0) if err != nil { t.Fatal(err) } assert.GreaterOrEqual(t, len(photos0), 1) t.Run("StartsWithPercent", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"%gold\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterPercent", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"I love % dog\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithPercent", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"sale%\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("StartsWithAmpersand", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"&IlikeFood\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterAmpersand", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"Pets & Dogs\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithAmpersand", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"Light&\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("StartsWithSingleQuote", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"'Family\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterSingleQuote", func(t *testing.T) { var f form.SearchPhotos // Note: If the string in raw starts with f/F, the txt package will assume it means false, f.Query = "raw:\"Mother's Day\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithSingleQuote", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"Ice Cream'\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("StartsWithAsterisk", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"*Forrest\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterAsterisk", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"My*Kids\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithAsterisk", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"Yoga***\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("StartsWithPipe", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"|Banana\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterPipe", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"Red|Green\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithPipe", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"Blue|\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("StartsWithNumber", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"345 Shirt\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterNumber", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"Color555 Blue\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithNumber", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"Route 66\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("AndSearch", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"Route 66 & Father's Day\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("OrSearch", func(t *testing.T) { var f form.SearchPhotos f.Query = "raw:\"Route %66 | *Father's Day\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) }
internal/search/photos_filter_raw_test.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0031125142704695463, 0.0002701127086766064, 0.0001662580471020192, 0.0001725470065139234, 0.0005278259050101042 ]
{ "id": 3, "code_window": [ " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/armv7/docker-compose.yml", "type": "replace", "edit_start_line_idx": 98 }
version: '3.5' # Example Docker Compose config file for PhotoPrism (Raspberry Pi 3/4 and other ARM64-based devices) # # Note: # - You have to boot your Raspberry Pi 3/4 with the parameter "arm_64bit=1" in config.txt to use our ARM64 (64-bit) image. # An "exec format" error will occur otherwise. # - Try explicitly pulling the ARM64 version if you've booted your device with the "arm_64bit=1" flag and you see # the "no matching manifest" error on Raspberry Pi OS (Raspbian). See documentation for details. # - Use https://dl.photoprism.app/docker/armv7/docker-compose.yml to run PhotoPrism and MariaDB on ARMv7-based devices # as well as Raspberry Pi OS (Raspbian) installations without 64-bit support. # - Running PhotoPrism on a server with less than 4 GB of swap space or setting a memory/swap limit can cause unexpected # restarts ("crashes"), for example, when the indexer temporarily needs more memory to process large files. # - In case you see Docker errors related to "cgroups", try adding the following parameters to /boot/firmware/cmdline.txt # or /boot/cmdline.txt (file location depends on the OS in use): cgroup_enable=cpuset cgroup_enable=memory cgroup_memory=1 # - If you install PhotoPrism on a public server outside your home network, please always run it behind a secure # HTTPS reverse proxy such as Traefik or Caddy. Your files and passwords will otherwise be transmitted # in clear text and can be intercepted by anyone, including your provider, hackers, and governments: # https://docs.photoprism.app/getting-started/proxies/traefik/ # # Documentation : https://docs.photoprism.app/getting-started/raspberry-pi/ # Docker Hub URL: https://hub.docker.com/r/photoprism/photoprism/ # # DOCKER COMPOSE COMMAND REFERENCE # see https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index # # All commands may have to be prefixed with "sudo" when not running as root. # This will point the home directory shortcut ~ to /root in volume mounts. services: photoprism: ## Use photoprism/photoprism:preview-arm64 for testing preview builds: image: photoprism/photoprism:arm64 depends_on: - mariadb ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors # restart: unless-stopped security_opt: - seccomp:unconfined - apparmor:unconfined ports: - "2342:2342" # HTTP port (host:container) environment: PHOTOPRISM_ADMIN_PASSWORD: "insecure" # !!! PLEASE CHANGE YOUR INITIAL "admin" PASSWORD !!! PHOTOPRISM_SITE_URL: "http://localhost:2342/" # public server URL incl http:// or https:// and /path, :port is optional PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "none" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_WORKERS: 2 # limits the number of indexing workers to reduce system load PHOTOPRISM_DEBUG: "false" # run in debug mode (shows additional log messages) PHOTOPRISM_PUBLIC: "false" # no authentication required (disables password protection) PHOTOPRISM_READONLY: "false" # do not modify originals directory (reduced functionality) PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables Settings in Web UI PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) # PHOTOPRISM_FFMPEG_ENCODER: "h264_v4l2m2m" # FFmpeg AVC encoder for video transcoding (default: libx264) # PHOTOPRISM_FFMPEG_BUFFERS: "64" # FFmpeg capture buffers (default: 32) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive PHOTOPRISM_UPLOAD_NSFW: "true" # allow uploads that MAY be offensive # PHOTOPRISM_DATABASE_DRIVER: "sqlite" # SQLite is an embedded database that doesn't require a server PHOTOPRISM_DATABASE_DRIVER: "mysql" # use MariaDB 10.5+ or MySQL 8+ instead of SQLite for improved performance PHOTOPRISM_DATABASE_SERVER: "mariadb:3306" # MariaDB or MySQL database server (hostname:port) PHOTOPRISM_DATABASE_NAME: "photoprism" # MariaDB or MySQL database schema name PHOTOPRISM_DATABASE_USER: "photoprism" # MariaDB or MySQL database user name PHOTOPRISM_DATABASE_PASSWORD: "insecure" # MariaDB or MySQL database user password PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clean): # PHOTOPRISM_INIT: "update clean" ## Run as a specific user, group, or with a custom umask (does not work together with "user:") # PHOTOPRISM_UID: 1000 # PHOTOPRISM_GID: 1000 # PHOTOPRISM_UMASK: 0000 HOME: "/photoprism" ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user) # user: "1000:1000" ## Share hardware devices with FFmpeg and TensorFlow (optional): # devices: # - "/dev/video11:/dev/video11" # Video4Linux (h264_v4l2m2m) working_dir: "/photoprism" ## Storage Folders: "~" is a shortcut for your home directory, "." for the current directory volumes: # "/host/folder:/photoprism/folder" # example - "~/Pictures:/photoprism/originals" # original media files (photos and videos) # - "/example/family:/photoprism/originals/family" # *additional* media folders can be mounted like this # - "~/Import:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) ## Database Server (recommended) ## see https://docs.photoprism.app/getting-started/faq/#should-i-use-sqlite-mariadb-or-mysql mariadb: ## If MariaDB gets stuck in a restart loop, this points to a memory or filesystem issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors restart: unless-stopped image: arm64v8/mariadb:10.7 # this mariadb image runs on ARM64-based devices only security_opt: - seccomp:unconfined - apparmor:unconfined command: mysqld --innodb-buffer-pool-size=128M --transaction-isolation=READ-COMMITTED --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --max-connections=512 --innodb-rollback-on-timeout=OFF --innodb-lock-wait-timeout=120 ## Never store database files on an unreliable device such as a USB flash drive, an SD card, or a shared network folder: volumes: - "./database:/var/lib/mysql" # important, do not remove environment: MARIADB_AUTO_UPGRADE: "1" MARIADB_INITDB_SKIP_TZINFO: "1" MARIADB_DATABASE: "photoprism" MARIADB_USER: "photoprism" MARIADB_PASSWORD: "insecure" MARIADB_ROOT_PASSWORD: "insecure" ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower # # watchtower: # restart: unless-stopped # image: containrrr/watchtower # environment: # WATCHTOWER_CLEANUP: "true" # WATCHTOWER_POLL_INTERVAL: 7200 # checks for updates every two hours # volumes: # - "/var/run/docker.sock:/var/run/docker.sock" # - "~/.docker/config.json:/config.json" # optional, for authentication if you have a Docker Hub account
docker/examples/arm64/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.9242730736732483, 0.06898345798254013, 0.00016386325296480209, 0.0054412358440458775, 0.2291441708803177 ]
{ "id": 3, "code_window": [ " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/armv7/docker-compose.yml", "type": "replace", "edit_start_line_idx": 98 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M256 32.86L32.86 256 256 479.14 479.14 256 256 32.86zM88.34 255.83c1.96-2 11.92-12.3 96.49-97.48 41.45-41.75 86.19-43.77 119.77-18.69 24.63 18.4 62.06 58.9 62.15 59 .68.74 1.07 2.86.58 3.38-11.27 11.84-22.68 23.54-33.5 34.69-34.21-32.31-40.52-38.24-48.51-43.95-17.77-12.69-41.4-10.13-56.98 5.1-2.17 2.13-1.79 3.43.12 5.35 2.94 2.95 28.1 28.33 35.09 35.78-11.95 11.6-23.66 22.97-35.69 34.66-12.02-12.54-24.48-25.53-36.54-38.11-21.39 21.09-41.69 41.11-61.85 60.99a42569.01 42569.01 0 01-41.13-40.72zm234.82 101.6c-35.49 35.43-78.09 38.14-106.99 20.47-22.08-13.5-39.38-32.08-72.93-66.84 12.05-12.37 23.79-24.42 35.37-36.31 33.02 31.91 37.06 36.01 44.68 42.09 18.48 14.74 42.52 13.67 59.32-1.8 3.68-3.39 3.69-3.64.14-7.24-10.59-10.73-21.19-21.44-31.77-32.18-1.32-1.34-3.03-2.48-.8-4.69 10.79-10.71 21.48-21.52 32.21-32.29.26-.26.65-.38 1.91-1.07 12.37 12.87 24.92 25.92 37.25 38.75 21.01-20.73 41.24-40.68 61.25-60.42 13.68 13.4 27.13 26.58 40.86 40.03-20.17 20.86-81.68 82.71-100.5 101.5zM256 0L0 256l256 256 256-256L256 0zM16 256L256 16l240 240-240 240L16 256z"/></svg>
assets/static/brands/fantasy-flight-games.svg
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.004394328687340021, 0.004394328687340021, 0.004394328687340021, 0.004394328687340021, 0 ]
{ "id": 3, "code_window": [ " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/armv7/docker-compose.yml", "type": "replace", "edit_start_line_idx": 98 }
<template> <div> <div v-if="photos.length === 0" class="pa-2"> <v-alert :value="true" color="secondary-dark" icon="image_not_supported" class="no-results ma-2 opacity-70" outline > <h3 v-if="filter.order === 'edited'" class="body-2 ma-0 pa-0"> <translate>No recently edited pictures</translate> </h3> <h3 v-else class="body-2 ma-0 pa-0"> <translate>No pictures found</translate> </h3> <p class="body-1 mt-2 mb-0 pa-0"> <translate>Try again using other filters or keywords.</translate> </p> </v-alert> </div> <v-data-table v-else v-model="selected" :headers="listColumns" :items="photos" hide-actions class="search-results photo-results list-view" :class="{'select-results': selectMode}" disable-initial-sort item-key="ID" :no-data-text="notFoundMessage" > <template #items="props"> <td style="user-select: none;" :data-uid="props.item.UID" class="result" :class="props.item.classes()"> <v-img :key="props.item.Hash" :src="props.item.thumbnailUrl('tile_50')" :alt="props.item.Title" :transition="false" aspect-ratio="1" style="user-select: none" class="accent lighten-2 clickable" @touchstart="onMouseDown($event, props.index)" @touchend.stop.prevent="onClick($event, props.index)" @mousedown="onMouseDown($event, props.index)" @contextmenu.stop="onContextMenu($event, props.index)" @click.stop.prevent="onClick($event, props.index)" > <v-btn v-if="selectMode" :ripple="false" flat icon large absolute class="input-select"> <v-icon color="white" class="select-on">check_circle</v-icon> <v-icon color="white" class="select-off">radio_button_off</v-icon> </v-btn> <v-btn v-else-if="props.item.Type === 'video' || props.item.Type === 'live'" :ripple="false" flat icon large absolute class="input-open" @click.stop.prevent="openPhoto(props.index, true)"> <v-icon color="white" class="default-hidden action-live" :title="$gettext('Live')">$vuetify.icons.live_photo</v-icon> <v-icon color="white" class="default-hidden action-play" :title="$gettext('Video')">play_arrow</v-icon> </v-btn> </v-img> </td> <td class="p-photo-desc clickable" :data-uid="props.item.UID" style="user-select: none;" @click.stop.prevent="openPhoto(props.index, false)"> {{ props.item.Title }} </td> <td class="p-photo-desc hidden-xs-only" :title="props.item.getDateString()"> <button style="user-select: none;" @click.stop.prevent="editPhoto(props.index)"> {{ props.item.shortDateString() }} </button> </td> <td class="p-photo-desc hidden-sm-and-down" style="user-select: none;"> <button @click.stop.prevent="editPhoto(props.index)"> {{ props.item.CameraMake }} {{ props.item.CameraModel }} </button> </td> <td class="p-photo-desc hidden-xs-only"> <button v-if="filter.order === 'name'" :title="$gettext('Name')" @click.exact="downloadFile(props.index)"> {{ props.item.FileName }} </button> <button v-else-if="props.item.Country !== 'zz' && showLocation" style="user-select: none;" @click.stop.prevent="openLocation(props.index)"> {{ props.item.locationInfo() }} </button> <span v-else> {{ props.item.locationInfo() }} </span> </td> </template> </v-data-table> </div> </template> <script> import download from "common/download"; import Notify from "common/notify"; export default { name: 'PPhotoList', props: { photos: { type: Array, default: () => [], }, openPhoto: Function, editPhoto: Function, openLocation: Function, album: { type: Object, default: () => {}, }, filter: { type: Object, default: () => {}, }, context: String, selectMode: Boolean, }, data() { let m = this.$gettext("Couldn't find anything."); m += " " + this.$gettext("Try again using other filters or keywords."); let showName = this.filter.order === 'name'; const align = !this.$rtl ? 'left' : 'right'; return { config: this.$config.values, notFoundMessage: m, 'selected': [], 'listColumns': [ {text: '', value: '', align: 'center', class: 'p-col-select', sortable: false}, {text: this.$gettext('Title'), align, value: 'Title', sortable: false}, {text: this.$gettext('Taken'), align, class: 'hidden-xs-only', value: 'TakenAt', sortable: false}, {text: this.$gettext('Camera'), align, class: 'hidden-sm-and-down', value: 'CameraModel', sortable: false}, { text: showName ? this.$gettext('Name') : this.$gettext('Location'), align, class: 'hidden-xs-only', value: showName ? 'FileName' : 'PlaceLabel', sortable: false }, ], showName: showName, showLocation: this.$config.values.settings.features.places, hidePrivate: this.$config.values.settings.features.private, mouseDown: { index: -1, scrollY: window.scrollY, timeStamp: -1, }, }; }, methods: { downloadFile(index) { Notify.success(this.$gettext("Downloading…")); const photo = this.photos[index]; download(`${this.$config.apiUri}/dl/${photo.Hash}?t=${this.$config.downloadToken()}`, photo.FileName); }, onSelect(ev, index) { if (ev.shiftKey) { this.selectRange(index); } else { this.toggle(this.photos[index]); } }, onMouseDown(ev, index) { this.mouseDown.index = index; this.mouseDown.scrollY = window.scrollY; this.mouseDown.timeStamp = ev.timeStamp; }, onClick(ev, index) { const longClick = (this.mouseDown.index === index && (ev.timeStamp - this.mouseDown.timeStamp) > 400); const scrolled = (this.mouseDown.scrollY - window.scrollY) !== 0; if (scrolled) { return; } if (longClick || this.selectMode) { if (longClick || ev.shiftKey) { this.selectRange(index); } else { this.toggle(this.photos[index]); } } else if (this.photos[index]) { let photo = this.photos[index]; if (photo.Type === 'video' && photo.isPlayable()) { this.openPhoto(index, true); } else { this.openPhoto(index, false); } } }, onContextMenu(ev, index) { if (this.$isMobile) { ev.preventDefault(); ev.stopPropagation(); this.selectRange(index); } }, toggle(photo) { this.$clipboard.toggle(photo); }, selectRange(index) { this.$clipboard.addRange(index, this.photos); }, } }; </script>
frontend/src/share/photo/list.vue
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00017592849326319993, 0.00017146175378002226, 0.00016765865439083427, 0.00017145267338491976, 0.0000022113965769676724 ]
{ "id": 3, "code_window": [ " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/armv7/docker-compose.yml", "type": "replace", "edit_start_line_idx": 98 }
package search import ( "testing" "github.com/photoprism/photoprism/internal/form" "github.com/stretchr/testify/assert" ) func TestPhotosQueryMono(t *testing.T) { var f0 form.SearchPhotos f0.Query = "mono:true" f0.Merged = true photos0, _, err := Photos(f0) if err != nil { t.Fatal(err) } assert.GreaterOrEqual(t, len(photos0), 8) t.Run("StartsWithPercent", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"%gold\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterPercent", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"I love % dog\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithPercent", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"sale%\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("StartsWithAmpersand", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"&IlikeFood\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterAmpersand", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"Pets & Dogs\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithAmpersand", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"Light&\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("StartsWithSingleQuote", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"'Family\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterSingleQuote", func(t *testing.T) { var f form.SearchPhotos // Note: If the string in mono starts with f/F, the txt package will assume it means false, f.Query = "mono:\"Mother's Day\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithSingleQuote", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"Ice Cream'\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("StartsWithAsterisk", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"*Forrest\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterAsterisk", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"My*Kids\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithAsterisk", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"Yoga***\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("StartsWithPipe", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"|Banana\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterPipe", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"Red|Green\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithPipe", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"Blue|\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("StartsWithNumber", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"345 Shirt\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("CenterNumber", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"Color555 Blue\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("EndsWithNumber", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"Route 66\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("AndSearch", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"Route 66 & Father's Day\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) t.Run("OrSearch", func(t *testing.T) { var f form.SearchPhotos f.Query = "mono:\"Route %66 | *Father's Day\"" f.Merged = true photos, _, err := Photos(f) if err != nil { t.Fatal(err) } assert.Equal(t, len(photos), len(photos0)) }) }
internal/search/photos_filter_mono_test.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0010440645273774862, 0.0002018625382333994, 0.00016565276018809527, 0.00017380205099470913, 0.00015641817299183458 ]
{ "id": 4, "code_window": [ " PHOTOPRISM_DATABASE_PASSWORD: \"_admin_password_\" # MariaDB or MySQL database user password\n", " ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clean):\n", " PHOTOPRISM_INIT: \"update tensorflow clean\"\n", " HOME: \"/photoprism\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example:\n", " - \"./originals:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n", " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/cloud/docker-compose.yml", "type": "replace", "edit_start_line_idx": 159 }
version: '3.5' # Example Docker Compose config file for PhotoPrism (Linux / AMD64) # Includes Ophelia, a docker job scheduler: https://github.com/mcuadros/ofelia # # Note: # - Running PhotoPrism on a server with less than 4 GB of swap space or setting a memory/swap limit can cause unexpected # restarts ("crashes"), for example, when the indexer temporarily needs more memory to process large files. # - If you install PhotoPrism on a public server outside your home network, please always run it behind a secure # HTTPS reverse proxy such as Traefik or Caddy. Your files and passwords will otherwise be transmitted # in clear text and can be intercepted by anyone, including your provider, hackers, and governments: # https://docs.photoprism.app/getting-started/proxies/traefik/ # # Documentation : https://docs.photoprism.app/getting-started/docker-compose/ # Docker Hub URL: https://hub.docker.com/r/photoprism/photoprism/ # # DOCKER COMPOSE COMMAND REFERENCE # see https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index # # All commands may have to be prefixed with "sudo" when not running as root. # This will point the home directory shortcut ~ to /root in volume mounts. services: photoprism: # Use photoprism/photoprism:preview for testing preview builds: image: photoprism/photoprism:latest container_name: photoprism depends_on: - mariadb ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors # restart: unless-stopped security_opt: - seccomp:unconfined - apparmor:unconfined ports: - "2342:2342" # HTTP port (host:container) environment: PHOTOPRISM_ADMIN_PASSWORD: "insecure" # !!! PLEASE CHANGE YOUR INITIAL "admin" PASSWORD !!! PHOTOPRISM_SITE_URL: "http://localhost:2342/" # public server URL incl http:// or https:// and /path, :port is optional PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "gzip" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_DEBUG: "false" # run in debug mode (shows additional log messages) PHOTOPRISM_PUBLIC: "false" # no authentication required (disables password protection) PHOTOPRISM_READONLY: "false" # do not modify originals directory (reduced functionality) PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables settings UI and API PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive (requires TensorFlow) PHOTOPRISM_UPLOAD_NSFW: "true" # allows uploads that MAY be offensive # PHOTOPRISM_DATABASE_DRIVER: "sqlite" # SQLite is an embedded database that doesn't require a server PHOTOPRISM_DATABASE_DRIVER: "mysql" # use MariaDB 10.5+ or MySQL 8+ instead of SQLite for improved performance PHOTOPRISM_DATABASE_SERVER: "mariadb:3306" # MariaDB or MySQL database server (hostname:port) PHOTOPRISM_DATABASE_NAME: "photoprism" # MariaDB or MySQL database schema name PHOTOPRISM_DATABASE_USER: "photoprism" # MariaDB or MySQL database user name PHOTOPRISM_DATABASE_PASSWORD: "insecure" # MariaDB or MySQL database user password PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clitools, clean): # PHOTOPRISM_INIT: "gpu tensorflow" ## Run as a specific user, group, or with a custom umask (does not work together with "user:") # PHOTOPRISM_UID: 1000 # PHOTOPRISM_GID: 1000 # PHOTOPRISM_UMASK: 0000 HOME: "/photoprism" ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user) # user: "1000:1000" working_dir: "/photoprism" ## Storage Folders: "~" is a shortcut for your home directory, "." for the current directory volumes: # "/host/folder:/photoprism/folder" # example - "~/Pictures:/photoprism/originals" # original media files (photos and videos) # - "/example/family:/photoprism/originals/family" # *additional* media folders can be mounted like this # - "~/Import:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) ## Database Server (recommended) ## see https://docs.photoprism.app/getting-started/faq/#should-i-use-sqlite-mariadb-or-mysql mariadb: restart: unless-stopped image: mariadb:10.7 container_name: mariadb security_opt: - seccomp:unconfined - apparmor:unconfined command: mysqld --innodb-buffer-pool-size=128M --transaction-isolation=READ-COMMITTED --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --max-connections=512 --innodb-rollback-on-timeout=OFF --innodb-lock-wait-timeout=120 ## Never store database files on an unreliable device such as a USB flash drive, an SD card, or a shared network folder: volumes: - "./database:/var/lib/mysql" # important, do not remove environment: MARIADB_AUTO_UPGRADE: "1" MARIADB_INITDB_SKIP_TZINFO: "1" MARIADB_DATABASE: "photoprism" MARIADB_USER: "photoprism" MARIADB_PASSWORD: "insecure" MARIADB_ROOT_PASSWORD: "insecure" ## Ofelia Job Runner (recommended for running background jobs) ## see https://github.com/mcuadros/ofelia ofelia: restart: unless-stopped image: mcuadros/ofelia:latest container_name: ofelia volumes: - "/var/run/docker.sock:/var/run/docker.sock:ro" - "./jobs.ini:/etc/ofelia/config.ini" ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower # # watchtower: # restart: unless-stopped # image: containrrr/watchtower # environment: # WATCHTOWER_CLEANUP: "true" # WATCHTOWER_POLL_INTERVAL: 7200 # checks for updates every two hours # volumes: # - "/var/run/docker.sock:/var/run/docker.sock" # - "~/.docker/config.json:/config.json" # optional, for authentication if you have a Docker Hub account
docker/examples/scheduler/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.2288871556520462, 0.044052258133888245, 0.00021907265181653202, 0.005550490692257881, 0.06888037174940109 ]
{ "id": 4, "code_window": [ " PHOTOPRISM_DATABASE_PASSWORD: \"_admin_password_\" # MariaDB or MySQL database user password\n", " ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clean):\n", " PHOTOPRISM_INIT: \"update tensorflow clean\"\n", " HOME: \"/photoprism\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example:\n", " - \"./originals:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n", " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/cloud/docker-compose.yml", "type": "replace", "edit_start_line_idx": 159 }
package api import ( "net/http" "testing" "github.com/tidwall/gjson" "github.com/stretchr/testify/assert" ) func TestGetConfig(t *testing.T) { t.Run("successful request", func(t *testing.T) { app, router, _ := NewApiTest() GetConfig(router) r := PerformRequest(app, "GET", "/api/v1/config") val := gjson.Get(r.Body.String(), "flags") assert.Equal(t, "public debug test sponsor experimental settings", val.String()) assert.Equal(t, http.StatusOK, r.Code) }) } func TestGetConfigOptions(t *testing.T) { t.Run("unauthorised", func(t *testing.T) { app, router, _ := NewApiTest() GetConfigOptions(router) r := PerformRequest(app, "GET", "/api/v1/config/options") assert.Equal(t, http.StatusUnauthorized, r.Code) }) } func TestSaveConfigOptions(t *testing.T) { t.Run("unauthorised", func(t *testing.T) { app, router, _ := NewApiTest() SaveConfigOptions(router) r := PerformRequest(app, "POST", "/api/v1/config/options") assert.Equal(t, http.StatusUnauthorized, r.Code) }) }
internal/api/config_test.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00017056723299901932, 0.00016520923236384988, 0.00015897296543698758, 0.00016564838006161153, 0.000004148545485804789 ]
{ "id": 4, "code_window": [ " PHOTOPRISM_DATABASE_PASSWORD: \"_admin_password_\" # MariaDB or MySQL database user password\n", " ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clean):\n", " PHOTOPRISM_INIT: \"update tensorflow clean\"\n", " HOME: \"/photoprism\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example:\n", " - \"./originals:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n", " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/cloud/docker-compose.yml", "type": "replace", "edit_start_line_idx": 159 }
 Open Sans Semibold 7168-7423
assets/static/font/Open Sans Semibold/7168-7423.pbf
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00016367276839446276, 0.00016367276839446276, 0.00016367276839446276, 0.00016367276839446276, 0 ]
{ "id": 4, "code_window": [ " PHOTOPRISM_DATABASE_PASSWORD: \"_admin_password_\" # MariaDB or MySQL database user password\n", " ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clean):\n", " PHOTOPRISM_INIT: \"update tensorflow clean\"\n", " HOME: \"/photoprism\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example:\n", " - \"./originals:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n", " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/cloud/docker-compose.yml", "type": "replace", "edit_start_line_idx": 159 }
export const Auto = ""; export const Default = "default"; export const Manual = "manual"; export const Estimate = "estimate"; export const Name = "name"; export const Meta = "meta"; export const Xmp = "xmp"; export const Yaml = "yaml"; export const Marker = "marker"; export const Image = "image"; export const Keyword = "keyword"; export const Location = "location";
frontend/src/common/src.js
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00017619659774936736, 0.00017601935542188585, 0.00017584212764631957, 0.00017601935542188585, 1.7723505152389407e-7 ]
{ "id": 5, "code_window": [ " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/docker-compose.yml", "type": "replace", "edit_start_line_idx": 93 }
version: '3.5' # PhotoPrism for Cloud Servers running Ubuntu 20.04 LTS (Focal Fossa) # =================================================================== # # Run this script as root to install PhotoPrism on a cloud server e.g. at DigitalOcean: # # bash <(curl -s https://dl.photoprism.app/docker/cloud/setup.sh) # # This may take a while to complete, depending on the performance of your # server and its internet connection. # # When done - and you see no errors - please open # # https://<YOUR SERVER IP>/ # # in a Web browser and log in using the initial admin password shown # by the script. You may also see the initial password by running # # cat /root/.initial-password.txt # # as root on your server. To open a terminal: # # ssh root@<YOUR SERVER IP> # # Data and all config files related to PhotoPrism can be found in # # /opt/photoprism # # The main docker-compose config file for changing config options is # # /opt/photoprism/docker-compose.yml # # The server is running as "photoprism" (UID 1000) by default. There's no need # to change defaults unless you experience conflicts with other services running # on the same server. For example, you may need to disable the Traefik reverse # proxy as the ports 80 and 443 can only be used by a single web server / proxy. # # Configuring multiple apps on the same server is beyond the scope of this base # config and for advanced users only. # # This config includes Ophelia, a docker job scheduler: # # https://github.com/mcuadros/ofelia # # See jobs.ini for details. # # SYSTEM REQUIREMENTS # -------------------------------------------------------------------------- # # We recommend hosting PhotoPrism on a server with at least 2 cores and # 4 GB of memory. Beyond these minimum requirements, the amount of RAM # should match the number of cores. Indexing large photo and video # collections significantly benefits from fast, local SSD storage. # # RAW image conversion and automatic image classification using TensorFlow # will be disabled on servers with 1 GB or less memory. # # DOCKER COMPOSE COMMAND REFERENCE # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index # # More examples: https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # # USING LET'S ENCRYPT HTTPS # -------------------------------------------------------------------------- # # If your server has a public domain name, please disable the self-signed # certificate and enable domain based routing in docker-compose.yml and # traefik.yaml (see inline instructions in !! UPPERCASE !!) # # ssh root@<YOUR SERVER IP> # cd /opt/photoprism # nano docker-compose.yml # nano traefik.yaml # docker-compose stop # docker-compose up -d # # You should now be able to access your instance without security warnings. services: photoprism: ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors restart: always ## Use photoprism/photoprism:preview for testing preview builds: image: photoprism/photoprism:latest container_name: photoprism depends_on: - mariadb security_opt: - seccomp:unconfined - apparmor:unconfined ## Run as a non-root user (see https://docs.docker.com/engine/reference/run/#user) user: "1000:1000" ## Don't expose port when running behind Traefik reverse proxy! # ports: # - "2342:2342" # HTTP port (host:container) labels: - "traefik.enable=true" - "traefik.http.services.photoprism.loadbalancer.server.port=2342" - "traefik.http.routers.photoprism.tls=true" - "traefik.http.routers.photoprism.entrypoints=websecure" ## !! REMOVE default route if your server has a public domain name !! - "traefik.http.routers.photoprism.rule=PathPrefix(`/`)" ## !! UNCOMMENT and CHANGE to set the public domain name !! # - "traefik.http.routers.photoprism.rule=Host(`photos.yourdomain.com`)" ## !! UNCOMMENT to enable Let's Encrypt HTTPS !! # - "traefik.http.routers.photoprism.tls.certresolver=myresolver" ## !! REMOVE both for Let's Encrypt HTTPS with default HTTP challenge (DNS challenge supports wildcards) !! - "traefik.http.routers.photoprism.tls.domains[0].main=example.com" - "traefik.http.routers.photoprism.tls.domains[0].sans=*.example.com" environment: ## !! CHANGE site url if your server has a public domain name e.g. "https://photos.yourdomain.com/" !! PHOTOPRISM_SITE_URL: "https://_public_ip_/" PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" PHOTOPRISM_ADMIN_PASSWORD: "_admin_password_" # YOUR INITIAL "admin" PASSWORD PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "gzip" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_DEBUG: "false" # run in debug mode (shows additional log messages) PHOTOPRISM_PUBLIC: "false" # no authentication required (disables password protection) PHOTOPRISM_READONLY: "false" # do not modify originals directory (reduced functionality) PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables Settings in Web UI PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive (requires TensorFlow) PHOTOPRISM_UPLOAD_NSFW: "true" # allows uploads that MAY be offensive PHOTOPRISM_DATABASE_DRIVER: "mysql" # use MariaDB 10.5+ or MySQL 8+ instead of SQLite for improved performance PHOTOPRISM_DATABASE_SERVER: "mariadb:3306" # MariaDB or MySQL database server (hostname:port) PHOTOPRISM_DATABASE_NAME: "photoprism" # MariaDB or MySQL database schema name PHOTOPRISM_DATABASE_USER: "photoprism" # MariaDB or MySQL database user name PHOTOPRISM_DATABASE_PASSWORD: "_admin_password_" # MariaDB or MySQL database user password ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clean): PHOTOPRISM_INIT: "update tensorflow clean" HOME: "/photoprism" working_dir: "/photoprism" ## Storage Folders: "~" is a shortcut for your home directory, "." for the current directory volumes: # "/host/folder:/photoprism/folder" # example: - "./originals:/photoprism/originals" # original media files (photos and videos) - "./import:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) - "./backup:/var/lib/photoprism" # *optional* storage folder for database backups ## Traefik Reverse Proxy (required) ## see https://docs.photoprism.app/getting-started/proxies/traefik/ traefik: restart: always image: traefik:v2.6 container_name: traefik ports: - "80:80" - "443:443" expose: - "80" - "443" volumes: - "/var/run/docker.sock:/var/run/docker.sock" - "./traefik/:/data/" - "./traefik.yaml:/etc/traefik/traefik.yaml" - "./certs/:/certs/" ## Database Server (recommended) ## see https://docs.photoprism.app/getting-started/faq/#should-i-use-sqlite-mariadb-or-mysql mariadb: restart: always image: mariadb:10.7 container_name: mariadb security_opt: - seccomp:unconfined - apparmor:unconfined command: mysqld --innodb-buffer-pool-size=128M --transaction-isolation=READ-COMMITTED --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --max-connections=512 --innodb-rollback-on-timeout=OFF --innodb-lock-wait-timeout=120 ## Never store database files on an unreliable device such as a USB flash drive, an SD card, or a shared network folder: volumes: - "./database:/var/lib/mysql" # important, do not remove environment: MARIADB_AUTO_UPGRADE: "1" MARIADB_INITDB_SKIP_TZINFO: "1" MARIADB_DATABASE: "photoprism" MARIADB_USER: "photoprism" MARIADB_PASSWORD: "_admin_password_" MARIADB_ROOT_PASSWORD: "_admin_password_" ## Ofelia Job Runner (recommended) ## see https://github.com/mcuadros/ofelia ofelia: restart: always image: mcuadros/ofelia:latest container_name: ofelia volumes: - "/var/run/docker.sock:/var/run/docker.sock:ro" - "./jobs.ini:/etc/ofelia/config.ini" ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower watchtower: restart: always image: containrrr/watchtower container_name: watchtower environment: WATCHTOWER_CLEANUP: "true" WATCHTOWER_POLL_INTERVAL: 86400 # checks for updates every day volumes: - "/var/run/docker.sock:/var/run/docker.sock"
docker/examples/cloud/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.46164628863334656, 0.025423958897590637, 0.0001633061037864536, 0.0007815839489921927, 0.09353043138980865 ]
{ "id": 5, "code_window": [ " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/docker-compose.yml", "type": "replace", "edit_start_line_idx": 93 }
package api import ( "net/http" "testing" "github.com/tidwall/gjson" "github.com/stretchr/testify/assert" ) func TestGetDownload(t *testing.T) { t.Run("download not existing file", func(t *testing.T) { app, router, conf := NewApiTest() GetDownload(router) r := PerformRequest(app, "GET", "/api/v1/dl/123xxx?t="+conf.DownloadToken()) val := gjson.Get(r.Body.String(), "error") assert.Equal(t, "record not found", val.String()) assert.Equal(t, http.StatusNotFound, r.Code) }) t.Run("could not find original", func(t *testing.T) { app, router, conf := NewApiTest() GetDownload(router) r := PerformRequest(app, "GET", "/api/v1/dl/3cad9168fa6acc5c5c2965ddf6ec465ca42fd818?t="+conf.DownloadToken()) assert.Equal(t, http.StatusNotFound, r.Code) }) t.Run("invalid download token", func(t *testing.T) { app, router, _ := NewApiTest() GetDownload(router) r := PerformRequest(app, "GET", "/api/v1/dl/3cad9168fa6acc5c5c2965ddf6ec465ca42fd818?t=xxx") assert.Equal(t, http.StatusForbidden, r.Code) }) }
internal/api/download_test.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00016863297787494957, 0.00016558698553126305, 0.0001640974951442331, 0.00016480873455293477, 0.0000018443444105287199 ]
{ "id": 5, "code_window": [ " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/docker-compose.yml", "type": "replace", "edit_start_line_idx": 93 }
package photoprism import ( "github.com/dustin/go-humanize/english" "github.com/photoprism/photoprism/internal/entity" "github.com/photoprism/photoprism/internal/face" "github.com/photoprism/photoprism/internal/query" "github.com/photoprism/photoprism/pkg/sanitize" ) // Audit face clusters and subjects. func (w *Faces) Audit(fix bool) (err error) { invalidFaces, invalidSubj, err := query.MarkersWithNonExistentReferences() if err != nil { return err } subj, err := query.SubjectMap() if err != nil { log.Errorf("faces: %s (find subjects)", err) } if n := len(subj); n == 0 { log.Infof("found no subjects") } else { log.Infof("found %s", english.Plural(n, "subject", "subjects")) } // Fix non-existent marker subjects references? if n := len(invalidSubj); n == 0 { log.Infof("found no invalid marker subjects") } else if !fix { log.Infof("%s with non-existent subjects", english.Plural(n, "marker", "markers")) } else if removed, err := query.RemoveNonExistentMarkerSubjects(); err != nil { log.Errorf("faces: %s (remove orphan subjects)", err) } else if removed > 0 { log.Infof("removed %d / %d markers with non-existent subjects", removed, n) } // Fix non-existent marker face references? if n := len(invalidFaces); n == 0 { log.Infof("found no invalid marker faces") } else if !fix { log.Infof("%s with non-existent faces", english.Plural(n, "marker", "markers")) } else if removed, err := query.RemoveNonExistentMarkerFaces(); err != nil { log.Errorf("faces: %s (remove orphan embeddings)", err) } else if removed > 0 { log.Infof("removed %d / %d markers with non-existent faces", removed, n) } conflicts := 0 resolved := 0 faces, err := query.Faces(true, false, false) if err != nil { return err } faceMap := make(map[string]entity.Face) for _, f1 := range faces { faceMap[f1.ID] = f1 for _, f2 := range faces { if matched, dist := f1.Match(face.Embeddings{f2.Embedding()}); matched { if f1.SubjUID == f2.SubjUID { continue } conflicts++ r := f1.SampleRadius + face.MatchDist log.Infof("face %s: ambiguous subject at dist %f, Ø %f from %d samples, collision Ø %f", f1.ID, dist, r, f1.Samples, f1.CollisionRadius) if f1.SubjUID != "" { log.Infof("face %s: subject %s (%s %s)", f1.ID, entity.SubjNames.Log(f1.SubjUID), f1.SubjUID, entity.SrcString(f1.FaceSrc)) } else { log.Infof("face %s: has no subject (%s)", f1.ID, entity.SrcString(f1.FaceSrc)) } if f2.SubjUID != "" { log.Infof("face %s: subject %s (%s %s)", f2.ID, entity.SubjNames.Log(f2.SubjUID), f2.SubjUID, entity.SrcString(f2.FaceSrc)) } else { log.Infof("face %s: has no subject (%s)", f2.ID, entity.SrcString(f2.FaceSrc)) } if !fix { // Do nothing. } else if ok, err := f1.ResolveCollision(face.Embeddings{f2.Embedding()}); err != nil { log.Errorf("conflict resolution for %s failed, face id %s has collisions with other persons (%s)", entity.SubjNames.Log(f1.SubjUID), f1.ID, err) } else if ok { log.Infof("successful conflict resolution for %s, face id %s had collisions with other persons", entity.SubjNames.Log(f1.SubjUID), f1.ID) resolved++ } else { log.Infof("conflict resolution for %s not successful, face id %s still has collisions with other persons", entity.SubjNames.Log(f1.SubjUID), f1.ID) } } } } if conflicts == 0 { log.Infof("found no ambiguous subjects") } else if !fix { log.Infof("%s", english.Plural(conflicts, "ambiguous subject", "ambiguous subjects")) } else { log.Infof("%s, %d resolved", english.Plural(conflicts, "ambiguous subject", "ambiguous subjects"), resolved) } if markers, err := query.MarkersWithSubjectConflict(); err != nil { log.Errorf("faces: %s (find marker conflicts)", err) } else { for _, m := range markers { log.Infof("marker %s: %s subject %s conflicts with face %s subject %s", m.MarkerUID, entity.SrcString(m.SubjSrc), sanitize.Log(subj[m.SubjUID].SubjName), m.FaceID, sanitize.Log(subj[faceMap[m.FaceID].SubjUID].SubjName)) } } // Find and fix orphan face clusters. if orphans, err := entity.OrphanFaces(); err != nil { log.Errorf("%s while finding orphan face clusters", err) } else if l := len(orphans); l == 0 { log.Infof("found no orphan face clusters") } else if !fix { log.Infof("found %s", english.Plural(l, "orphan face cluster", "orphan face clusters")) } else if err := orphans.Delete(); err != nil { log.Errorf("failed removing %s: %s", english.Plural(l, "orphan face cluster", "orphan face clusters"), err) } else { log.Infof("removed %s", english.Plural(l, "orphan face cluster", "orphan face clusters")) } // Find and fix orphan people. if orphans, err := entity.OrphanPeople(); err != nil { log.Errorf("%s while finding orphan people", err) } else if l := len(orphans); l == 0 { log.Infof("found no orphan people") } else if !fix { log.Infof("found %s", english.Plural(l, "orphan person", "orphan people")) } else if err := orphans.Delete(); err != nil { log.Errorf("failed fixing %s: %s", english.Plural(l, "orphan person", "orphan people"), err) } else { log.Infof("removed %s", english.Plural(l, "orphan person", "orphan people")) } return nil }
internal/photoprism/faces_audit.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0007725337636657059, 0.00021349832240957767, 0.0001703976740827784, 0.0001737955171847716, 0.00014941512199584395 ]
{ "id": 5, "code_window": [ " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " ## Share hardware devices with FFmpeg and TensorFlow (optional):\n", " # devices:\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/docker-compose.yml", "type": "replace", "edit_start_line_idx": 93 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M512 194.8c0 101.3-82.4 183.8-183.8 183.8-101.7 0-184.4-82.4-184.4-183.8 0-101.6 82.7-184.3 184.4-184.3C429.6 10.5 512 93.2 512 194.8zM0 501.5h90v-491H0v491z"/></svg>
assets/static/brands/patreon.svg
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00017268183000851423, 0.00017268183000851423, 0.00017268183000851423, 0.00017268183000851423, 0 ]
{ "id": 6, "code_window": [ " # - \"/dev/nvidia-modeset:/dev/nvidia-modeset\"\n", " # - \"/dev/nvidia-nvswitchctl:/dev/nvidia-nvswitchctl\"\n", " # - \"/dev/nvidia-uvm:/dev/nvidia-uvm\"\n", " # - \"/dev/nvidia-uvm-tools:/dev/nvidia-uvm-tools\"\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/docker-compose.yml", "type": "replace", "edit_start_line_idx": 106 }
version: '3.5' # Example Docker Compose config file for PhotoPrism (Windows / AMD64) # # Note: # - Running PhotoPrism on a server with less than 4 GB of swap space or setting a memory/swap limit can cause unexpected # restarts ("crashes"), for example, when the indexer temporarily needs more memory to process large files. # - Windows Pro users should disable the WSL 2 based engine in Docker Settings > General so that # they can mount drives other than C:. This will enable Hyper-V, which Microsoft doesn't offer # to its Windows Home customers. Docker Desktop uses dynamic memory allocation with WSL 2. # It's important to explicitly increase the Docker memory limit to 4 GB or more when using Hyper-V. # The default of 2 GB may reduce indexing performance and cause unexpected restarts. # - If you install PhotoPrism on a public server outside your home network, please always run it behind a secure # HTTPS reverse proxy such as Traefik or Caddy. Your files and passwords will otherwise be transmitted # in clear text and can be intercepted by anyone, including your provider, hackers, and governments: # https://docs.photoprism.app/getting-started/proxies/traefik/ # # Documentation : https://docs.photoprism.app/getting-started/docker-compose/ # Docker Hub URL: https://hub.docker.com/r/photoprism/photoprism/ # # DOCKER COMPOSE COMMAND REFERENCE # see https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index services: photoprism: ## Use photoprism/photoprism:preview for testing preview builds: image: photoprism/photoprism:latest depends_on: - mariadb ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors # restart: unless-stopped security_opt: - seccomp:unconfined - apparmor:unconfined ports: - "2342:2342" # HTTP port (host:container) environment: PHOTOPRISM_ADMIN_PASSWORD: "insecure" # !!! PLEASE CHANGE YOUR INITIAL "admin" PASSWORD !!! PHOTOPRISM_SITE_URL: "http://localhost:2342/" # public server URL incl http:// or https:// and /path, :port is optional PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "gzip" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_DEBUG: "false" # run in debug mode, shows additional log messages PHOTOPRISM_PUBLIC: "false" # no authentication required, disables password protection PHOTOPRISM_READONLY: "false" # do not modify originals folder; disables import, upload, and delete PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables settings UI and API PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive (requires TensorFlow) PHOTOPRISM_UPLOAD_NSFW: "true" # allows uploads that MAY be offensive PHOTOPRISM_DATABASE_DRIVER: "mysql" # use MariaDB 10.5+ or MySQL 8+ instead of SQLite for improved performance PHOTOPRISM_DATABASE_SERVER: "mariadb:3306" # MariaDB or MySQL database server hostname (:port is optional) PHOTOPRISM_DATABASE_NAME: "photoprism" # MariaDB or MySQL database schema name PHOTOPRISM_DATABASE_USER: "photoprism" # MariaDB or MySQL database user name PHOTOPRISM_DATABASE_PASSWORD: "insecure" # MariaDB or MySQL database user password PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" HOME: "/photoprism" working_dir: "/photoprism" ## Storage Folders: use "/" not "\" as separator, "~" is a shortcut for C:/user/{username}, "." for the current directory volumes: # "C:/user/username/folder:/photoprism/folder" # example - "~/Pictures:/photoprism/originals" # original media files (photos and videos) # - "D:/example/family:/photoprism/originals/family" # *additional* media folders can be mounted like this # - "E:/:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) ## Database Server (recommended) ## see https://docs.photoprism.app/getting-started/faq/#should-i-use-sqlite-mariadb-or-mysql mariadb: ## If MariaDB gets stuck in a restart loop, this points to a memory or filesystem issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors restart: unless-stopped image: mariadb:10.7 security_opt: - seccomp:unconfined - apparmor:unconfined ## --lower-case-table-names=1 stores tables in lowercase and compares names in a case-insensitive manner ## see https://mariadb.com/kb/en/server-system-variables/#lower_case_table_names command: mysqld --innodb-buffer-pool-size=128M --lower-case-table-names=1 --transaction-isolation=READ-COMMITTED --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --max-connections=512 --innodb-rollback-on-timeout=OFF --innodb-lock-wait-timeout=120 volumes: - "database:/var/lib/mysql" # important, do not remove; named volume "database" is defined at the bottom environment: MARIADB_AUTO_UPGRADE: "1" MARIADB_INITDB_SKIP_TZINFO: "1" MARIADB_DATABASE: "photoprism" MARIADB_USER: "photoprism" MARIADB_PASSWORD: "insecure" MARIADB_ROOT_PASSWORD: "insecure" ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower # # watchtower: # restart: unless-stopped # image: containrrr/watchtower # environment: # WATCHTOWER_CLEANUP: "true" # WATCHTOWER_POLL_INTERVAL: 7200 # checks for updates every two hours # volumes: # - "/var/run/docker.sock:/var/run/docker.sock" # - "~/.docker/config.json:/config.json" # optional, for authentication if you have a Docker Hub account ## Create named volumes, advanced users may remove this if they mount a regular host folder ## for the database or use SQLite instead (never remove otherwise) volumes: database: driver: local
docker/examples/windows/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.2347518354654312, 0.02197166159749031, 0.00016196562501136214, 0.0010450019035488367, 0.059458985924720764 ]
{ "id": 6, "code_window": [ " # - \"/dev/nvidia-modeset:/dev/nvidia-modeset\"\n", " # - \"/dev/nvidia-nvswitchctl:/dev/nvidia-nvswitchctl\"\n", " # - \"/dev/nvidia-uvm:/dev/nvidia-uvm\"\n", " # - \"/dev/nvidia-uvm-tools:/dev/nvidia-uvm-tools\"\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/docker-compose.yml", "type": "replace", "edit_start_line_idx": 106 }
<template> <v-dialog v-model="show" lazy persistent max-width="350" class="p-file-delete-dialog" @keydown.esc="cancel"> <v-card raised elevation="24"> <v-container fluid class="pb-2 pr-2 pl-2"> <v-layout row wrap> <v-flex xs3 text-xs-center> <v-icon size="54" color="secondary-dark lighten-1">delete_outline</v-icon> </v-flex> <v-flex xs9 text-xs-left align-self-center> <div class="subheading pr-1"> <translate>Are you sure you want to permanently delete this file?</translate> </div> </v-flex> <v-flex xs12 text-xs-right class="pt-3"> <v-btn depressed color="secondary-light" class="action-cancel" @click.stop="cancel"> <translate key="Cancel">Cancel</translate> </v-btn> <v-btn color="primary-button" depressed dark class="action-confirm" @click.stop="confirm"> <translate key="Delete">Delete</translate> </v-btn> </v-flex> </v-layout> </v-container> </v-card> </v-dialog> </template> <script> export default { name: 'PFileDeleteDialog', props: { show: Boolean, }, data() { return {}; }, methods: { cancel() { this.$emit('cancel'); }, confirm() { this.$emit('confirm'); }, } }; </script>
frontend/src/dialog/file/delete.vue
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00017474165360908955, 0.00017148697224911302, 0.00016870905528776348, 0.00017071349429897964, 0.0000021351922896428732 ]
{ "id": 6, "code_window": [ " # - \"/dev/nvidia-modeset:/dev/nvidia-modeset\"\n", " # - \"/dev/nvidia-nvswitchctl:/dev/nvidia-nvswitchctl\"\n", " # - \"/dev/nvidia-uvm:/dev/nvidia-uvm\"\n", " # - \"/dev/nvidia-uvm-tools:/dev/nvidia-uvm-tools\"\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/docker-compose.yml", "type": "replace", "edit_start_line_idx": 106 }
import { Selector } from "testcafe"; import testcafeconfig from "./testcafeconfig"; import Page from "./page-model"; fixture`Test components`.page`${testcafeconfig.url}`; const page = new Page(); test.meta("testID", "components-001")("Test filter options", async (t) => { await t.expect(Selector("body").withText("object Object").exists).notOk(); }); test.meta("testID", "components-002")("Fullscreen mode", async (t) => { await t.click(Selector("div.v-image__image").nth(0)); if (await Selector("#photo-viewer").visible) { await t .expect(Selector("#photo-viewer").visible) .ok() .expect(Selector("img.pswp__img").visible) .ok(); } else { await t.expect(Selector("div.video-viewer").visible).ok(); } }); test.meta("testID", "components-003")("Mosaic view", async (t) => { await page.setFilter("view", "Mosaic"); await t .expect(Selector("div.v-image__image").visible) .ok() .expect(Selector("div.p-photo-mosaic").visible) .ok() .expect(Selector("div.is-photo div.caption").exists) .notOk() .expect(Selector("#photo-viewer").visible) .notOk(); }); test.meta("testID", "components-004")("List view", async (t) => { await page.setFilter("view", "List"); await t .expect(Selector("table.v-datatable").visible) .ok() .expect(Selector("div.list-view").visible) .ok(); }); test.meta("testID", "components-005")("#Card view", async (t) => { await page.setFilter("view", "Cards"); await t .expect(Selector("div.v-image__image").visible) .ok() .expect(Selector("div.is-photo div.caption").visible) .ok() .expect(Selector("#photo-viewer").visible) .notOk(); });
frontend/tests/acceptance/components.js
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.000176313376869075, 0.0001747277710819617, 0.00017405238759238273, 0.0001744203909765929, 7.600604590152216e-7 ]
{ "id": 6, "code_window": [ " # - \"/dev/nvidia-modeset:/dev/nvidia-modeset\"\n", " # - \"/dev/nvidia-nvswitchctl:/dev/nvidia-nvswitchctl\"\n", " # - \"/dev/nvidia-uvm:/dev/nvidia-uvm\"\n", " # - \"/dev/nvidia-uvm-tools:/dev/nvidia-uvm-tools\"\n", " # - \"/dev/video11:/dev/video11\" # Video4Linux (h264_v4l2m2m)\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/docker-compose.yml", "type": "replace", "edit_start_line_idx": 106 }
package fs import ( "fmt" "os" "path" ) // CachePath returns a cache directory name based on the base path, file hash and cache namespace. func CachePath(basePath, fileHash, namespace string, create bool) (cachePath string, err error) { if len(fileHash) < 4 { return "", fmt.Errorf("cache: hash '%s' is too short", fileHash) } if namespace == "" { return "", fmt.Errorf("cache: namespace for hash '%s' is empty", fileHash) } cachePath = path.Join(basePath, namespace, fileHash[0:1], fileHash[1:2], fileHash[2:3]) if create { if err := os.MkdirAll(cachePath, os.ModePerm); err != nil { return "", err } } return cachePath, nil }
pkg/fs/cache.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00018184204236604273, 0.00017429360013920814, 0.00016991063603200018, 0.00017112810746766627, 0.000005360649993235711 ]
{ "id": 7, "code_window": [ " PHOTOPRISM_SITE_DESCRIPTION: \"\"\n", " PHOTOPRISM_SITE_AUTHOR: \"\"\n", " ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clitools, clean):\n", " # PHOTOPRISM_INIT: \"gpu tensorflow\"\n", " HOME: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/macos/docker-compose.yml", "type": "replace", "edit_start_line_idx": 80 }
version: '3.5' # PhotoPrism for Cloud Servers running Ubuntu 20.04 LTS (Focal Fossa) # =================================================================== # # Run this script as root to install PhotoPrism on a cloud server e.g. at DigitalOcean: # # bash <(curl -s https://dl.photoprism.app/docker/cloud/setup.sh) # # This may take a while to complete, depending on the performance of your # server and its internet connection. # # When done - and you see no errors - please open # # https://<YOUR SERVER IP>/ # # in a Web browser and log in using the initial admin password shown # by the script. You may also see the initial password by running # # cat /root/.initial-password.txt # # as root on your server. To open a terminal: # # ssh root@<YOUR SERVER IP> # # Data and all config files related to PhotoPrism can be found in # # /opt/photoprism # # The main docker-compose config file for changing config options is # # /opt/photoprism/docker-compose.yml # # The server is running as "photoprism" (UID 1000) by default. There's no need # to change defaults unless you experience conflicts with other services running # on the same server. For example, you may need to disable the Traefik reverse # proxy as the ports 80 and 443 can only be used by a single web server / proxy. # # Configuring multiple apps on the same server is beyond the scope of this base # config and for advanced users only. # # This config includes Ophelia, a docker job scheduler: # # https://github.com/mcuadros/ofelia # # See jobs.ini for details. # # SYSTEM REQUIREMENTS # -------------------------------------------------------------------------- # # We recommend hosting PhotoPrism on a server with at least 2 cores and # 4 GB of memory. Beyond these minimum requirements, the amount of RAM # should match the number of cores. Indexing large photo and video # collections significantly benefits from fast, local SSD storage. # # RAW image conversion and automatic image classification using TensorFlow # will be disabled on servers with 1 GB or less memory. # # DOCKER COMPOSE COMMAND REFERENCE # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index # # More examples: https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # # USING LET'S ENCRYPT HTTPS # -------------------------------------------------------------------------- # # If your server has a public domain name, please disable the self-signed # certificate and enable domain based routing in docker-compose.yml and # traefik.yaml (see inline instructions in !! UPPERCASE !!) # # ssh root@<YOUR SERVER IP> # cd /opt/photoprism # nano docker-compose.yml # nano traefik.yaml # docker-compose stop # docker-compose up -d # # You should now be able to access your instance without security warnings. services: photoprism: ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors restart: always ## Use photoprism/photoprism:preview for testing preview builds: image: photoprism/photoprism:latest container_name: photoprism depends_on: - mariadb security_opt: - seccomp:unconfined - apparmor:unconfined ## Run as a non-root user (see https://docs.docker.com/engine/reference/run/#user) user: "1000:1000" ## Don't expose port when running behind Traefik reverse proxy! # ports: # - "2342:2342" # HTTP port (host:container) labels: - "traefik.enable=true" - "traefik.http.services.photoprism.loadbalancer.server.port=2342" - "traefik.http.routers.photoprism.tls=true" - "traefik.http.routers.photoprism.entrypoints=websecure" ## !! REMOVE default route if your server has a public domain name !! - "traefik.http.routers.photoprism.rule=PathPrefix(`/`)" ## !! UNCOMMENT and CHANGE to set the public domain name !! # - "traefik.http.routers.photoprism.rule=Host(`photos.yourdomain.com`)" ## !! UNCOMMENT to enable Let's Encrypt HTTPS !! # - "traefik.http.routers.photoprism.tls.certresolver=myresolver" ## !! REMOVE both for Let's Encrypt HTTPS with default HTTP challenge (DNS challenge supports wildcards) !! - "traefik.http.routers.photoprism.tls.domains[0].main=example.com" - "traefik.http.routers.photoprism.tls.domains[0].sans=*.example.com" environment: ## !! CHANGE site url if your server has a public domain name e.g. "https://photos.yourdomain.com/" !! PHOTOPRISM_SITE_URL: "https://_public_ip_/" PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" PHOTOPRISM_ADMIN_PASSWORD: "_admin_password_" # YOUR INITIAL "admin" PASSWORD PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "gzip" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_DEBUG: "false" # run in debug mode (shows additional log messages) PHOTOPRISM_PUBLIC: "false" # no authentication required (disables password protection) PHOTOPRISM_READONLY: "false" # do not modify originals directory (reduced functionality) PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables Settings in Web UI PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive (requires TensorFlow) PHOTOPRISM_UPLOAD_NSFW: "true" # allows uploads that MAY be offensive PHOTOPRISM_DATABASE_DRIVER: "mysql" # use MariaDB 10.5+ or MySQL 8+ instead of SQLite for improved performance PHOTOPRISM_DATABASE_SERVER: "mariadb:3306" # MariaDB or MySQL database server (hostname:port) PHOTOPRISM_DATABASE_NAME: "photoprism" # MariaDB or MySQL database schema name PHOTOPRISM_DATABASE_USER: "photoprism" # MariaDB or MySQL database user name PHOTOPRISM_DATABASE_PASSWORD: "_admin_password_" # MariaDB or MySQL database user password ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clean): PHOTOPRISM_INIT: "update tensorflow clean" HOME: "/photoprism" working_dir: "/photoprism" ## Storage Folders: "~" is a shortcut for your home directory, "." for the current directory volumes: # "/host/folder:/photoprism/folder" # example: - "./originals:/photoprism/originals" # original media files (photos and videos) - "./import:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) - "./backup:/var/lib/photoprism" # *optional* storage folder for database backups ## Traefik Reverse Proxy (required) ## see https://docs.photoprism.app/getting-started/proxies/traefik/ traefik: restart: always image: traefik:v2.6 container_name: traefik ports: - "80:80" - "443:443" expose: - "80" - "443" volumes: - "/var/run/docker.sock:/var/run/docker.sock" - "./traefik/:/data/" - "./traefik.yaml:/etc/traefik/traefik.yaml" - "./certs/:/certs/" ## Database Server (recommended) ## see https://docs.photoprism.app/getting-started/faq/#should-i-use-sqlite-mariadb-or-mysql mariadb: restart: always image: mariadb:10.7 container_name: mariadb security_opt: - seccomp:unconfined - apparmor:unconfined command: mysqld --innodb-buffer-pool-size=128M --transaction-isolation=READ-COMMITTED --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --max-connections=512 --innodb-rollback-on-timeout=OFF --innodb-lock-wait-timeout=120 ## Never store database files on an unreliable device such as a USB flash drive, an SD card, or a shared network folder: volumes: - "./database:/var/lib/mysql" # important, do not remove environment: MARIADB_AUTO_UPGRADE: "1" MARIADB_INITDB_SKIP_TZINFO: "1" MARIADB_DATABASE: "photoprism" MARIADB_USER: "photoprism" MARIADB_PASSWORD: "_admin_password_" MARIADB_ROOT_PASSWORD: "_admin_password_" ## Ofelia Job Runner (recommended) ## see https://github.com/mcuadros/ofelia ofelia: restart: always image: mcuadros/ofelia:latest container_name: ofelia volumes: - "/var/run/docker.sock:/var/run/docker.sock:ro" - "./jobs.ini:/etc/ofelia/config.ini" ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower watchtower: restart: always image: containrrr/watchtower container_name: watchtower environment: WATCHTOWER_CLEANUP: "true" WATCHTOWER_POLL_INTERVAL: 86400 # checks for updates every day volumes: - "/var/run/docker.sock:/var/run/docker.sock"
docker/examples/cloud/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.16754114627838135, 0.01880212128162384, 0.00016090918506961316, 0.0004668758774641901, 0.045924048870801926 ]
{ "id": 7, "code_window": [ " PHOTOPRISM_SITE_DESCRIPTION: \"\"\n", " PHOTOPRISM_SITE_AUTHOR: \"\"\n", " ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clitools, clean):\n", " # PHOTOPRISM_INIT: \"gpu tensorflow\"\n", " HOME: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/macos/docker-compose.yml", "type": "replace", "edit_start_line_idx": 80 }
 Open Sans Italic 59392-59647
assets/static/font/Open Sans Italic/59392-59647.pbf
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0001627257006475702, 0.0001627257006475702, 0.0001627257006475702, 0.0001627257006475702, 0 ]
{ "id": 7, "code_window": [ " PHOTOPRISM_SITE_DESCRIPTION: \"\"\n", " PHOTOPRISM_SITE_AUTHOR: \"\"\n", " ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clitools, clean):\n", " # PHOTOPRISM_INIT: \"gpu tensorflow\"\n", " HOME: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/macos/docker-compose.yml", "type": "replace", "edit_start_line_idx": 80 }
 Open Sans Italic 10752-11007
assets/static/font/Open Sans Italic/10752-11007.pbf
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0001628122990950942, 0.0001628122990950942, 0.0001628122990950942, 0.0001628122990950942, 0 ]
{ "id": 7, "code_window": [ " PHOTOPRISM_SITE_DESCRIPTION: \"\"\n", " PHOTOPRISM_SITE_AUTHOR: \"\"\n", " ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clitools, clean):\n", " # PHOTOPRISM_INIT: \"gpu tensorflow\"\n", " HOME: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/macos/docker-compose.yml", "type": "replace", "edit_start_line_idx": 80 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M377.74 32H70.26C31.41 32 0 63.41 0 102.26v307.48C0 448.59 31.41 480 70.26 480h307.48c38.52 0 69.76-31.08 70.26-69.6-45.96-25.62-110.59-60.34-171.6-88.44-32.07 43.97-84.14 81-148.62 81-70.59 0-93.73-45.3-97.04-76.37-3.97-39.01 14.88-81.5 99.52-81.5 35.38 0 79.35 10.25 127.13 24.96 16.53-30.09 26.45-60.34 26.45-60.34h-178.2v-16.7h92.08v-31.24H88.28v-19.01h109.44V92.34h50.92v50.42h109.44v19.01H248.63v31.24h88.77s-15.21 46.62-38.35 90.92c48.93 16.7 100.01 36.04 148.62 52.74V102.26C447.83 63.57 416.43 32 377.74 32zM47.28 322.95c.99 20.17 10.25 53.73 69.93 53.73 52.07 0 92.58-39.68 117.87-72.9-44.63-18.68-84.48-31.41-109.44-31.41-67.45 0-79.35 33.06-78.36 50.58z"/></svg>
assets/static/brands/alipay.svg
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00016388481890317053, 0.00016388481890317053, 0.00016388481890317053, 0.00016388481890317053, 0 ]
{ "id": 8, "code_window": [ " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/scheduler/docker-compose.yml", "type": "replace", "edit_start_line_idx": 90 }
version: '3.5' # Example Docker Compose config file for PhotoPrism (Linux / AMD64) # # Note: # - Use SQLite only for small libraries and testing. SQLite locks the index on updates, so other operations have to # wait. In the worst case, this can lead to timeout errors. MariaDB is optimized for high concurrency. # - Running PhotoPrism on a server with less than 4 GB of swap space or setting a memory/swap limit can cause unexpected # restarts ("crashes"), for example, when the indexer temporarily needs more memory to process large files. # - If you install PhotoPrism on a public server outside your home network, please always run it behind a secure # HTTPS reverse proxy such as Traefik or Caddy. Your files and passwords will otherwise be transmitted # in clear text and can be intercepted by anyone, including your provider, hackers, and governments: # https://docs.photoprism.app/getting-started/proxies/traefik/ # # Documentation : https://docs.photoprism.app/getting-started/docker-compose/ # Docker Hub URL: https://hub.docker.com/r/photoprism/photoprism/ # # DOCKER COMPOSE COMMAND REFERENCE # see https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index # # All commands may have to be prefixed with "sudo" when not running as root. # This will point the home directory shortcut ~ to /root in volume mounts. services: photoprism: ## Use photoprism/photoprism:preview for testing preview builds: image: photoprism/photoprism:latest ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors # restart: unless-stopped security_opt: - seccomp:unconfined - apparmor:unconfined ports: - "2342:2342" # HTTP port (host:container) environment: PHOTOPRISM_ADMIN_PASSWORD: "insecure" # !!! PLEASE CHANGE YOUR INITIAL "admin" PASSWORD !!! PHOTOPRISM_SITE_URL: "http://localhost:2342/" # public server URL incl http:// or https:// and /path, :port is optional PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "gzip" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_DEBUG: "false" # run in debug mode (shows additional log messages) PHOTOPRISM_PUBLIC: "false" # no authentication required (disables password protection) PHOTOPRISM_READONLY: "false" # do not modify originals directory (reduced functionality) PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables settings UI and API PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive (requires TensorFlow) PHOTOPRISM_UPLOAD_NSFW: "true" # allows uploads that MAY be offensive PHOTOPRISM_DATABASE_DRIVER: "sqlite" # SQLite is an embedded database that doesn't require a server PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clitools, clean): # PHOTOPRISM_INIT: "gpu tensorflow" ## Run as a specific user, group, or with a custom umask (does not work together with "user:") # PHOTOPRISM_UID: 1000 # PHOTOPRISM_GID: 1000 # PHOTOPRISM_UMASK: 0000 HOME: "/photoprism" ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user) # user: "1000:1000" working_dir: "/photoprism" ## Storage Folders: "~" is a shortcut for your home directory, "." for the current directory volumes: # "/host/folder:/photoprism/folder" # example - "~/Pictures:/photoprism/originals" # original media files (photos and videos) # - "/example/family:/photoprism/originals/family" # *additional* media folders can be mounted like this # - "~/Import:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower # # watchtower: # restart: unless-stopped # image: containrrr/watchtower # environment: # WATCHTOWER_CLEANUP: "true" # WATCHTOWER_POLL_INTERVAL: 7200 # checks for updates every two hours # volumes: # - "/var/run/docker.sock:/var/run/docker.sock" # - "~/.docker/config.json:/config.json" # optional, for authentication if you have a Docker Hub account
docker/examples/sqlite/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.5414360165596008, 0.07298704236745834, 0.00016425433568656445, 0.0011360559146851301, 0.15920229256153107 ]
{ "id": 8, "code_window": [ " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/scheduler/docker-compose.yml", "type": "replace", "edit_start_line_idx": 90 }
<!DOCTYPE html> <html lang="en" data-color-mode="dark" data-light-theme="light" data-dark-theme="dark" class="overflow-y-hidden"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0{{if not .config.Settings.UI.Zoom }}, maximum-scale=1.0, user-scalable=no{{end}}"> <title>{{ .config.SiteTitle }}</title> {{template "favicons.tmpl" .}} <link rel="stylesheet" href="{{ .config.CssUri }}"> <link rel="manifest" href="{{ .config.ManifestUri }}" crossorigin="use-credentials"> <script> window.__CONFIG__ = {{ .config }}; </script> </head> <body class="{{ .config.Flags }} nojs"> {{template "app.tmpl" .}} <script src="{{ .config.JsUri }}"></script> </body> </html>
assets/templates/minimal.tmpl
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00017035641940310597, 0.00016790702647995204, 0.00016309137572534382, 0.00017027326975949109, 0.0000034053448416671017 ]
{ "id": 8, "code_window": [ " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/scheduler/docker-compose.yml", "type": "replace", "edit_start_line_idx": 90 }
 Open Sans Semibold 4864-5119
assets/static/font/Open Sans Semibold/4864-5119.pbf
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0001720059517538175, 0.0001720059517538175, 0.0001720059517538175, 0.0001720059517538175, 0 ]
{ "id": 8, "code_window": [ " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/scheduler/docker-compose.yml", "type": "replace", "edit_start_line_idx": 90 }
# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: [email protected]\n" "POT-Creation-Date: 2021-12-09 00:51+0000\n" "PO-Revision-Date: 2022-03-16 17:35+0000\n" "Last-Translator: cheehoong <[email protected]>\n" "Language-Team: Chinese (Traditional) <https://translate.photoprism.app/" "projects/photoprism/backend/zh_Hant/>\n" "Language: zh_TW\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" "X-Generator: Weblate 4.11.2\n" msgid "Unexpected error, please try again" msgstr "未知错误, 请重试" msgid "Invalid request" msgstr "无效请求" msgid "Changes could not be saved" msgstr "无法保存更改" msgid "Could not be deleted" msgstr "无法删除" #, c-format msgid "%s already exists" msgstr "%s 已存在" msgid "Not found" msgstr "未找到" msgid "File not found" msgstr "未找到文件" msgid "Selection not found" msgstr "未找到所选" msgid "Entity not found" msgstr "未找到實體" msgid "Account not found" msgstr "未找到账户" msgid "User not found" msgstr "未找到用户" msgid "Label not found" msgstr "未找到标签" msgid "Album not found" msgstr "未找到相册" msgid "Subject not found" msgstr "未找到主題" msgid "Person not found" msgstr "找不到人" msgid "Face not found" msgstr "找不到人臉" msgid "Not available in public mode" msgstr "公开模式中不可用" msgid "not available in read-only mode" msgstr "只读模式中不可用" msgid "Please log in and try again" msgstr "请登陆后重试" msgid "Upload might be offensive" msgstr "所上传文件可能会冒犯其他人" msgid "No items selected" msgstr "未选择任何项目" msgid "Failed creating file, please check permissions" msgstr "无法创建文件, 请检查权限" msgid "Failed creating folder, please check permissions" msgstr "无法创建目录, 请检查权限" msgid "Could not connect, please try again" msgstr "无法连接, 请重试" msgid "Invalid password, please try again" msgstr "无效密码, 请重试" msgid "Feature disabled" msgstr "特性已被禁用" msgid "No labels selected" msgstr "未选择标签" msgid "No albums selected" msgstr "未选择相册" msgid "No files available for download" msgstr "没有可供下载的文件" msgid "Failed to create zip file" msgstr "创建zip文件失败" msgid "Invalid credentials" msgstr "无效凭证" msgid "Invalid link" msgstr "无效链接" msgid "Invalid name" msgstr "名稱無效" msgid "Busy, please try again later" msgstr "忙,请稍后再试" msgid "Changes successfully saved" msgstr "更改已保存" msgid "Album created" msgstr "相册已创建" msgid "Album saved" msgstr "相册已保存" #, c-format msgid "Album %s deleted" msgstr "相册 %s 已被删除" msgid "Album contents cloned" msgstr "相册内容已被复制" msgid "File removed from stack" msgstr "文件已被移出" msgid "File deleted" msgstr "%u 檔案已刪除" #, c-format msgid "Selection added to %s" msgstr "所选项目已被加入 %s" #, c-format msgid "One entry added to %s" msgstr "已向 %s 添加一个条目" #, c-format msgid "%d entries added to %s" msgstr "%d个条目已被加入到%s" #, c-format msgid "One entry removed from %s" msgstr "已从 %s 移除一个条目" #, c-format msgid "%d entries removed from %s" msgstr "%d 个条目已被移除于 %s" msgid "Account created" msgstr "已创建账户" msgid "Account saved" msgstr "已保存账户" msgid "Account deleted" msgstr "已删除账户" msgid "Settings saved" msgstr "设置已保存" msgid "Password changed" msgstr "密码已修改" #, c-format msgid "Import completed in %d s" msgstr "导入成功, 共花费 %d 秒" msgid "Import canceled" msgstr "导入已被中止" #, c-format msgid "Indexing completed in %d s" msgstr "索引成功, 共花费 %d 秒" msgid "Indexing originals..." msgstr "索引原始文件..." #, c-format msgid "Indexing files in %s" msgstr "为 %s 中的文件创建索引" msgid "Indexing canceled" msgstr "索引已被中止" #, c-format msgid "Removed %d files and %d photos" msgstr "删除了 %d 个文件和 %d 张照片" #, c-format msgid "Moving files from %s" msgstr "正在从 %s 中移动文件" #, c-format msgid "Copying files from %s" msgstr "正在从 %s 中复制文件" msgid "Labels deleted" msgstr "删除的标签" msgid "Label saved" msgstr "已保存标签" msgid "Subject saved" msgstr "主題已保存" msgid "Subject deleted" msgstr "主題已刪除" msgid "Person saved" msgstr "已保存的人" msgid "Person deleted" msgstr "已刪除人員" #, c-format msgid "%d files uploaded in %d s" msgstr "已上传 %d 个文件, 耗时 %d 秒" msgid "Selection approved" msgstr "选择已批准" msgid "Selection archived" msgstr "所选项目已被归档" msgid "Selection restored" msgstr "所选项目已被恢复" msgid "Selection marked as private" msgstr "所选项目已被设为私有" msgid "Albums deleted" msgstr "已删除的专辑" #, c-format msgid "Zip created in %d s" msgstr "Zip文件创建成功, 耗时 %d 秒" msgid "Permanently deleted" msgstr "永久刪除" #~ msgid "Not found on server, deleted?" #~ msgstr "服务器上不存在此文件, 或已被删除?"
assets/locales/zh_TW/default.po
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0002529537014197558, 0.00017406851111445576, 0.00016880736802704632, 0.00017104964354075491, 0.000015537949366262183 ]
{ "id": 9, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/scheduler/docker-compose.yml", "type": "replace", "edit_start_line_idx": 93 }
version: '3.5' # Example Docker Compose config file for PhotoPrism (Linux / AMD64) # # Note: # - Running PhotoPrism on a server with less than 4 GB of swap space or setting a memory/swap limit can cause unexpected # restarts ("crashes"), for example, when the indexer temporarily needs more memory to process large files. # - If you install PhotoPrism on a public server outside your home network, please always run it behind a secure # HTTPS reverse proxy such as Traefik or Caddy. Your files and passwords will otherwise be transmitted # in clear text and can be intercepted by anyone, including your provider, hackers, and governments: # https://docs.photoprism.app/getting-started/proxies/traefik/ # # Documentation : https://docs.photoprism.app/getting-started/docker-compose/ # Docker Hub URL: https://hub.docker.com/r/photoprism/photoprism/ # # DOCKER COMPOSE COMMAND REFERENCE # see https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index # # All commands may have to be prefixed with "sudo" when not running as root. # This will point the home directory shortcut ~ to /root in volume mounts. services: photoprism: ## Use photoprism/photoprism:preview for testing preview builds: image: photoprism/photoprism:latest depends_on: - mariadb ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors # restart: unless-stopped security_opt: - seccomp:unconfined - apparmor:unconfined ports: - "2342:2342" # HTTP port (host:container) environment: PHOTOPRISM_ADMIN_PASSWORD: "insecure" # !!! PLEASE CHANGE YOUR INITIAL "admin" PASSWORD !!! PHOTOPRISM_SITE_URL: "http://localhost:2342/" # public server URL incl http:// or https:// and /path, :port is optional PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "gzip" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_DEBUG: "false" # run in debug mode (shows additional log messages) PHOTOPRISM_PUBLIC: "false" # no authentication required (disables password protection) PHOTOPRISM_READONLY: "false" # do not modify originals directory (reduced functionality) PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables settings UI and API PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive (requires TensorFlow) PHOTOPRISM_UPLOAD_NSFW: "true" # allows uploads that MAY be offensive # PHOTOPRISM_DATABASE_DRIVER: "sqlite" # SQLite is an embedded database that doesn't require a server PHOTOPRISM_DATABASE_DRIVER: "mysql" # use MariaDB 10.5+ or MySQL 8+ instead of SQLite for improved performance PHOTOPRISM_DATABASE_SERVER: "mariadb:3306" # MariaDB or MySQL database server (hostname:port) PHOTOPRISM_DATABASE_NAME: "photoprism" # MariaDB or MySQL database schema name PHOTOPRISM_DATABASE_USER: "photoprism" # MariaDB or MySQL database user name PHOTOPRISM_DATABASE_PASSWORD: "insecure" # MariaDB or MySQL database user password PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clitools, clean): # PHOTOPRISM_INIT: "gpu tensorflow" ## Hardware video transcoding config (optional) # PHOTOPRISM_FFMPEG_BUFFERS: "64" # FFmpeg capture buffers (default: 32) # PHOTOPRISM_FFMPEG_BITRATE: "32" # FFmpeg encoding bitrate limit in Mbit/s (default: 50) # PHOTOPRISM_FFMPEG_ENCODER: "h264_v4l2m2m" # use Video4Linux for AVC transcoding (default: libx264) # PHOTOPRISM_FFMPEG_ENCODER: "h264_qsv" # use Intel Quick Sync Video for AVC transcoding (default: libx264) ## Run as a specific user, group, or with a custom umask (does not work together with "user:") # PHOTOPRISM_UID: 1000 # PHOTOPRISM_GID: 1000 # PHOTOPRISM_UMASK: 0000 HOME: "/photoprism" ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user) # user: "1000:1000" ## Share hardware devices with FFmpeg and TensorFlow (optional): # devices: # - "/dev/dri:/dev/dri" # Intel (h264_qsv) # - "/dev/nvidia0:/dev/nvidia0" # Nvidia (h264_nvenc) # - "/dev/nvidiactl:/dev/nvidiactl" # - "/dev/nvidia-modeset:/dev/nvidia-modeset" # - "/dev/nvidia-nvswitchctl:/dev/nvidia-nvswitchctl" # - "/dev/nvidia-uvm:/dev/nvidia-uvm" # - "/dev/nvidia-uvm-tools:/dev/nvidia-uvm-tools" # - "/dev/video11:/dev/video11" # Video4Linux (h264_v4l2m2m) working_dir: "/photoprism" ## Storage Folders: "~" is a shortcut for your home directory, "." for the current directory volumes: # "/host/folder:/photoprism/folder" # example - "~/Pictures:/photoprism/originals" # original media files (photos and videos) # - "/example/family:/photoprism/originals/family" # *additional* media folders can be mounted like this # - "~/Import:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) ## Database Server (recommended) ## see https://docs.photoprism.app/getting-started/faq/#should-i-use-sqlite-mariadb-or-mysql mariadb: ## If MariaDB gets stuck in a restart loop, this points to a memory or filesystem issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors restart: unless-stopped image: mariadb:10.7 security_opt: - seccomp:unconfined - apparmor:unconfined command: mysqld --innodb-buffer-pool-size=128M --transaction-isolation=READ-COMMITTED --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --max-connections=512 --innodb-rollback-on-timeout=OFF --innodb-lock-wait-timeout=120 ## Never store database files on an unreliable device such as a USB flash drive, an SD card, or a shared network folder: volumes: - "./database:/var/lib/mysql" # important, do not remove environment: MARIADB_AUTO_UPGRADE: "1" MARIADB_INITDB_SKIP_TZINFO: "1" MARIADB_DATABASE: "photoprism" MARIADB_USER: "photoprism" MARIADB_PASSWORD: "insecure" MARIADB_ROOT_PASSWORD: "insecure" ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower # # watchtower: # restart: unless-stopped # image: containrrr/watchtower # environment: # WATCHTOWER_CLEANUP: "true" # WATCHTOWER_POLL_INTERVAL: 7200 # checks for updates every two hours # volumes: # - "/var/run/docker.sock:/var/run/docker.sock" # - "~/.docker/config.json:/config.json" # optional, for authentication if you have a Docker Hub account
docker/examples/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.19074857234954834, 0.03436058759689331, 0.00021035067038610578, 0.0024951596278697252, 0.0582016184926033 ]
{ "id": 9, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/scheduler/docker-compose.yml", "type": "replace", "edit_start_line_idx": 93 }
package sanitize import ( "testing" "github.com/stretchr/testify/assert" ) func TestSearchString(t *testing.T) { t.Run("Replace", func(t *testing.T) { q := SearchString("table spoon & usa | img% json OR BILL!\n") assert.Equal(t, "table spoon & usa | img* json OR BILL!", q) }) t.Run("AndOr", func(t *testing.T) { q := SearchString("Jens AND Mander and me Or Kitty AND ") assert.Equal(t, "Jens AND Mander and me Or Kitty AND ", q) }) t.Run("FlowersInThePark", func(t *testing.T) { q := SearchString(" Flowers in the Park ") assert.Equal(t, " Flowers in the Park ", q) }) } func TestSearchQuery(t *testing.T) { t.Run("Replace", func(t *testing.T) { q := SearchQuery("table spoon & usa | img% json OR BILL!\n") assert.Equal(t, "table spoon & usa | img* json|BILL!", q) }) t.Run("AndOr", func(t *testing.T) { q := SearchQuery("Jens AND Mander and me Or Kitty AND ") assert.Equal(t, "Jens&Mander&me|Kitty&", q) }) t.Run("FlowersInThePark", func(t *testing.T) { q := SearchQuery(" Flowers in the Park ") assert.Equal(t, "Flowers&the Park", q) }) }
pkg/sanitize/search_test.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00017751868290361017, 0.00017415428010281175, 0.00016946227697189897, 0.00017481809481978416, 0.0000030280418741313042 ]
{ "id": 9, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/scheduler/docker-compose.yml", "type": "replace", "edit_start_line_idx": 93 }
package entity import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/photoprism/photoprism/internal/face" "github.com/photoprism/photoprism/pkg/colors" "github.com/photoprism/photoprism/pkg/fs" ) func TestFirstFileByHash(t *testing.T) { t.Run("not existing file", func(t *testing.T) { f, err := FirstFileByHash("xxx") assert.EqualError(t, err, "record not found") assert.Equal(t, uint(0), f.ID) }) t.Run("existing file", func(t *testing.T) { f, err := FirstFileByHash("2cad9168fa6acc5c5c2965ddf6ec465ca42fd818") if err != nil { t.Fatal(err) } assert.Equal(t, uint(0xf4240), f.ID) }) } func TestFile_ShareFileName(t *testing.T) { t.Run("photo with title", func(t *testing.T) { photo := &Photo{TakenAtLocal: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC), PhotoTitle: "Berlin / Morning Mood"} file := &File{Photo: photo, FileType: "jpg", FileUID: "foobar345678765", FileHash: "e98eb86480a72bd585d228a709f0622f90e86cbc"} filename := file.ShareBase(0) assert.Contains(t, filename, "20190115-000000-Berlin-Morning-Mood") assert.Contains(t, filename, fs.JpegExt) }) t.Run("photo without title", func(t *testing.T) { photo := &Photo{TakenAtLocal: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC), PhotoTitle: ""} file := &File{Photo: photo, FileType: "jpg", PhotoUID: "123", FileUID: "foobar345678765", FileHash: "e98eb86480a72bd585d228a709f0622f90e86cbc"} filename := file.ShareBase(0) assert.Equal(t, filename, "e98eb86480a72bd585d228a709f0622f90e86cbc.jpg") }) t.Run("photo without photo", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileUID: "foobar345678765", FileHash: "e98eb86480a72bd585d228a709f0622f90e86cbc"} filename := file.ShareBase(0) assert.Equal(t, "e98eb86480a72bd585d228a709f0622f90e86cbc.jpg", filename) }) t.Run("file without photo", func(t *testing.T) { file := FileFixtures.Get("FileWithoutPhoto.mp4") filename := file.ShareBase(0) assert.Equal(t, "pcad9a68fa6acc5c5ba965adf6ec465ca42fd916.mp4", filename) }) t.Run("file hash < 8", func(t *testing.T) { photo := &Photo{TakenAtLocal: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC), PhotoTitle: "Berlin / Morning Mood"} file := &File{Photo: photo, FileType: "jpg", FileUID: "foobar345678765", FileHash: "e98"} filename := file.ShareBase(0) assert.NotContains(t, filename, "20190115-000000-Berlin-Morning-Mood") }) t.Run("no file uid", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileHash: "e98ijhyt"} filename := file.ShareBase(0) assert.Equal(t, filename, "e98ijhyt.jpg") }) } func TestFile_Changed(t *testing.T) { var deletedAt = time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC) t.Run("different modified times", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSize: 500, ModTime: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC).Unix()} d := time.Date(2020, 01, 15, 0, 0, 0, 0, time.UTC) assert.Equal(t, true, file.Changed(500, d)) }) t.Run("different sizes", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSize: 600, ModTime: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC).Unix()} d := time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC) assert.Equal(t, true, file.Changed(500, d)) }) t.Run("no change", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSize: 500, ModTime: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC).Unix()} d := time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC) assert.Equal(t, false, file.Changed(500, d)) }) t.Run("deleted", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSize: 500, ModTime: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC).Unix(), DeletedAt: &deletedAt} d := time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC) assert.Equal(t, false, file.Changed(500, d)) }) } func TestFile_Missing(t *testing.T) { var deletedAt = time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC) t.Run("deleted", func(t *testing.T) { file := &File{FileMissing: false, Photo: nil, FileType: "jpg", FileSize: 500, ModTime: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC).Unix(), DeletedAt: &deletedAt} assert.Equal(t, true, file.Missing()) }) t.Run("missing", func(t *testing.T) { file := &File{FileMissing: true, Photo: nil, FileType: "jpg", FileSize: 500, ModTime: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC).Unix(), DeletedAt: nil} assert.Equal(t, true, file.Missing()) }) t.Run("not_missing", func(t *testing.T) { file := &File{FileMissing: false, Photo: nil, FileType: "jpg", FileSize: 500, ModTime: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC).Unix(), DeletedAt: nil} assert.Equal(t, false, file.Missing()) }) } func TestFile_Create(t *testing.T) { t.Run("photo id == 0", func(t *testing.T) { file := File{PhotoID: 0} assert.Error(t, file.Create()) }) t.Run("file already exists", func(t *testing.T) { file := &File{PhotoID: 123, FileType: "jpg", FileSize: 500, ModTime: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC).Unix()} assert.Nil(t, file.Create()) assert.Error(t, file.Create()) }) t.Run("success", func(t *testing.T) { photo := &Photo{TakenAtLocal: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC), PhotoTitle: "Berlin / Morning Mood"} file := &File{Photo: photo, FileType: "jpg", FileSize: 500, PhotoID: 766, FileName: "testname", FileRoot: "xyz"} err := file.Create() if err != nil { t.Fatal(err) } }) } func TestFile_Purge(t *testing.T) { t.Run("success", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSize: 500} assert.Equal(t, nil, file.Purge()) }) } func TestFile_Found(t *testing.T) { t.Run("success", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSize: 500} assert.Equal(t, nil, file.Purge()) assert.Equal(t, true, file.FileMissing) err := file.Found() if err != nil { t.Fatal(err) } assert.Equal(t, false, file.FileMissing) }) } func TestFile_AllFilesMissing(t *testing.T) { t.Run("true", func(t *testing.T) { file := FileFixtures.Get("missing.jpg") assert.True(t, file.AllFilesMissing()) }) t.Run("false", func(t *testing.T) { file := FileFixtures.Get("Quality1FavoriteTrue.jpg") assert.False(t, file.AllFilesMissing()) }) } func TestFile_Save(t *testing.T) { t.Run("save without photo", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", PhotoUID: "123", FileUID: "123"} err := file.Save() if err == nil { t.Fatal("error should not be nil") } if file.ID != 0 { t.Fatalf("file id should be 0: %d", file.ID) } assert.Equal(t, "file 123: cannot save file with empty photo id", err.Error()) }) t.Run("success", func(t *testing.T) { photo := &Photo{TakenAtLocal: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC), PhotoTitle: "Berlin / Morning Mood"} file := &File{Photo: photo, FileType: "jpg", FileSize: 500, PhotoID: 766, FileName: "Food", FileRoot: "", UpdatedAt: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC)} err := file.Save() if err != nil { t.Fatal(err) } }) } func TestFile_UpdateVideoInfos(t *testing.T) { t.Run("success", func(t *testing.T) { file := &File{FileType: "jpg", FileWidth: 600, FileName: "VideoUpdate", PhotoID: 1000003} assert.Equal(t, "1990/04/bridge2.mp4", FileFixturesExampleBridgeVideo.FileName) assert.Equal(t, int(1200), FileFixturesExampleBridgeVideo.FileWidth) err := file.UpdateVideoInfos() if err != nil { t.Fatal(err) } var files Files if err := Db().Where("photo_id = ? AND file_video = 1", file.PhotoID).Find(&files).Error; err != nil { t.Fatal(err) } assert.Len(t, files, 1) for _, f := range files { assert.Equal(t, "1990/04/bridge2.mp4", f.FileName) assert.Equal(t, int(600), f.FileWidth) } }) } func TestFile_Update(t *testing.T) { t.Run("success", func(t *testing.T) { file := &File{FileType: "jpg", FileSize: 500, FileName: "ToBeUpdated", FileRoot: "", PhotoID: 5678} err := file.Save() if err != nil { t.Fatal(err) } assert.Equal(t, "ToBeUpdated", file.FileName) err2 := file.Update("FileName", "Happy") if err2 != nil { t.Fatal(err2) } assert.Equal(t, "Happy", file.FileName) }) } func TestFile_Links(t *testing.T) { t.Run("result", func(t *testing.T) { file := FileFixturesExampleBridge links := file.Links() assert.Equal(t, "5jxf3jfn2k", links[0].LinkToken) }) } func TestFile_NoJPEG(t *testing.T) { t.Run("true", func(t *testing.T) { file := &File{Photo: nil, FileType: "xmp", FileSize: 500} assert.True(t, file.NoJPEG()) }) t.Run("false", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSize: 500} assert.False(t, file.NoJPEG()) }) } func TestFile_Panorama(t *testing.T) { t.Run("3000", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSidecar: false, FileWidth: 3000, FileHeight: 1000} assert.True(t, file.Panorama()) }) t.Run("1999", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSidecar: false, FileWidth: 1999, FileHeight: 1000} assert.False(t, file.Panorama()) }) t.Run("2000", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSidecar: false, FileWidth: 2000, FileHeight: 1000} assert.True(t, file.Panorama()) }) t.Run("false", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSidecar: false, FileWidth: 1500, FileHeight: 1000} assert.False(t, file.Panorama()) }) t.Run("equirectangular", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSidecar: false, FileWidth: 1500, FileHeight: 1000, FileProjection: ProjEquirectangular} assert.True(t, file.Panorama()) }) t.Run("transverse-cylindrical", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSidecar: false, FileWidth: 1500, FileHeight: 1000, FileProjection: ProjTransverseCylindrical} assert.True(t, file.Panorama()) }) t.Run("sidecar", func(t *testing.T) { file := &File{Photo: nil, FileType: "xmp", FileSidecar: true, FileWidth: 3000, FileHeight: 1000} assert.False(t, file.Panorama()) }) } func TestFile_SetProjection(t *testing.T) { t.Run(ProjDefault, func(t *testing.T) { m := &File{} m.SetProjection(ProjDefault) assert.Equal(t, ProjDefault, m.FileProjection) }) t.Run(ProjCubestrip, func(t *testing.T) { m := &File{} m.SetProjection(ProjCubestrip) assert.Equal(t, ProjCubestrip, m.FileProjection) }) t.Run(ProjCylindrical, func(t *testing.T) { m := &File{} m.SetProjection(ProjCylindrical) assert.Equal(t, ProjCylindrical, m.FileProjection) }) t.Run(ProjTransverseCylindrical, func(t *testing.T) { m := &File{} m.SetProjection(ProjTransverseCylindrical) assert.Equal(t, ProjTransverseCylindrical, m.FileProjection) }) t.Run(ProjPseudocylindricalCompromise, func(t *testing.T) { m := &File{} m.SetProjection(ProjPseudocylindricalCompromise) assert.Equal(t, ProjPseudocylindricalCompromise, m.FileProjection) }) t.Run("Sanitize", func(t *testing.T) { m := &File{} m.SetProjection(" 幸福 Hanzi are logograms developed for the writing of Chinese! Expressions in an index may not ...!") assert.Equal(t, "hanzi are logograms developed for the writing of chinese! expres", m.FileProjection) assert.Equal(t, ClipStringType, len(m.FileProjection)) }) } func TestFile_Delete(t *testing.T) { t.Run("permanently", func(t *testing.T) { file := &File{FileType: "jpg", FileSize: 500, FileName: "ToBePermanentlyDeleted", FileRoot: "", PhotoID: 5678} err := file.Save() if err != nil { t.Fatal(err) } assert.Equal(t, "ToBePermanentlyDeleted", file.FileName) err2 := file.Delete(true) assert.Nil(t, err2) }) t.Run("not permanently", func(t *testing.T) { file := &File{FileType: "jpg", FileSize: 500, FileName: "ToBeDeleted", FileRoot: "", PhotoID: 5678} err := file.Save() if err != nil { t.Fatal(err) } assert.Equal(t, "ToBeDeleted", file.FileName) err2 := file.Delete(false) assert.Nil(t, err2) }) } func TestPrimaryFile(t *testing.T) { file, err := PrimaryFile("pt9jtdre2lvl0y17") if err != nil { t.Fatal(err) } assert.Equal(t, "Holiday/Video.jpg", file.FileName) } func TestFile_OriginalBase(t *testing.T) { t.Run("original name empty, filename empty", func(t *testing.T) { photo := &Photo{TakenAtLocal: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC), PhotoTitle: "Berlin / Morning Mood"} file := &File{Photo: photo, FileType: "jpg", FileUID: "foobar345678765", FileHash: "e98eb86480a72bd585d228a709f0622f90e86cbc", OriginalName: "", FileName: ""} filename := file.OriginalBase(0) assert.Contains(t, filename, "20190115-000000-Berlin-Morning-Mood") assert.Contains(t, filename, fs.JpegExt) filename2 := file.OriginalBase(1) assert.Contains(t, filename2, "20190115-000000-Berlin-Morning-Mood") assert.Contains(t, filename2, "(1)") assert.Contains(t, filename2, fs.JpegExt) }) t.Run("original name empty", func(t *testing.T) { photo := &Photo{TakenAtLocal: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC), PhotoTitle: "Berlin / Morning Mood"} file := &File{Photo: photo, FileType: "jpg", FileUID: "foobar345678765", FileHash: "e98eb86480a72bd585d228a709f0622f90e86cbc", OriginalName: "", FileName: "sonnenaufgang.jpg"} filename := file.OriginalBase(0) assert.Contains(t, filename, "sonnenaufgang") assert.Contains(t, filename, fs.JpegExt) filename2 := file.OriginalBase(1) assert.Contains(t, filename2, "sonnenaufgang") assert.Contains(t, filename2, "(1)") assert.Contains(t, filename2, fs.JpegExt) }) t.Run("original name not empty", func(t *testing.T) { photo := &Photo{TakenAtLocal: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC), PhotoTitle: "Berlin / Morning Mood"} file := &File{Photo: photo, FileType: "jpg", FileUID: "foobar345678765", FileHash: "e98eb86480a72bd585d228a709f0622f90e86cbc", OriginalName: "Sonnenaufgang.jpg", FileName: "123.jpg"} filename := file.OriginalBase(0) assert.Contains(t, filename, "Sonnenaufgang") assert.Contains(t, filename, fs.JpegExt) filename2 := file.OriginalBase(1) assert.Contains(t, filename2, "Sonnenaufgang") assert.Contains(t, filename2, "(1)") assert.Contains(t, filename2, fs.JpegExt) }) } func TestFile_DownloadName(t *testing.T) { t.Run("DownloadNameFile", func(t *testing.T) { photo := &Photo{TakenAtLocal: time.Date(2019, 01, 15, 0, 0, 0, 0, time.UTC), PhotoTitle: "Berlin / Morning Mood"} file := &File{Photo: photo, FileType: "jpg", FileUID: "foobar345678765", FileHash: "e98eb86480a72bd585d228a709f0622f90e86cbc", OriginalName: "originalName.jpg", FileName: "filename.jpg"} filename := file.DownloadName(DownloadNameFile, 0) assert.Contains(t, filename, "filename") assert.Contains(t, filename, fs.JpegExt) filename2 := file.DownloadName(DownloadNameOriginal, 1) assert.Contains(t, filename2, "originalName") assert.Contains(t, filename2, "(1)") assert.Contains(t, filename2, fs.JpegExt) filename3 := file.DownloadName("xxx", 0) assert.Contains(t, filename3, "20190115-000000-Berlin-Morning-Mood") }) } func TestFile_Undelete(t *testing.T) { t.Run("success", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSize: 500} assert.Equal(t, nil, file.Purge()) assert.Equal(t, true, file.FileMissing) err := file.Undelete() if err != nil { t.Fatal(err) } assert.Equal(t, false, file.FileMissing) }) t.Run("file not missing", func(t *testing.T) { file := &File{Photo: nil, FileType: "jpg", FileSize: 500} assert.Equal(t, false, file.FileMissing) err := file.Undelete() if err != nil { t.Fatal(err) } assert.Equal(t, false, file.FileMissing) }) } func TestFile_AddFaces(t *testing.T) { t.Run("Primary", func(t *testing.T) { file := &File{FileUID: "fqzuh65p4sjk3kdn", FileHash: "346b3897eec9ef75e35fbf0bbc4c83c55ca41e31", FileType: "jpg", FileWidth: 720, FileName: "FacesTest", PhotoID: 1000003, FilePrimary: true} faces := face.Faces{face.Face{ Rows: 480, Cols: 720, Score: 45, Area: face.NewArea("face", 250, 200, 10), Eyes: face.Areas{face.NewArea("eye_l", 240, 195, 1), face.NewArea("eye_r", 240, 205, 1)}, Landmarks: face.Areas{face.NewArea("a", 250, 185, 2), face.NewArea("b", 250, 215, 2)}, Embeddings: face.Embeddings{{0.012816238, 0.0054710666, 0.06963101, 0.037285835, 0.04412884, 0.017333193, 0.03373656, -0.033069234, 0.025952332, -0.0035901065, -0.029420156, 0.07464688, -0.043232113, 0.060328174, 0.028897963, -0.027495274, -0.02622295, 0.038605634, -0.030962847, 0.05343173, -0.05042871, 0.010407827, 0.014773584, 0.04305641, -0.045918103, 0.014705811, 0.0031296816, 0.08703609, 0.012646829, 0.040463835, 0.080548696, -0.04496776, 0.032542497, -0.046235666, 0.0018886769, -0.09422433, -0.006701393, 0.0601084, 0.05649471, -0.02277308, 0.048038833, -0.022022927, -0.024692882, -0.0067683067, 0.02597589, -0.026766079, -0.04489042, -0.060946267, 0.052194964, 0.0098239435, -0.063547, 0.008626338, -0.041202333, -0.057555206, -0.05206756, -0.007974572, -0.036597952, -0.04232167, 0.0064586936, 0.011131428, -0.076106876, -0.014716604, 0.027977718, 0.060634963, 0.0046368516, -0.035929997, -0.079733424, -0.051017676, -0.03521493, -0.0062531913, -0.030387852, 0.101194955, -0.027980363, -0.010152243, -0.005128962, -0.026926627, 0.008371125, -0.088778615, 0.022396773, -0.025815062, -0.0027552384, -0.049987435, -0.019902563, -0.024667386, 0.064883195, -0.010091326, -0.024541432, -0.03390568, -0.04975766, -0.05255319, 0.0462333, -0.062871166, 0.070803925, -0.020970127, 0.012365979, -0.048543453, 0.027297763, 0.02785581, 0.09220687, -0.021206442, 0.015040259, 0.11726589, 0.00079200073, 0.08544253, 0.08694455, -0.037786104, -0.09956117, 0.07473473, 0.086737245, 0.02916126, 0.0355523, 0.067868374, -0.056218974, 0.007066174, 0.046310645, -0.025015457, -0.019863142, -0.018884404, 0.00076502684, -0.0699868, 0.043558553, 0.11221989, -0.036503807, -0.07346668, 0.023614183, 0.008353507, 0.05629068, -0.05628395, -0.030611087, 0.013364313, -0.014508443, 0.013493559, 0.061809033, 0.06598724, -0.03538405, -0.08597677, -0.06253287, -0.032587055, 0.030790405, 0.031729434, 0.0349981, 0.09145327, 0.012044479, 0.09593962, -0.011460096, -0.014851449, -0.041916795, 0.0037967677, -0.028313408, -0.016944066, -0.023236271, 0.046519253, 0.09026307, -0.014203754, 0.0048228586, 0.012194195, -0.062746234, -0.02189861, -0.030368697, 0.004226377, -0.044146035, 0.04542304, 0.046805177, 0.03882082, -0.06006401, 0.06286592, 0.03714168, -0.011287339, -0.0129849315, 0.01757729, -0.031555075, 0.005606887, 0.0045785876, 0.031963747, 0.040269036, 0.033833507, -0.06477002, -0.0039275866, 0.079373375, 0.044617712, 0.012070597, -0.06322144, 0.011061547, -0.006825576, 0.033158936, -0.10063759, -0.016583988, 0.008227036, 0.05604638, -0.0039418507, 0.030264255, 0.006545456, -0.046788998, -0.06612186, 0.019110108, 0.010173552, -0.0015304928, -0.02745248, 0.08436771, -0.05111628, 0.03491268, -0.018905425, 0.009436589, -0.071091056, 0.06312779, 0.055885248, -0.008187491, 0.013967105, 0.049851406, -0.046775173, -0.05380721, -0.02520902, 0.048415728, -0.053037673, 0.08821214, -0.04349023, -0.002511317, -0.013129268, -0.04000359, -0.0100794975, -0.0659472, 0.044489317, -0.03651276, 0.0032823374, -0.004647774, -0.019675476, 0.11854173, 0.035627883, 0.015952459, -0.017490689, -0.009468227, -0.034936972, -0.0040077316, -0.014501512, -0.040732305, -0.004475036, 0.026295308, 0.11893579, -0.012221011, 0.01921595, 0.003704211, -0.00081420684, 0.031362444, 0.021526098, -0.03796045, -0.04051389, 0.08994492, 0.020430982, -0.13368618, 0.059530005, 0.02978135, -0.020171875, 0.07243986, 0.08047519, 0.014236827, 0.023928184, -0.056827813, 0.030533543, -0.01695773, 0.0019564428, 0.019315101, 0.048426118, 0.012069902, 0.014532966, 0.07157925, -0.00082132005, -0.03102693, 0.05207618, 0.033050887, -0.06816059, 0.037159886, 0.012156096, 0.0906456, 0.05786973, 0.021087963, -0.03615757, -0.0006905898, 0.0062891473, 0.054622658, -0.02605763, -0.050890833, -0.00017370642, -0.010385195, 0.022578984, 0.001822225, -0.045328267, 0.015035055, 0.05529688, 0.046605356, -0.0007772419, -0.09158666, -0.039371215, -0.0026332953, 0.022653094, 0.077683136, -0.027678892, -0.07956019, -0.08317627, 0.012950206, -0.04643972, 0.027308058, -0.007675166, 0.009162879, -0.0064983773, -0.0073145335, 0.041186735, -0.027793638, -0.00047516363, 0.014808601, 0.052241515, 0.07800082, 0.048793413, 0.018123679, 0.06639319, 0.0056572245, -0.0023089426, -0.0012806753, 0.07676211, -0.08715853, -0.02962473, -0.009583457, -0.028001878, -0.0037823156, 0.048585914, -0.017176645, -0.028013503, -0.04553737, -0.04014757, -0.012503475, -0.098679036, -0.031309552, -0.07011677, 0.0286711, -0.007448121, -0.03362688, 0.014612736, 0.006140878, 0.050224025, -0.03131365, 0.017277641, -0.012991993, -0.045904126, 0.006959225, 0.044762693, -0.0052471757, -0.009494742, 0.020247253, -0.025165197, -0.007513343, -0.007732138, -0.03059627, -0.027137207, 0.030832471, -0.0006397405, 0.026458293, 0.048394475, -0.014066572, -0.008397393, 0.030369336, -0.0018644024, -0.08373501, 0.02299318, 0.08410273, 0.03791566, 0.016693544, -0.022285318, -0.107647866, 0.008533737, 0.05805777, 0.063223496, 0.043848637, -0.033787355, 0.013578734, 0.020149017, 0.059982095, -0.016969858, 0.04481642, 0.027871825, 0.037242968, 0.04364479, -0.05280717, 0.008205654, -0.03536789, 0.020066299, 0.02891452, 0.029394835, 0.09834288, 0.03443311, 0.038843676, -0.023331352, -0.0022070059, 0.039741606, 0.033018216, 0.04989029, 0.035506245, 0.026467659, 0.034031004, 0.029856045, -0.06866382, -0.0496181, 0.063887335, -0.02873221, 0.024889331, 0.01833896, -0.010304041, -0.048351713, -0.083444275, -0.030584292, -0.092650875, 0.012108162, -0.022506258, 0.014489741, -0.037093587, -0.0041784635, 0.08624283, -0.012284314, -0.014817595, -0.0073567405, -0.013233772, -0.07208923, 0.049182527, -0.019994823, 0.006094942, -0.014795295, -0.017715558, -0.021894615, -0.01329216, 0.0032535691, -0.061918758, -0.0027641011, -0.04525581, 0.051380426, -0.027817326, 0.040541418, 0.020033667, 0.027792405, -0.059075374, 0.026320897, 0.012968171, -0.002865264, -0.017004456, 0.041212566, 0.0038082711, -0.08282011, -0.052709907, -0.041330304, 0.06054631, -0.08095043, 0.017253665, 0.066494696, -0.0356273, -0.059468318, 0.032792054, 0.10238864, 0.029640062, 0.06367693, -0.000065915876, -0.07408563, -0.035968937, -0.06602596, 0.024129247, 0.002624706, -0.0044429703, -0.038953166, -0.02367998, -0.009588521, 0.031618122, -0.063372254, 0.05579818, -0.00065322284, -0.012777491, -0.04045443, -0.015359356, -0.08424052, 0.016582847, 0.04319089, 0.03904139, -0.004957754, 0.03633682, 0.016728338, 0.0071737715, 0.07263827, -0.059946816, 0.020960696, 0.05819421, -0.0047716517, -0.00028777352, -0.044942997, 0.019640505, -0.0060415184, -0.009499886, 0.03395488, -0.05268878, -0.040615927, 0.05501862, 0.0143708, -0.084489234, -0.046911728, -0.04033474, 0.050277222, 0.04054947, 0.014454217, -0.023438897, -0.05800994, -0.029950928, 0.0032126154, 0.0017874262, 0.025801007, 0.08680619, 0.017868958, 0.0035924045, -0.04201902}}, }} file.AddFaces(faces) assert.Equal(t, 1, len(*file.Markers())) if err := file.Save(); err != nil { t.Fatal(err) } assert.Equal(t, false, file.FileMissing) assert.NotEmpty(t, file.FileUID) assert.NotEmpty(t, file.Markers()) }) t.Run("NoEmbeddings", func(t *testing.T) { file := &File{FileUID: "fqzuh65p4sjk3kd1", FileHash: "146b3897eec9ef75e35fbf0bbc4c83c55ca41e31", FileType: "jpg", FileWidth: 720, FileName: "FacesTest", PhotoID: 1000003, FilePrimary: false} faces := face.Faces{face.Face{ Rows: 480, Cols: 720, Score: 45, Area: face.NewArea("face", 250, 200, 10), Eyes: face.Areas{face.NewArea("eye_l", 240, 195, 1), face.NewArea("eye_r", 240, 205, 1)}, Landmarks: face.Areas{face.NewArea("a", 250, 185, 2), face.NewArea("b", 250, 215, 2)}, }} file.AddFaces(faces) assert.Equal(t, 0, len(*file.Markers())) }) } func TestFile_ValidFaceCount(t *testing.T) { t.Run("FileFixturesExampleBridge", func(t *testing.T) { file := FileFixturesExampleBridge result := file.ValidFaceCount() assert.GreaterOrEqual(t, result, 3) }) } func TestFile_Rename(t *testing.T) { t.Run("success", func(t *testing.T) { m := FileFixtures.Get("exampleFileName.jpg") assert.Equal(t, "2790/07/27900704_070228_D6D51B6C.jpg", m.FileName) assert.Equal(t, RootOriginals, m.FileRoot) assert.Equal(t, false, m.FileMissing) assert.Nil(t, m.DeletedAt) p := m.RelatedPhoto() assert.Equal(t, "2790/07", p.PhotoPath) assert.Equal(t, "27900704_070228_D6D51B6C", p.PhotoName) if err := m.Rename("x/y/newName.jpg", "newRoot", "x/y", "newBase"); err != nil { t.Fatal(err) } assert.Equal(t, "x/y/newName.jpg", m.FileName) assert.Equal(t, "newRoot", m.FileRoot) assert.Equal(t, false, m.FileMissing) assert.Nil(t, m.DeletedAt) assert.Equal(t, "x/y", p.PhotoPath) assert.Equal(t, "newBase", p.PhotoName) if err := m.Rename("2790/07/27900704_070228_D6D51B6C.jpg", RootOriginals, "2790/07", "27900704_070228_D6D51B6C"); err != nil { t.Fatal(err) } assert.Equal(t, "2790/07/27900704_070228_D6D51B6C.jpg", m.FileName) assert.Equal(t, RootOriginals, m.FileRoot) assert.Equal(t, false, m.FileMissing) assert.Nil(t, m.DeletedAt) assert.Equal(t, "2790/07", p.PhotoPath) assert.Equal(t, "27900704_070228_D6D51B6C", p.PhotoName) }) } func TestFile_SubjectNames(t *testing.T) { t.Run("Photo27.jpg", func(t *testing.T) { m := FileFixtures.Get("Photo27.jpg") names := m.SubjectNames() t.Log(len(names)) if len(names) != 1 { t.Errorf("there should be one name: %#v", names) } else { assert.Equal(t, "Actress A", names[0]) } }) t.Run("Video.jpg", func(t *testing.T) { m := FileFixtures.Get("Video.jpg") names := m.SubjectNames() t.Log(len(names)) if len(names) != 1 { t.Errorf("there should be one name: %#v", names) } else { assert.Equal(t, "Actor A", names[0]) } }) t.Run("bridge.jpg", func(t *testing.T) { m := FileFixtures.Get("bridge.jpg") names := m.SubjectNames() if len(names) != 2 { t.Errorf("two names expected: %#v", names) } else { assert.Equal(t, []string{"Corn McCornface", "Jens Mander"}, names) } }) } func TestFile_UnsavedMarkers(t *testing.T) { t.Run("bridge2.jpg", func(t *testing.T) { m := FileFixtures.Get("bridge2.jpg") assert.Equal(t, "ft2es49w15bnlqdw", m.FileUID) assert.False(t, m.UnsavedMarkers()) markers := m.Markers() assert.Equal(t, 1, m.ValidFaceCount()) assert.Equal(t, 1, markers.ValidFaceCount()) assert.Equal(t, 1, markers.DetectedFaceCount()) assert.False(t, m.UnsavedMarkers()) assert.False(t, markers.Unsaved()) newMarker := *NewMarker(m, cropArea1, "lt9k3pw1wowuy1c1", SrcManual, MarkerFace, 100, 65) markers.Append(newMarker) assert.Equal(t, 1, m.ValidFaceCount()) assert.Equal(t, 2, markers.ValidFaceCount()) assert.Equal(t, 1, markers.DetectedFaceCount()) assert.True(t, m.UnsavedMarkers()) assert.True(t, markers.Unsaved()) }) } func TestFile_ReplaceHash(t *testing.T) { t.Run("exampleFileName.jpg", func(t *testing.T) { m := FileFixtures.Get("exampleFileName.jpg") if err := m.ReplaceHash(""); err != nil { t.Fatal(err) } }) } func TestFile_SetHDR(t *testing.T) { t.Run("Success", func(t *testing.T) { m := FileFixtures.Get("exampleFileName.jpg") assert.Equal(t, false, m.IsHDR()) m.SetHDR(false) assert.Equal(t, false, m.IsHDR()) m.SetHDR(true) assert.Equal(t, true, m.IsHDR()) m.ResetHDR() assert.Equal(t, false, m.IsHDR()) }) } func TestFile_SetColorProfile(t *testing.T) { t.Run("DisplayP3", func(t *testing.T) { m := FileFixtures.Get("exampleFileName.jpg") assert.Equal(t, "", m.ColorProfile()) assert.True(t, m.HasColorProfile(colors.Default)) assert.False(t, m.HasColorProfile(colors.ProfileDisplayP3)) m.SetColorProfile(string(colors.ProfileDisplayP3)) assert.Equal(t, "Display P3", m.ColorProfile()) assert.False(t, m.HasColorProfile(colors.Default)) assert.True(t, m.HasColorProfile(colors.ProfileDisplayP3)) m.SetColorProfile("") assert.Equal(t, "Display P3", m.ColorProfile()) assert.False(t, m.HasColorProfile(colors.Default)) assert.True(t, m.HasColorProfile(colors.ProfileDisplayP3)) m.ResetColorProfile() assert.Equal(t, "", m.ColorProfile()) assert.True(t, m.HasColorProfile(colors.Default)) assert.False(t, m.HasColorProfile(colors.ProfileDisplayP3)) }) }
internal/entity/file_test.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00413940753787756, 0.00023125686857383698, 0.00016348963254131377, 0.00017306770314462483, 0.0004775264242198318 ]
{ "id": 9, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n", " # - \"/example/family:/photoprism/originals/family\" # *additional* media folders can be mounted like this\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/scheduler/docker-compose.yml", "type": "replace", "edit_start_line_idx": 93 }
 Open Sans Bold 36608-36863
assets/static/font/Open Sans Bold/36608-36863.pbf
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0001717119594104588, 0.0001717119594104588, 0.0001717119594104588, 0.0001717119594104588, 0 ]
{ "id": 10, "code_window": [ " # PHOTOPRISM_INIT: \"gpu tensorflow\"\n", " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/sqlite/docker-compose.yml", "type": "replace", "edit_start_line_idx": 83 }
version: '3.5' # Example Docker Compose config file for PhotoPrism (Linux / AMD64) # # Note: # - Running PhotoPrism on a server with less than 4 GB of swap space or setting a memory/swap limit can cause unexpected # restarts ("crashes"), for example, when the indexer temporarily needs more memory to process large files. # - If you install PhotoPrism on a public server outside your home network, please always run it behind a secure # HTTPS reverse proxy such as Traefik or Caddy. Your files and passwords will otherwise be transmitted # in clear text and can be intercepted by anyone, including your provider, hackers, and governments: # https://docs.photoprism.app/getting-started/proxies/traefik/ # # Documentation : https://docs.photoprism.app/getting-started/docker-compose/ # Docker Hub URL: https://hub.docker.com/r/photoprism/photoprism/ # # DOCKER COMPOSE COMMAND REFERENCE # see https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index # # All commands may have to be prefixed with "sudo" when not running as root. # This will point the home directory shortcut ~ to /root in volume mounts. services: photoprism: ## Use photoprism/photoprism:preview for testing preview builds: image: photoprism/photoprism:latest depends_on: - mariadb ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors # restart: unless-stopped security_opt: - seccomp:unconfined - apparmor:unconfined ports: - "2342:2342" # HTTP port (host:container) environment: PHOTOPRISM_ADMIN_PASSWORD: "insecure" # !!! PLEASE CHANGE YOUR INITIAL "admin" PASSWORD !!! PHOTOPRISM_SITE_URL: "http://localhost:2342/" # public server URL incl http:// or https:// and /path, :port is optional PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "gzip" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_DEBUG: "false" # run in debug mode (shows additional log messages) PHOTOPRISM_PUBLIC: "false" # no authentication required (disables password protection) PHOTOPRISM_READONLY: "false" # do not modify originals directory (reduced functionality) PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables settings UI and API PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive (requires TensorFlow) PHOTOPRISM_UPLOAD_NSFW: "true" # allows uploads that MAY be offensive # PHOTOPRISM_DATABASE_DRIVER: "sqlite" # SQLite is an embedded database that doesn't require a server PHOTOPRISM_DATABASE_DRIVER: "mysql" # use MariaDB 10.5+ or MySQL 8+ instead of SQLite for improved performance PHOTOPRISM_DATABASE_SERVER: "mariadb:3306" # MariaDB or MySQL database server (hostname:port) PHOTOPRISM_DATABASE_NAME: "photoprism" # MariaDB or MySQL database schema name PHOTOPRISM_DATABASE_USER: "photoprism" # MariaDB or MySQL database user name PHOTOPRISM_DATABASE_PASSWORD: "insecure" # MariaDB or MySQL database user password PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clitools, clean): # PHOTOPRISM_INIT: "gpu tensorflow" ## Hardware video transcoding config (optional) # PHOTOPRISM_FFMPEG_BUFFERS: "64" # FFmpeg capture buffers (default: 32) # PHOTOPRISM_FFMPEG_BITRATE: "32" # FFmpeg encoding bitrate limit in Mbit/s (default: 50) # PHOTOPRISM_FFMPEG_ENCODER: "h264_v4l2m2m" # use Video4Linux for AVC transcoding (default: libx264) # PHOTOPRISM_FFMPEG_ENCODER: "h264_qsv" # use Intel Quick Sync Video for AVC transcoding (default: libx264) ## Run as a specific user, group, or with a custom umask (does not work together with "user:") # PHOTOPRISM_UID: 1000 # PHOTOPRISM_GID: 1000 # PHOTOPRISM_UMASK: 0000 HOME: "/photoprism" ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user) # user: "1000:1000" ## Share hardware devices with FFmpeg and TensorFlow (optional): # devices: # - "/dev/dri:/dev/dri" # Intel (h264_qsv) # - "/dev/nvidia0:/dev/nvidia0" # Nvidia (h264_nvenc) # - "/dev/nvidiactl:/dev/nvidiactl" # - "/dev/nvidia-modeset:/dev/nvidia-modeset" # - "/dev/nvidia-nvswitchctl:/dev/nvidia-nvswitchctl" # - "/dev/nvidia-uvm:/dev/nvidia-uvm" # - "/dev/nvidia-uvm-tools:/dev/nvidia-uvm-tools" # - "/dev/video11:/dev/video11" # Video4Linux (h264_v4l2m2m) working_dir: "/photoprism" ## Storage Folders: "~" is a shortcut for your home directory, "." for the current directory volumes: # "/host/folder:/photoprism/folder" # example - "~/Pictures:/photoprism/originals" # original media files (photos and videos) # - "/example/family:/photoprism/originals/family" # *additional* media folders can be mounted like this # - "~/Import:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) ## Database Server (recommended) ## see https://docs.photoprism.app/getting-started/faq/#should-i-use-sqlite-mariadb-or-mysql mariadb: ## If MariaDB gets stuck in a restart loop, this points to a memory or filesystem issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors restart: unless-stopped image: mariadb:10.7 security_opt: - seccomp:unconfined - apparmor:unconfined command: mysqld --innodb-buffer-pool-size=128M --transaction-isolation=READ-COMMITTED --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --max-connections=512 --innodb-rollback-on-timeout=OFF --innodb-lock-wait-timeout=120 ## Never store database files on an unreliable device such as a USB flash drive, an SD card, or a shared network folder: volumes: - "./database:/var/lib/mysql" # important, do not remove environment: MARIADB_AUTO_UPGRADE: "1" MARIADB_INITDB_SKIP_TZINFO: "1" MARIADB_DATABASE: "photoprism" MARIADB_USER: "photoprism" MARIADB_PASSWORD: "insecure" MARIADB_ROOT_PASSWORD: "insecure" ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower # # watchtower: # restart: unless-stopped # image: containrrr/watchtower # environment: # WATCHTOWER_CLEANUP: "true" # WATCHTOWER_POLL_INTERVAL: 7200 # checks for updates every two hours # volumes: # - "/var/run/docker.sock:/var/run/docker.sock" # - "~/.docker/config.json:/config.json" # optional, for authentication if you have a Docker Hub account
docker/examples/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.20660002529621124, 0.030947787687182426, 0.000166294674272649, 0.0006481032469309866, 0.05634596571326256 ]
{ "id": 10, "code_window": [ " # PHOTOPRISM_INIT: \"gpu tensorflow\"\n", " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/sqlite/docker-compose.yml", "type": "replace", "edit_start_line_idx": 83 }
package form import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewAlbum(t *testing.T) { t.Run("success", func(t *testing.T) { var album = struct { AlbumTitle string AlbumDescription string AlbumNotes string AlbumOrder string AlbumTemplate string AlbumFavorite bool }{ AlbumTitle: "Foo", AlbumDescription: "bar", AlbumNotes: "test notes", AlbumOrder: "newest", AlbumTemplate: "default", AlbumFavorite: true, } r, err := NewAlbum(album) if err != nil { t.Fatal(err) } assert.Equal(t, "Foo", r.AlbumTitle) assert.Equal(t, "bar", r.AlbumDescription) assert.Equal(t, "test notes", r.AlbumNotes) assert.Equal(t, "newest", r.AlbumOrder) assert.Equal(t, "default", r.AlbumTemplate) assert.Equal(t, true, r.AlbumFavorite) }) }
internal/form/album_test.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00017746537923812866, 0.00017322371422778815, 0.00017140981799457222, 0.00017222370661329478, 0.000002202029691034113 ]
{ "id": 10, "code_window": [ " # PHOTOPRISM_INIT: \"gpu tensorflow\"\n", " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/sqlite/docker-compose.yml", "type": "replace", "edit_start_line_idx": 83 }
! Open Sans Semibold 38656-38911
assets/static/font/Open Sans Semibold/38656-38911.pbf
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0001708770141704008, 0.0001708770141704008, 0.0001708770141704008, 0.0001708770141704008, 0 ]
{ "id": 10, "code_window": [ " # PHOTOPRISM_INIT: \"gpu tensorflow\"\n", " ## Run as a specific user, group, or with a custom umask (does not work together with \"user:\")\n", " # PHOTOPRISM_UID: 1000\n", " # PHOTOPRISM_GID: 1000\n", " # PHOTOPRISM_UMASK: 0000\n", " HOME: \"/photoprism\"\n", " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/sqlite/docker-compose.yml", "type": "replace", "edit_start_line_idx": 83 }
! Open Sans Semibold 53760-54015
assets/static/font/Open Sans Semibold/53760-54015.pbf
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00017026449495460838, 0.00017026449495460838, 0.00017026449495460838, 0.00017026449495460838, 0 ]
{ "id": 11, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/sqlite/docker-compose.yml", "type": "replace", "edit_start_line_idx": 86 }
version: '3.5' # Example Docker Compose config file for PhotoPrism (Linux / AMD64) # # Note: # - Use SQLite only for small libraries and testing. SQLite locks the index on updates, so other operations have to # wait. In the worst case, this can lead to timeout errors. MariaDB is optimized for high concurrency. # - Running PhotoPrism on a server with less than 4 GB of swap space or setting a memory/swap limit can cause unexpected # restarts ("crashes"), for example, when the indexer temporarily needs more memory to process large files. # - If you install PhotoPrism on a public server outside your home network, please always run it behind a secure # HTTPS reverse proxy such as Traefik or Caddy. Your files and passwords will otherwise be transmitted # in clear text and can be intercepted by anyone, including your provider, hackers, and governments: # https://docs.photoprism.app/getting-started/proxies/traefik/ # # Documentation : https://docs.photoprism.app/getting-started/docker-compose/ # Docker Hub URL: https://hub.docker.com/r/photoprism/photoprism/ # # DOCKER COMPOSE COMMAND REFERENCE # see https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index # # All commands may have to be prefixed with "sudo" when not running as root. # This will point the home directory shortcut ~ to /root in volume mounts. services: photoprism: ## Use photoprism/photoprism:preview for testing preview builds: image: photoprism/photoprism:latest ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors # restart: unless-stopped security_opt: - seccomp:unconfined - apparmor:unconfined ports: - "2342:2342" # HTTP port (host:container) environment: PHOTOPRISM_ADMIN_PASSWORD: "insecure" # !!! PLEASE CHANGE YOUR INITIAL "admin" PASSWORD !!! PHOTOPRISM_SITE_URL: "http://localhost:2342/" # public server URL incl http:// or https:// and /path, :port is optional PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "gzip" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_DEBUG: "false" # run in debug mode (shows additional log messages) PHOTOPRISM_PUBLIC: "false" # no authentication required (disables password protection) PHOTOPRISM_READONLY: "false" # do not modify originals directory (reduced functionality) PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables settings UI and API PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive (requires TensorFlow) PHOTOPRISM_UPLOAD_NSFW: "true" # allows uploads that MAY be offensive PHOTOPRISM_DATABASE_DRIVER: "sqlite" # SQLite is an embedded database that doesn't require a server PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clitools, clean): # PHOTOPRISM_INIT: "gpu tensorflow" ## Run as a specific user, group, or with a custom umask (does not work together with "user:") # PHOTOPRISM_UID: 1000 # PHOTOPRISM_GID: 1000 # PHOTOPRISM_UMASK: 0000 HOME: "/photoprism" ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user) # user: "1000:1000" working_dir: "/photoprism" ## Storage Folders: "~" is a shortcut for your home directory, "." for the current directory volumes: # "/host/folder:/photoprism/folder" # example - "~/Pictures:/photoprism/originals" # original media files (photos and videos) # - "/example/family:/photoprism/originals/family" # *additional* media folders can be mounted like this # - "~/Import:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower # # watchtower: # restart: unless-stopped # image: containrrr/watchtower # environment: # WATCHTOWER_CLEANUP: "true" # WATCHTOWER_POLL_INTERVAL: 7200 # checks for updates every two hours # volumes: # - "/var/run/docker.sock:/var/run/docker.sock" # - "~/.docker/config.json:/config.json" # optional, for authentication if you have a Docker Hub account
docker/examples/sqlite/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.9944151639938354, 0.10238444805145264, 0.00028359604766592383, 0.005153949838131666, 0.2833684980869293 ]
{ "id": 11, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/sqlite/docker-compose.yml", "type": "replace", "edit_start_line_idx": 86 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M502.17 201.67C516.69 287.53 471.23 369.59 389 409.8c13 34.1-12.4 70.2-48.32 70.2a51.68 51.68 0 01-51.57-49c-6.44.19-64.2 0-76.33-.64A51.69 51.69 0 01159 479.92c-33.86-1.36-57.95-34.84-47-67.92-37.21-13.11-72.54-34.87-99.62-70.8-13-17.28-.48-41.8 20.84-41.8 46.31 0 32.22-54.17 43.15-110.26C94.8 95.2 193.12 32 288.09 32c102.48 0 197.15 70.67 214.08 169.67zM373.51 388.28c42-19.18 81.33-56.71 96.29-102.14 40.48-123.09-64.15-228-181.71-228-83.45 0-170.32 55.42-186.07 136-9.53 48.91 5 131.35-68.75 131.35C58.21 358.6 91.6 378.11 127 389.54c24.66-21.8 63.87-15.47 79.83 14.34 14.22 1 79.19 1.18 87.9.82a51.69 51.69 0 0178.78-16.42zM205.12 187.13c0-34.74 50.84-34.75 50.84 0s-50.84 34.74-50.84 0zm116.57 0c0-34.74 50.86-34.75 50.86 0s-50.86 34.75-50.86 0zm-122.61 70.69c-3.44-16.94 22.18-22.18 25.62-5.21l.06.28c4.14 21.42 29.85 44 64.12 43.07 35.68-.94 59.25-22.21 64.11-42.77 4.46-16.05 28.6-10.36 25.47 6-5.23 22.18-31.21 62-91.46 62.9-42.55 0-80.88-27.84-87.9-64.25z"/></svg>
assets/static/brands/waze.svg
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.000600042927544564, 0.000600042927544564, 0.000600042927544564, 0.000600042927544564, 0 ]
{ "id": 11, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/sqlite/docker-compose.yml", "type": "replace", "edit_start_line_idx": 86 }
package sanitize const ( EnOr = "or" EnAnd = "and" EnWith = "with" EnIn = "in" EnAt = "at" Empty = "" Space = " " Or = "|" And = "&" Plus = "+" SpacedPlus = Space + Plus + Space )
pkg/sanitize/const.go
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.0001693756930762902, 0.00016936278552748263, 0.00016934986342675984, 0.00016936278552748263, 1.291482654153242e-8 ]
{ "id": 11, "code_window": [ " ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user)\n", " # user: \"1000:1000\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: \"~\" is a shortcut for your home directory, \".\" for the current directory\n", " volumes:\n", " # \"/host/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/sqlite/docker-compose.yml", "type": "replace", "edit_start_line_idx": 86 }
 Open Sans Bold 60928-61183
assets/static/font/Open Sans Bold/60928-61183.pbf
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00016954018792603165, 0.00016954018792603165, 0.00016954018792603165, 0.00016954018792603165, 0 ]
{ "id": 12, "code_window": [ " PHOTOPRISM_DATABASE_PASSWORD: \"insecure\" # MariaDB or MySQL database user password\n", " PHOTOPRISM_SITE_TITLE: \"PhotoPrism\"\n", " PHOTOPRISM_SITE_CAPTION: \"AI-Powered Photos App\"\n", " PHOTOPRISM_SITE_DESCRIPTION: \"\"\n", " PHOTOPRISM_SITE_AUTHOR: \"\"\n", " HOME: \"/photoprism\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: use \"/\" not \"\\\" as separator, \"~\" is a shortcut for C:/user/{username}, \".\" for the current directory\n", " volumes:\n", " # \"C:/user/username/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n", " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/windows/docker-compose.yml", "type": "replace", "edit_start_line_idx": 83 }
version: '3.5' # Example Docker Compose config file for PhotoPrism (Linux / AMD64) # # Note: # - Running PhotoPrism on a server with less than 4 GB of swap space or setting a memory/swap limit can cause unexpected # restarts ("crashes"), for example, when the indexer temporarily needs more memory to process large files. # - If you install PhotoPrism on a public server outside your home network, please always run it behind a secure # HTTPS reverse proxy such as Traefik or Caddy. Your files and passwords will otherwise be transmitted # in clear text and can be intercepted by anyone, including your provider, hackers, and governments: # https://docs.photoprism.app/getting-started/proxies/traefik/ # # Documentation : https://docs.photoprism.app/getting-started/docker-compose/ # Docker Hub URL: https://hub.docker.com/r/photoprism/photoprism/ # # DOCKER COMPOSE COMMAND REFERENCE # see https://docs.photoprism.app/getting-started/docker-compose/#command-line-interface # -------------------------------------------------------------------------- # Start | docker-compose up -d # Stop | docker-compose stop # Update | docker-compose pull # Logs | docker-compose logs --tail=25 -f # Terminal | docker-compose exec photoprism bash # Help | docker-compose exec photoprism photoprism help # Config | docker-compose exec photoprism photoprism config # Reset | docker-compose exec photoprism photoprism reset # Backup | docker-compose exec photoprism photoprism backup -a -i # Restore | docker-compose exec photoprism photoprism restore -a -i # Index | docker-compose exec photoprism photoprism index # Reindex | docker-compose exec photoprism photoprism index -f # Import | docker-compose exec photoprism photoprism import # # To search originals for faces without a complete rescan: # docker-compose exec photoprism photoprism faces index # # All commands may have to be prefixed with "sudo" when not running as root. # This will point the home directory shortcut ~ to /root in volume mounts. services: photoprism: ## Use photoprism/photoprism:preview for testing preview builds: image: photoprism/photoprism:latest depends_on: - mariadb ## Don't enable automatic restarts until PhotoPrism has been properly configured and tested! ## If the service gets stuck in a restart loop, this points to a memory, filesystem, network, or database issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors # restart: unless-stopped security_opt: - seccomp:unconfined - apparmor:unconfined ports: - "2342:2342" # HTTP port (host:container) environment: PHOTOPRISM_ADMIN_PASSWORD: "insecure" # !!! PLEASE CHANGE YOUR INITIAL "admin" PASSWORD !!! PHOTOPRISM_SITE_URL: "http://localhost:2342/" # public server URL incl http:// or https:// and /path, :port is optional PHOTOPRISM_ORIGINALS_LIMIT: 5000 # file size limit for originals in MB (increase for high-res video) PHOTOPRISM_HTTP_COMPRESSION: "gzip" # improves transfer speed and bandwidth utilization (none or gzip) PHOTOPRISM_DEBUG: "false" # run in debug mode (shows additional log messages) PHOTOPRISM_PUBLIC: "false" # no authentication required (disables password protection) PHOTOPRISM_READONLY: "false" # do not modify originals directory (reduced functionality) PHOTOPRISM_EXPERIMENTAL: "false" # enables experimental features PHOTOPRISM_DISABLE_CHOWN: "false" # disables storage permission updates on startup PHOTOPRISM_DISABLE_WEBDAV: "false" # disables built-in WebDAV server PHOTOPRISM_DISABLE_SETTINGS: "false" # disables settings UI and API PHOTOPRISM_DISABLE_TENSORFLOW: "false" # disables all features depending on TensorFlow PHOTOPRISM_DISABLE_FACES: "false" # disables facial recognition PHOTOPRISM_DISABLE_CLASSIFICATION: "false" # disables image classification PHOTOPRISM_JPEG_QUALITY: 85 # image quality, a higher value reduces compression (25-100) PHOTOPRISM_RAW_PRESETS: "false" # enables RAW file converter presets (may reduce performance) PHOTOPRISM_DETECT_NSFW: "false" # flag photos as private that MAY be offensive (requires TensorFlow) PHOTOPRISM_UPLOAD_NSFW: "true" # allows uploads that MAY be offensive # PHOTOPRISM_DATABASE_DRIVER: "sqlite" # SQLite is an embedded database that doesn't require a server PHOTOPRISM_DATABASE_DRIVER: "mysql" # use MariaDB 10.5+ or MySQL 8+ instead of SQLite for improved performance PHOTOPRISM_DATABASE_SERVER: "mariadb:3306" # MariaDB or MySQL database server (hostname:port) PHOTOPRISM_DATABASE_NAME: "photoprism" # MariaDB or MySQL database schema name PHOTOPRISM_DATABASE_USER: "photoprism" # MariaDB or MySQL database user name PHOTOPRISM_DATABASE_PASSWORD: "insecure" # MariaDB or MySQL database user password PHOTOPRISM_SITE_TITLE: "PhotoPrism" PHOTOPRISM_SITE_CAPTION: "AI-Powered Photos App" PHOTOPRISM_SITE_DESCRIPTION: "" PHOTOPRISM_SITE_AUTHOR: "" ## Run/install on first startup (options: update, gpu, tensorflow, davfs, clitools, clean): # PHOTOPRISM_INIT: "gpu tensorflow" ## Hardware video transcoding config (optional) # PHOTOPRISM_FFMPEG_BUFFERS: "64" # FFmpeg capture buffers (default: 32) # PHOTOPRISM_FFMPEG_BITRATE: "32" # FFmpeg encoding bitrate limit in Mbit/s (default: 50) # PHOTOPRISM_FFMPEG_ENCODER: "h264_v4l2m2m" # use Video4Linux for AVC transcoding (default: libx264) # PHOTOPRISM_FFMPEG_ENCODER: "h264_qsv" # use Intel Quick Sync Video for AVC transcoding (default: libx264) ## Run as a specific user, group, or with a custom umask (does not work together with "user:") # PHOTOPRISM_UID: 1000 # PHOTOPRISM_GID: 1000 # PHOTOPRISM_UMASK: 0000 HOME: "/photoprism" ## Start as a non-root user (see https://docs.docker.com/engine/reference/run/#user) # user: "1000:1000" ## Share hardware devices with FFmpeg and TensorFlow (optional): # devices: # - "/dev/dri:/dev/dri" # Intel (h264_qsv) # - "/dev/nvidia0:/dev/nvidia0" # Nvidia (h264_nvenc) # - "/dev/nvidiactl:/dev/nvidiactl" # - "/dev/nvidia-modeset:/dev/nvidia-modeset" # - "/dev/nvidia-nvswitchctl:/dev/nvidia-nvswitchctl" # - "/dev/nvidia-uvm:/dev/nvidia-uvm" # - "/dev/nvidia-uvm-tools:/dev/nvidia-uvm-tools" # - "/dev/video11:/dev/video11" # Video4Linux (h264_v4l2m2m) working_dir: "/photoprism" ## Storage Folders: "~" is a shortcut for your home directory, "." for the current directory volumes: # "/host/folder:/photoprism/folder" # example - "~/Pictures:/photoprism/originals" # original media files (photos and videos) # - "/example/family:/photoprism/originals/family" # *additional* media folders can be mounted like this # - "~/Import:/photoprism/import" # *optional* base folder from which files can be imported to originals - "./storage:/photoprism/storage" # *writable* storage folder for cache, database, and sidecar files (never remove) ## Database Server (recommended) ## see https://docs.photoprism.app/getting-started/faq/#should-i-use-sqlite-mariadb-or-mysql mariadb: ## If MariaDB gets stuck in a restart loop, this points to a memory or filesystem issue: ## https://docs.photoprism.app/getting-started/troubleshooting/#fatal-server-errors restart: unless-stopped image: mariadb:10.7 security_opt: - seccomp:unconfined - apparmor:unconfined command: mysqld --innodb-buffer-pool-size=128M --transaction-isolation=READ-COMMITTED --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --max-connections=512 --innodb-rollback-on-timeout=OFF --innodb-lock-wait-timeout=120 ## Never store database files on an unreliable device such as a USB flash drive, an SD card, or a shared network folder: volumes: - "./database:/var/lib/mysql" # important, do not remove environment: MARIADB_AUTO_UPGRADE: "1" MARIADB_INITDB_SKIP_TZINFO: "1" MARIADB_DATABASE: "photoprism" MARIADB_USER: "photoprism" MARIADB_PASSWORD: "insecure" MARIADB_ROOT_PASSWORD: "insecure" ## Watchtower upgrades services automatically (optional) ## see https://docs.photoprism.app/getting-started/updates/#watchtower # # watchtower: # restart: unless-stopped # image: containrrr/watchtower # environment: # WATCHTOWER_CLEANUP: "true" # WATCHTOWER_POLL_INTERVAL: 7200 # checks for updates every two hours # volumes: # - "/var/run/docker.sock:/var/run/docker.sock" # - "~/.docker/config.json:/config.json" # optional, for authentication if you have a Docker Hub account
docker/examples/docker-compose.yml
1
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.35324257612228394, 0.05307188257575035, 0.00016701515414752066, 0.00912208016961813, 0.0900680422782898 ]
{ "id": 12, "code_window": [ " PHOTOPRISM_DATABASE_PASSWORD: \"insecure\" # MariaDB or MySQL database user password\n", " PHOTOPRISM_SITE_TITLE: \"PhotoPrism\"\n", " PHOTOPRISM_SITE_CAPTION: \"AI-Powered Photos App\"\n", " PHOTOPRISM_SITE_DESCRIPTION: \"\"\n", " PHOTOPRISM_SITE_AUTHOR: \"\"\n", " HOME: \"/photoprism\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: use \"/\" not \"\\\" as separator, \"~\" is a shortcut for C:/user/{username}, \".\" for the current directory\n", " volumes:\n", " # \"C:/user/username/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n", " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/windows/docker-compose.yml", "type": "replace", "edit_start_line_idx": 83 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M244.6 232.4c0 8.5-4.26 20.49-21.34 20.49h-19.61v-41.47h19.61c17.13 0 21.34 12.36 21.34 20.98zM448 32v448H0V32zM151.3 287.84c0-21.24-12.12-34.54-46.72-44.85-20.57-7.41-26-10.91-26-18.63s7-14.61 20.41-14.61c14.09 0 20.79 8.45 20.79 18.35h30.7l.19-.57c.5-19.57-15.06-41.65-51.12-41.65-23.37 0-52.55 10.75-52.55 38.29 0 19.4 9.25 31.29 50.74 44.37 17.26 6.15 21.91 10.4 21.91 19.48 0 15.2-19.13 14.23-19.47 14.23-20.4 0-25.65-9.1-25.65-21.9h-30.8l-.18.56c-.68 31.32 28.38 45.22 56.63 45.22 29.98 0 51.12-13.55 51.12-38.29zm125.38-55.63c0-25.3-18.43-45.46-53.42-45.46h-51.78v138.18h32.17v-47.36h19.61c30.25 0 53.42-15.95 53.42-45.36zM297.94 325L347 186.78h-31.09L268 325zm106.52-138.22h-31.09L325.46 325h29.94z"/></svg>
assets/static/brands/stackpath.svg
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00016697168757673353, 0.00016697168757673353, 0.00016697168757673353, 0.00016697168757673353, 0 ]
{ "id": 12, "code_window": [ " PHOTOPRISM_DATABASE_PASSWORD: \"insecure\" # MariaDB or MySQL database user password\n", " PHOTOPRISM_SITE_TITLE: \"PhotoPrism\"\n", " PHOTOPRISM_SITE_CAPTION: \"AI-Powered Photos App\"\n", " PHOTOPRISM_SITE_DESCRIPTION: \"\"\n", " PHOTOPRISM_SITE_AUTHOR: \"\"\n", " HOME: \"/photoprism\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: use \"/\" not \"\\\" as separator, \"~\" is a shortcut for C:/user/{username}, \".\" for the current directory\n", " volumes:\n", " # \"C:/user/username/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n", " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/windows/docker-compose.yml", "type": "replace", "edit_start_line_idx": 83 }
 Open Sans Bold 52480-52735
assets/static/font/Open Sans Bold/52480-52735.pbf
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00016685534501448274, 0.00016685534501448274, 0.00016685534501448274, 0.00016685534501448274, 0 ]
{ "id": 12, "code_window": [ " PHOTOPRISM_DATABASE_PASSWORD: \"insecure\" # MariaDB or MySQL database user password\n", " PHOTOPRISM_SITE_TITLE: \"PhotoPrism\"\n", " PHOTOPRISM_SITE_CAPTION: \"AI-Powered Photos App\"\n", " PHOTOPRISM_SITE_DESCRIPTION: \"\"\n", " PHOTOPRISM_SITE_AUTHOR: \"\"\n", " HOME: \"/photoprism\"\n", " working_dir: \"/photoprism\"\n", " ## Storage Folders: use \"/\" not \"\\\" as separator, \"~\" is a shortcut for C:/user/{username}, \".\" for the current directory\n", " volumes:\n", " # \"C:/user/username/folder:/photoprism/folder\" # example\n", " - \"~/Pictures:/photoprism/originals\" # original media files (photos and videos)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " HOME: \"/photoprism\" # do not change or remove\n", " working_dir: \"/photoprism\" # do not change or remove\n" ], "file_path": "docker/examples/windows/docker-compose.yml", "type": "replace", "edit_start_line_idx": 83 }
! Open Sans Semibold 64512-64767
assets/static/font/Open Sans Semibold/64512-64767.pbf
0
https://github.com/photoprism/photoprism/commit/772da6babacf53babb2c738ab2cf38fc1017dea7
[ 0.00016156643687281758, 0.00016156643687281758, 0.00016156643687281758, 0.00016156643687281758, 0 ]
{ "id": 0, "code_window": [ "\tisClient = flag.Bool(\"client\", false, \"Whether this certificate is for a client.\")\n", "\torg = flag.String(\"organization\", \"Juju org\", \"Organization for the cert.\")\n", "\toutCert = flag.String(\"out-cert\", \"cert.pem\", \"Output certificate file.\")\n", "\toutPriv = flag.String(\"out-priv\", \"priv.pem\", \"Output private key file.\")\n", "\tkeySize = flag.Int(\"key-size\", 1024, \"Size of the generated private key\")\n", ")\n", "\n", "func checkCmdLine() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = flag.Int(\"key-size\", 2048, \"Size of the generated private key\")\n" ], "file_path": "security/cmd/generate_cert/main.go", "type": "replace", "edit_start_line_idx": 46 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Provide a tool to generate X.509 CSR with different options. package main import ( "flag" "fmt" "io/ioutil" "istio.io/istio/security/pkg/pki/ca" "github.com/golang/glog" ) var ( host = flag.String("host", "", "Comma-separated hostnames and IPs to generate a certificate for.") org = flag.String("organization", "Juju org", "Organization for the cert.") outCsr = flag.String("out-csr", "csr.pem", "Output csr file.") outPriv = flag.String("out-priv", "priv.pem", "Output private key file.") keySize = flag.Int("key-size", 1024, "Size of the generated private key") ) func saveCreds(csrPem []byte, privPem []byte) { err := ioutil.WriteFile(*outCsr, csrPem, 0644) if err != nil { glog.Fatalf("Could not write output certificate request: %s.", err) } err = ioutil.WriteFile(*outPriv, privPem, 0600) if err != nil { glog.Fatalf("Could not write output private key: %s.", err) } } func main() { flag.Parse() csrPem, privPem, err := ca.GenCSR(ca.CertOptions{ Host: *host, Org: *org, RSAKeySize: *keySize, }) if err != nil { glog.Fatalf("Failed to generate CSR: %s.", err) } saveCreds(csrPem, privPem) fmt.Printf("Certificate and private files successfully saved in %s and %s\n", *outCsr, *outPriv) }
security/cmd/generate_csr/main.go
1
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.9987347722053528, 0.5608200430870056, 0.00017214739636983722, 0.9303103089332581, 0.4858657121658325 ]
{ "id": 0, "code_window": [ "\tisClient = flag.Bool(\"client\", false, \"Whether this certificate is for a client.\")\n", "\torg = flag.String(\"organization\", \"Juju org\", \"Organization for the cert.\")\n", "\toutCert = flag.String(\"out-cert\", \"cert.pem\", \"Output certificate file.\")\n", "\toutPriv = flag.String(\"out-priv\", \"priv.pem\", \"Output private key file.\")\n", "\tkeySize = flag.Int(\"key-size\", 1024, \"Size of the generated private key\")\n", ")\n", "\n", "func checkCmdLine() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = flag.Int(\"key-size\", 2048, \"Size of the generated private key\")\n" ], "file_path": "security/cmd/generate_cert/main.go", "type": "replace", "edit_start_line_idx": 46 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package runtime import ( "errors" "fmt" "strconv" "strings" "sync/atomic" "time" "github.com/golang/glog" "github.com/prometheus/client_golang/prometheus" adptTmpl "istio.io/api/mixer/v1/template" "istio.io/istio/mixer/pkg/attribute" "istio.io/istio/mixer/pkg/expr" ) // Rule represents a runtime view of cpb.Rule. type Rule struct { // Match condition from the original rule. match string // Actions are stored in runtime format. actions map[adptTmpl.TemplateVariety][]*Action // Rule is a top level config object and it has a unique name. // It is used here for informational purposes. name string // rtype is gathered from labels. rtype ResourceType } func (r Rule) String() string { return fmt.Sprintf("[name:<%s>, match:<%s>, type:%s, actions: %v", r.name, r.match, r.rtype, r.actions) } // resolver is the runtime view of the configuration database. type resolver struct { // evaluator evaluates selectors evaluator expr.PredicateEvaluator // identityAttribute defines which configuration scopes apply to a request. // default: target.service // The value of this attribute is expected to be a hostname of form "svc.$ns.suffix" identityAttribute string // defaultConfigNamespace defines the namespace that contains configuration defaults for istio. // This is distinct from the "default" namespace in K8s. // default: istio-default-config defaultConfigNamespace string // rules in the configuration database keyed by $namespace. rules map[string][]*Rule // refCount tracks the number requests currently using this // configuration. resolver state can be cleaned up when this count is 0. refCount int32 // id of the resolver for debugging. id int } // newResolver returns a Resolver. func newResolver(evaluator expr.PredicateEvaluator, identityAttribute string, defaultConfigNamespace string, rules map[string][]*Rule, id int) *resolver { return &resolver{ evaluator: evaluator, identityAttribute: identityAttribute, defaultConfigNamespace: defaultConfigNamespace, rules: rules, id: id, } } const ( // DefaultConfigNamespace holds istio wide configuration. DefaultConfigNamespace = "istio-system" // DefaultIdentityAttribute is attribute that defines config scopes. DefaultIdentityAttribute = "destination.service" // ContextProtocolAttributeName is the attribute that defines the protocol context. ContextProtocolAttributeName = "context.protocol" // ContextProtocolTCP defines constant for tcp protocol. ContextProtocolTCP = "tcp" // expectedResolvedActionsCount is used to preallocate slice for actions. expectedResolvedActionsCount = 10 ) // Resolve resolves the in memory configuration to a set of actions based on request attributes. // Resolution is performed in the following order // 1. Check rules from the defaultConfigNamespace -- these rules always apply // 2. Check rules from the target.service namespace func (r *resolver) Resolve(attrs attribute.Bag, variety adptTmpl.TemplateVariety) (ra Actions, err error) { nselected := 0 target := "unknown" var ns string start := time.Now() // increase refcount just before returning // only if there is no error. defer func() { if err == nil { r.incRefCount() } }() // monitoring info defer func() { lbls := prometheus.Labels{ targetStr: target, errorStr: strconv.FormatBool(err != nil), } resolveCounter.With(lbls).Inc() resolveDuration.With(lbls).Observe(time.Since(start).Seconds()) resolveRules.With(lbls).Observe(float64(nselected)) raLen := 0 if ra != nil { raLen = len(ra.Get()) } resolveActions.With(lbls).Observe(float64(raLen)) }() if target, ns, err = destAndNamespace(attrs, r.identityAttribute); err != nil { return nil, err } // at most this can have 2 elements. rulesArr := make([][]*Rule, 0, 2) // add default namespace if present rulesArr = appendRules(rulesArr, r.rules, r.defaultConfigNamespace) // If the destination namespace is different than the default namespace // add those rules too if r.defaultConfigNamespace != ns { rulesArr = appendRules(rulesArr, r.rules, ns) } else if glog.V(3) { glog.Infof("Resolve: skipping duplicate namespace %s", ns) } var res []*Action res, nselected, err = r.filterActions(rulesArr, attrs, variety) if err != nil { return nil, err } // TODO add dedupe + group actions by handler/template ra = &actions{a: res, done: r.decRefCount} return ra, nil } func appendRules(rulesArr [][]*Rule, rules map[string][]*Rule, ns string) [][]*Rule { if r := rules[ns]; r != nil { rulesArr = append(rulesArr, r) } else if glog.V(3) { glog.Infof("Resolve: no namespace config for %s", ns) } return rulesArr } // destAndNamespace extracts namespace from identity attribute. func destAndNamespace(attrs attribute.Bag, idAttr string) (dest string, ns string, err error) { attr, _ := attrs.Get(idAttr) if attr == nil { msg := fmt.Sprintf("%s identity not found in attributes%v", idAttr, attrs.Names()) glog.Warningf(msg) return "", "", errors.New(msg) } var ok bool if dest, ok = attr.(string); !ok { msg := fmt.Sprintf("%s identity must be string: %v", idAttr, attr) glog.Warningf(msg) return "", "", errors.New(msg) } splits := strings.SplitN(dest, ".", 3) // we only care about service and namespace. if len(splits) > 1 { ns = splits[1] } return dest, ns, nil } //filterActions filters rules based on template variety and selectors. func (r *resolver) filterActions(rulesArr [][]*Rule, attrs attribute.Bag, variety adptTmpl.TemplateVariety) ([]*Action, int, error) { res := make([]*Action, 0, expectedResolvedActionsCount) var selected bool nselected := 0 var err error ctxProtocol, _ := attrs.Get(ContextProtocolAttributeName) tcp := ctxProtocol == ContextProtocolTCP for _, rules := range rulesArr { for _, rule := range rules { act := rule.actions[variety] if act == nil { // do not evaluate match if there is no variety specific action there. continue } // default rtype is HTTP + Check|Report|Preprocess if tcp != rule.rtype.IsTCP() { if glog.V(4) { glog.Infof("filterActions: rule %s removed ctxProtocol=%s, type %s", rule.name, ctxProtocol, rule.rtype) } continue } // do not evaluate empty predicates. if len(rule.match) != 0 { if selected, err = r.evaluator.EvalPredicate(rule.match, attrs); err != nil { return nil, 0, err } if !selected { continue } } if glog.V(3) { glog.Infof("filterActions: rule %s selected %v", rule.name, rule.rtype) } nselected++ res = append(res, act...) } } return res, nselected, nil } func (r *resolver) incRefCount() { atomic.AddInt32(&r.refCount, 1) } func (r *resolver) decRefCount() { atomic.AddInt32(&r.refCount, -1) } // actions implements Actions interface. type actions struct { a []*Action done func() } func (a *actions) Get() []*Action { return a.a } func (a *actions) Done() { a.done() }
mixer/pkg/runtime/resolver.go
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.0001784527557902038, 0.00017192766244988889, 0.0001607604353921488, 0.00017325676162727177, 0.0000043466975512274075 ]
{ "id": 0, "code_window": [ "\tisClient = flag.Bool(\"client\", false, \"Whether this certificate is for a client.\")\n", "\torg = flag.String(\"organization\", \"Juju org\", \"Organization for the cert.\")\n", "\toutCert = flag.String(\"out-cert\", \"cert.pem\", \"Output certificate file.\")\n", "\toutPriv = flag.String(\"out-priv\", \"priv.pem\", \"Output private key file.\")\n", "\tkeySize = flag.Int(\"key-size\", 1024, \"Size of the generated private key\")\n", ")\n", "\n", "func checkCmdLine() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = flag.Int(\"key-size\", 2048, \"Size of the generated private key\")\n" ], "file_path": "security/cmd/generate_cert/main.go", "type": "replace", "edit_start_line_idx": 46 }
#!/bin/bash # Copyright 2017 Istio Authors # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ####################################### # # # e2e-suite # # # ####################################### # Exit immediately for non zero status set -e # Check unset variables set -u # Print commands set -x echo 'Running e2e no rbac, no auth Tests' ./prow/e2e-suite.sh "$@"
prow/e2e-suite-no_rbac-no_auth.sh
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00017713486158754677, 0.0001742244785418734, 0.0001689022028585896, 0.00017543041030876338, 0.0000031557651709590573 ]
{ "id": 0, "code_window": [ "\tisClient = flag.Bool(\"client\", false, \"Whether this certificate is for a client.\")\n", "\torg = flag.String(\"organization\", \"Juju org\", \"Organization for the cert.\")\n", "\toutCert = flag.String(\"out-cert\", \"cert.pem\", \"Output certificate file.\")\n", "\toutPriv = flag.String(\"out-priv\", \"priv.pem\", \"Output private key file.\")\n", "\tkeySize = flag.Int(\"key-size\", 1024, \"Size of the generated private key\")\n", ")\n", "\n", "func checkCmdLine() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = flag.Int(\"key-size\", 2048, \"Size of the generated private key\")\n" ], "file_path": "security/cmd/generate_cert/main.go", "type": "replace", "edit_start_line_idx": 46 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package na import ( "fmt" "github.com/golang/glog" "istio.io/istio/security/pkg/platform" "istio.io/istio/security/pkg/workload" ) // NodeAgent interface that should be implemented by // various platform specific node agents. type NodeAgent interface { Start() error } // NewNodeAgent is constructor for Node agent based on the provided Environment variable. func NewNodeAgent(cfg *Config) (NodeAgent, error) { if cfg == nil { return nil, fmt.Errorf("Nil configuration passed") } na := &nodeAgentInternal{ config: cfg, certUtil: CertUtilImpl{}, } if pc, err := platform.NewClient(cfg.Env, cfg.PlatformConfig, cfg.IstioCAAddress); err == nil { na.pc = pc } else { return nil, err } cAClient := &cAGrpcClientImpl{} na.cAClient = cAClient // TODO: Specify files for service identity cert/key instead of node agent files. secretServer, err := workload.NewSecretServer( workload.NewSecretFileServerConfig(cfg.PlatformConfig.CertChainFile, cfg.PlatformConfig.KeyFile)) if err != nil { glog.Fatalf("Workload IO creation error: %v", err) } na.secretServer = secretServer return na, nil }
security/cmd/node_agent/na/nafactory.go
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.0004949517897330225, 0.00022715881641488522, 0.0001678403641562909, 0.00017483523697592318, 0.00011980531417066231 ]
{ "id": 1, "code_window": [ "\torg = flag.String(\"organization\", \"Juju org\", \"Organization for the cert.\")\n", "\toutCsr = flag.String(\"out-csr\", \"csr.pem\", \"Output csr file.\")\n", "\toutPriv = flag.String(\"out-priv\", \"priv.pem\", \"Output private key file.\")\n", "\tkeySize = flag.Int(\"key-size\", 1024, \"Size of the generated private key\")\n", ")\n", "\n", "func saveCreds(csrPem []byte, privPem []byte) {\n", "\terr := ioutil.WriteFile(*outCsr, csrPem, 0644)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = flag.Int(\"key-size\", 2048, \"Size of the generated private key\")\n" ], "file_path": "security/cmd/generate_csr/main.go", "type": "replace", "edit_start_line_idx": 33 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package controller import ( "bytes" "fmt" "reflect" "time" "github.com/golang/glog" "istio.io/istio/security/pkg/pki" "istio.io/istio/security/pkg/pki/ca" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" corev1 "k8s.io/client-go/kubernetes/typed/core/v1" "k8s.io/api/core/v1" "k8s.io/client-go/tools/cache" ) /* #nosec: disable gas linter */ const ( // The Istio secret annotation type IstioSecretType = "istio.io/key-and-cert" // The ID/name for the certificate chain file. CertChainID = "cert-chain.pem" // The ID/name for the private key file. PrivateKeyID = "key.pem" // The ID/name for the CA root certificate file. RootCertID = "root-cert.pem" secretNamePrefix = "istio." secretResyncPeriod = time.Minute serviceAccountNameAnnotationKey = "istio.io/service-account.name" // The size of a private key for a leaf certificate. keySize = 1024 ) // SecretController manages the service accounts' secrets that contains Istio keys and certificates. type SecretController struct { ca ca.CertificateAuthority core corev1.CoreV1Interface // Controller and store for service account objects. saController cache.Controller saStore cache.Store // Controller and store for secret objects. scrtController cache.Controller scrtStore cache.Store } // NewSecretController returns a pointer to a newly constructed SecretController instance. func NewSecretController(ca ca.CertificateAuthority, core corev1.CoreV1Interface, namespace string) *SecretController { c := &SecretController{ ca: ca, core: core, } saLW := &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return core.ServiceAccounts(namespace).List(options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return core.ServiceAccounts(namespace).Watch(options) }, } rehf := cache.ResourceEventHandlerFuncs{ AddFunc: c.saAdded, DeleteFunc: c.saDeleted, UpdateFunc: c.saUpdated, } c.saStore, c.saController = cache.NewInformer(saLW, &v1.ServiceAccount{}, time.Minute, rehf) istioSecretSelector := fields.SelectorFromSet(map[string]string{"type": IstioSecretType}).String() scrtLW := &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { options.FieldSelector = istioSecretSelector return core.Secrets(namespace).List(options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { options.FieldSelector = istioSecretSelector return core.Secrets(namespace).Watch(options) }, } c.scrtStore, c.scrtController = cache.NewInformer(scrtLW, &v1.Secret{}, secretResyncPeriod, cache.ResourceEventHandlerFuncs{ DeleteFunc: c.scrtDeleted, UpdateFunc: c.scrtUpdated, }) return c } // Run starts the SecretController until stopCh is closed. func (sc *SecretController) Run(stopCh chan struct{}) { go sc.scrtController.Run(stopCh) go sc.saController.Run(stopCh) } // Handles the event where a service account is added. func (sc *SecretController) saAdded(obj interface{}) { acct := obj.(*v1.ServiceAccount) sc.upsertSecret(acct.GetName(), acct.GetNamespace()) } // Handles the event where a service account is deleted. func (sc *SecretController) saDeleted(obj interface{}) { acct := obj.(*v1.ServiceAccount) sc.deleteSecret(acct.GetName(), acct.GetNamespace()) } // Handles the event where a service account is updated. func (sc *SecretController) saUpdated(oldObj, curObj interface{}) { if reflect.DeepEqual(oldObj, curObj) { // Nothing is changed. The method is invoked by periodical re-sync with the apiserver. return } oldSa := oldObj.(*v1.ServiceAccount) curSa := curObj.(*v1.ServiceAccount) curName := curSa.GetName() curNamespace := curSa.GetNamespace() oldName := oldSa.GetName() oldNamespace := oldSa.GetNamespace() // We only care the name and namespace of a service account. if curName != oldName || curNamespace != oldNamespace { sc.deleteSecret(oldName, oldNamespace) sc.upsertSecret(curName, curNamespace) glog.Infof("Service account \"%s\" in namespace \"%s\" has been updated to \"%s\" in namespace \"%s\"", oldName, oldNamespace, curName, curNamespace) } } func (sc *SecretController) upsertSecret(saName, saNamespace string) { secret := &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{serviceAccountNameAnnotationKey: saName}, Name: getSecretName(saName), Namespace: saNamespace, }, Type: IstioSecretType, } _, exists, err := sc.scrtStore.Get(secret) if err != nil { glog.Errorf("Failed to get secret from the store (error %v)", err) } if exists { // Do nothing for existing secrets. Rotating expiring certs are handled by the `scrtUpdated` method. return } // Now we know the secret does not exist yet. So we create a new one. chain, key, err := sc.generateKeyAndCert(saName, saNamespace) if err != nil { glog.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)", saName, saNamespace, err) return } rootCert := sc.ca.GetRootCertificate() secret.Data = map[string][]byte{ CertChainID: chain, PrivateKeyID: key, RootCertID: rootCert, } _, err = sc.core.Secrets(saNamespace).Create(secret) if err != nil { glog.Errorf("Failed to create secret (error: %s)", err) return } glog.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been created", saName, saNamespace) } func (sc *SecretController) deleteSecret(saName, saNamespace string) { err := sc.core.Secrets(saNamespace).Delete(getSecretName(saName), nil) // kube-apiserver returns NotFound error when the secret is successfully deleted. if err == nil || errors.IsNotFound(err) { glog.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been deleted", saName, saNamespace) return } glog.Errorf("Failed to delete Istio secret for service account \"%s\" in namespace \"%s\" (error: %s)", saName, saNamespace, err) } func (sc *SecretController) scrtDeleted(obj interface{}) { scrt, ok := obj.(*v1.Secret) if !ok { glog.Warning("Failed to convert to secret object: %v", obj) return } glog.Infof("Re-create deleted Istio secret") saName := scrt.Annotations[serviceAccountNameAnnotationKey] sc.upsertSecret(saName, scrt.GetNamespace()) } func (sc *SecretController) generateKeyAndCert(saName string, saNamespace string) ([]byte, []byte, error) { id := fmt.Sprintf("%s://cluster.local/ns/%s/sa/%s", ca.URIScheme, saNamespace, saName) options := ca.CertOptions{ Host: id, RSAKeySize: keySize, } csrPEM, keyPEM, err := ca.GenCSR(options) if err != nil { return nil, nil, err } certPEM, err := sc.ca.Sign(csrPEM) if err != nil { return nil, nil, err } return certPEM, keyPEM, nil } func (sc *SecretController) scrtUpdated(oldObj, newObj interface{}) { scrt, ok := newObj.(*v1.Secret) if !ok { glog.Warning("Failed to convert to secret object: %v", newObj) return } certBytes := scrt.Data[CertChainID] cert, err := pki.ParsePemEncodedCertificate(certBytes) if err != nil { // TODO: we should refresh secret in this case since the secret contains an // invalid cert. glog.Error(err) return } ttl := time.Until(cert.NotAfter) rootCertificate := sc.ca.GetRootCertificate() // Refresh the secret if 1) the certificate contained in the secret is about // to expire, or 2) the root certificate in the secret is different than the // one held by the ca (this may happen when the CA is restarted and // a new self-signed CA cert is generated). if ttl.Seconds() < secretResyncPeriod.Seconds() || !bytes.Equal(rootCertificate, scrt.Data[RootCertID]) { namespace := scrt.GetNamespace() name := scrt.GetName() glog.Infof("Refreshing secret %s/%s, either the leaf certificate is about to expire "+ "or the root certificate is outdated", namespace, name) saName := scrt.Annotations[serviceAccountNameAnnotationKey] chain, key, err := sc.generateKeyAndCert(saName, namespace) if err != nil { glog.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)", saName, namespace, err) return } scrt.Data[CertChainID] = chain scrt.Data[PrivateKeyID] = key scrt.Data[RootCertID] = rootCertificate if _, err = sc.core.Secrets(namespace).Update(scrt); err != nil { glog.Errorf("Failed to update secret %s/%s (error: %s)", namespace, name, err) } } } func getSecretName(saName string) string { return secretNamePrefix + saName }
security/pkg/pki/ca/controller/secret.go
1
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.03525899350643158, 0.0016418804880231619, 0.0001606612786417827, 0.00017270831449422985, 0.006319957319647074 ]
{ "id": 1, "code_window": [ "\torg = flag.String(\"organization\", \"Juju org\", \"Organization for the cert.\")\n", "\toutCsr = flag.String(\"out-csr\", \"csr.pem\", \"Output csr file.\")\n", "\toutPriv = flag.String(\"out-priv\", \"priv.pem\", \"Output private key file.\")\n", "\tkeySize = flag.Int(\"key-size\", 1024, \"Size of the generated private key\")\n", ")\n", "\n", "func saveCreds(csrPem []byte, privPem []byte) {\n", "\terr := ioutil.WriteFile(*outCsr, csrPem, 0644)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = flag.Int(\"key-size\", 2048, \"Size of the generated private key\")\n" ], "file_path": "security/cmd/generate_csr/main.go", "type": "replace", "edit_start_line_idx": 33 }
errors during parsing: Error: mixer/tools/codegen/pkg/interfacegen/testdata/ErrorTemplate.proto: package name missing. Error: mixer/tools/codegen/pkg/interfacegen/testdata/ErrorTemplate.proto: message 'Template' not defined.
mixer/tools/codegen/pkg/interfacegen/testdata/ErrorTemplate.baseline
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00016887416131794453, 0.00016887416131794453, 0.00016887416131794453, 0.00016887416131794453, 0 ]
{ "id": 1, "code_window": [ "\torg = flag.String(\"organization\", \"Juju org\", \"Organization for the cert.\")\n", "\toutCsr = flag.String(\"out-csr\", \"csr.pem\", \"Output csr file.\")\n", "\toutPriv = flag.String(\"out-priv\", \"priv.pem\", \"Output private key file.\")\n", "\tkeySize = flag.Int(\"key-size\", 1024, \"Size of the generated private key\")\n", ")\n", "\n", "func saveCreds(csrPem []byte, privPem []byte) {\n", "\terr := ioutil.WriteFile(*outCsr, csrPem, 0644)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = flag.Int(\"key-size\", 2048, \"Size of the generated private key\")\n" ], "file_path": "security/cmd/generate_csr/main.go", "type": "replace", "edit_start_line_idx": 33 }
# gazelle:ignore package(default_visibility = ["//visibility:public"]) load("@io_bazel_rules_go//go:def.bzl", "go_library") load("//mixer/adapter:inventory.bzl", "inventory_library") inventory_library( name = "go_default_library", packages = { "denier": "istio.io/istio/mixer/adapter/denier", "list": "istio.io/istio/mixer/adapter/list", "noop": "istio.io/istio/mixer/adapter/noop", "prometheus": "istio.io/istio/mixer/adapter/prometheus", "stackdriver": "istio.io/istio/mixer/adapter/stackdriver", "statsd": "istio.io/istio/mixer/adapter/statsd", "stdio": "istio.io/istio/mixer/adapter/stdio", "svcctrl": "istio.io/istio/mixer/adapter/svcctrl", "memquota": "istio.io/istio/mixer/adapter/memquota", }, deps = [ "//mixer/adapter/denier:go_default_library", "//mixer/adapter/list:go_default_library", "//mixer/adapter/memquota:go_default_library", "//mixer/adapter/noop:go_default_library", "//mixer/adapter/prometheus:go_default_library", "//mixer/adapter/stackdriver:go_default_library", "//mixer/adapter/statsd:go_default_library", "//mixer/adapter/stdio:go_default_library", "//mixer/adapter/svcctrl:go_default_library", ], )
mixer/adapter/BUILD
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00017612334340810776, 0.0001734448887873441, 0.00017065767315216362, 0.00017349925474263728, 0.000002231189000667655 ]
{ "id": 1, "code_window": [ "\torg = flag.String(\"organization\", \"Juju org\", \"Organization for the cert.\")\n", "\toutCsr = flag.String(\"out-csr\", \"csr.pem\", \"Output csr file.\")\n", "\toutPriv = flag.String(\"out-priv\", \"priv.pem\", \"Output private key file.\")\n", "\tkeySize = flag.Int(\"key-size\", 1024, \"Size of the generated private key\")\n", ")\n", "\n", "func saveCreds(csrPem []byte, privPem []byte) {\n", "\terr := ioutil.WriteFile(*outCsr, csrPem, 0644)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = flag.Int(\"key-size\", 2048, \"Size of the generated private key\")\n" ], "file_path": "security/cmd/generate_csr/main.go", "type": "replace", "edit_start_line_idx": 33 }
--- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: servicegraph namespace: istio-system annotations: sidecar.istio.io/inject: "false" spec: replicas: 1 template: metadata: labels: app: servicegraph spec: containers: - name: servicegraph image: gcr.io/istio-testing/servicegraph:5253b6b574a98b209c0ef3d0d6e90c1b8d6a5c2a ports: - containerPort: 8088 args: - --prometheusAddr=http://prometheus:9090 --- apiVersion: v1 kind: Service metadata: name: servicegraph namespace: istio-system spec: ports: - name: http port: 8088 selector: app: servicegraph ---
install/kubernetes/addons/servicegraph.yaml
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.0001766839559422806, 0.00017576325626578182, 0.00017497157386969775, 0.00017569874762557447, 6.204010674082383e-7 ]
{ "id": 2, "code_window": [ "\n", "\tflags := rootCmd.Flags()\n", "\n", "\tflags.StringVar(&naConfig.ServiceIdentityOrg, \"org\", \"\", \"Organization for the cert\")\n", "\tflags.IntVar(&naConfig.RSAKeySize, \"key-size\", 1024, \"Size of generated private key\")\n", "\tflags.StringVar(&naConfig.IstioCAAddress,\n", "\t\t\"ca-address\", \"istio-ca:8060\", \"Istio CA address\")\n", "\tflags.StringVar(&naConfig.Env, \"env\", \"onprem\", \"Node Environment : onprem | gcp | aws\")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tflags.IntVar(&naConfig.RSAKeySize, \"key-size\", 2048, \"Size of generated private key\")\n" ], "file_path": "security/cmd/node_agent/main.go", "type": "replace", "edit_start_line_idx": 42 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ca import ( "bytes" "crypto/x509" "encoding/asn1" "fmt" "reflect" "testing" "time" "istio.io/istio/security/pkg/pki" "istio.io/istio/security/pkg/pki/testutil" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" "k8s.io/api/core/v1" ) func TestSelfSignedIstioCAWithoutSecret(t *testing.T) { certTTL := 30 * time.Minute caCertTTL := time.Hour org := "test.ca.org" caNamespace := "default" client := fake.NewSimpleClientset() ca, err := NewSelfSignedIstioCA(caCertTTL, certTTL, org, caNamespace, client.CoreV1()) if err != nil { t.Errorf("Failed to create a self-signed CA: %v", err) } name := "foo" namespace := "bar" id := fmt.Sprintf("spiffe://cluster.local/ns/%s/sa/%s", namespace, name) options := CertOptions{ Host: id, RSAKeySize: 1024, } csr, _, err := GenCSR(options) if err != nil { t.Error(err) } cb, err := ca.Sign(csr) if err != nil { t.Error(err) } rcb := ca.GetRootCertificate() certPool := x509.NewCertPool() certPool.AppendCertsFromPEM(cb) rootPool := x509.NewCertPool() rootPool.AppendCertsFromPEM(rcb) cert, err := pki.ParsePemEncodedCertificate(cb) if err != nil { t.Error(err) } if ttl := cert.NotAfter.Sub(cert.NotBefore); ttl != certTTL { t.Errorf("Unexpected certificate TTL (expecting %v, actual %v)", certTTL, ttl) } rootCert, err := pki.ParsePemEncodedCertificate(rcb) if err != nil { t.Error(err) } if ttl := rootCert.NotAfter.Sub(rootCert.NotBefore); ttl != caCertTTL { t.Errorf("Unexpected CA certificate TTL (expecting %v, actual %v)", caCertTTL, ttl) } if certOrg := rootCert.Issuer.Organization[0]; certOrg != org { t.Errorf("Unexpected CA certificate organization (expecting %v, actual %v)", org, certOrg) } chain, err := cert.Verify(x509.VerifyOptions{ Intermediates: certPool, Roots: rootPool, }) if len(chain) == 0 || err != nil { t.Error("Failed to verify generated cert") } san := pki.ExtractSANExtension(cert.Extensions) if san == nil { t.Errorf("Generated certificate does not contain a SAN field") } rv := asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(id)} bs, err := asn1.Marshal([]asn1.RawValue{rv}) if err != nil { t.Error(err) } if !bytes.Equal(bs, san.Value) { t.Errorf("SAN field does not match: %s is expected but actual is %s", bs, san.Value) } caSecret, err := client.CoreV1().Secrets("default").Get(cASecret, metav1.GetOptions{}) if err != nil { t.Errorf("Failed to get secret (error: %s)", err) } signingCert, err := pki.ParsePemEncodedCertificate(caSecret.Data[cACertID]) if err != nil { t.Errorf("Failed to parse cert (error: %s)", err) } if !signingCert.Equal(ca.signingCert) { t.Error("Cert does not match") } if len(ca.certChainBytes) > 0 { t.Error("CertChain should be empty") } rootCertBytes := copyBytes(caSecret.Data[cACertID]) if !bytes.Equal(ca.rootCertBytes, rootCertBytes) { t.Error("Root cert does not match") } } func TestSelfSignedIstioCAWithSecret(t *testing.T) { rootCert := ` -----BEGIN CERTIFICATE----- MIIC5jCCAc6gAwIBAgIRAO1DMLWq99XL/B2kRlNpnikwDQYJKoZIhvcNAQELBQAw HDEaMBgGA1UEChMRazhzLmNsdXN0ZXIubG9jYWwwHhcNMTcwOTIwMjMxODQwWhcN MTgwOTIwMjMxODQwWjAcMRowGAYDVQQKExFrOHMuY2x1c3Rlci5sb2NhbDCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKYSyDbjRlYuyyYJOuZQHiG9wOsn M4Rx/wWTJUOQthYz3uIBnR0WSMdyJ25VdpitHqDOR4hJo33DxNmknMnXhAuyVZoq YpoSx/UdlOBYNQivy6OCRxe3LuDbJ5+wNZ4y3OoEqMQjxWPWcL6iyaYHyVEJprMm IhjHD9yedJaX3F7pN0hosdtkfEsBkfcK5VPx99ekbAEo8DcsopG+XvNuT4nb7ww9 wd9VtGA8upmgNOCJvkLGVHwybw67LL4T7nejdUQd9T7o7CfAXGmBlkuGWHnsbeOe QtCfHD3+6iCmRjcSUK6AfGnfcHTjbwzGjv48JPFaNbjm2hLixC0TdAdPousCAwEA AaMjMCEwDgYDVR0PAQH/BAQDAgIEMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN AQELBQADggEBAHV5DdWspKxjeE4BsjnsA3oSkTBnbmUkMGFUtIgAvSlULYy3Wl4O bAj7VfxIegZbE3tnkuky9BwVCoBD+d2zIqCZ5Xl17+ki6cttLAFWni85cg9gX8a6 2p/EMefUYxLXEdZTw80eAB56/34Xkt6g/CnB531W8vOvjTzg25qClkA7TjVIil2+ kLAXl8xEp48cvAxX4FslgAlBPagpJYbjVM0BjQbgmGLg1rjoH/jbkQJyIabX5dSq 9fdQYxkTzYnvcvgHf4WSl/awopjsI1NhNv07+qE8ie86EoYJgXPrNtlytyqSvIXQ 2ETBxlxOg3DdlBwhBz/Hg31tCLv8E8U8fqQ= -----END CERTIFICATE----- ` // Use the same signing cert and root cert for self-signed CA. signingCert := rootCert signingKey := ` -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAphLINuNGVi7LJgk65lAeIb3A6yczhHH/BZMlQ5C2FjPe4gGd HRZIx3InblV2mK0eoM5HiEmjfcPE2aScydeEC7JVmipimhLH9R2U4Fg1CK/Lo4JH F7cu4Nsnn7A1njLc6gSoxCPFY9ZwvqLJpgfJUQmmsyYiGMcP3J50lpfcXuk3SGix 22R8SwGR9wrlU/H316RsASjwNyyikb5e825PidvvDD3B31W0YDy6maA04Im+QsZU fDJvDrssvhPud6N1RB31PujsJ8BcaYGWS4ZYeext455C0J8cPf7qIKZGNxJQroB8 ad9wdONvDMaO/jwk8Vo1uObaEuLELRN0B0+i6wIDAQABAoIBAHzHVelvoFR2uips +vU7MziU0xOcE6gq4rr0kSYP39AUzx0uqzbEnJBGY/wReJdEU+PsuXBcK9v9sLT6 atd493y2VH0N5aHwBI9V15ssi0RomW/UHchi2XUXFNF12wNvIe8u6wLcAZ5+651A wJPf+9HIl5i5SRsmzfMsl1ri5S/lgnjUQty4GYnT/Y53uaZoquX+sUhZ3pW8SkzX ZvKvMbj6UOiXlelDgtEGOCgftjdm916OfnQDnSOJsh/0UvM/Bn3kQJEOgwzhMy2/ +TOIB04wVN7K6ZEbSaV7gkciiDyjg0XhJqfkmOUm8kLhLFgervjrBdkUSuukdGmq TZmP1EkCgYEA194D0hslC//Qu0XtUCcJgLV4a41U/PDYIStf92FRXcqqYGBHDtzJ 1J86BuO/cjOdp+jZBjIIoECvY3n3TCacUiKvjmszMtanwz42eFPpVgSi3pZcyBF+ cLPB08dnUWxrxA46ss1g6gjPXjUXuEFkxuogrPiNwQPuwZnjrPWa580CgYEAxPLg oXZ7BFVUxDEUjokj9HsvSToJNAIu7XAc84Z00yJ8z/B/muCZtpC5CZ2ZhejwBioR AbpPEVRXFs9M2W1jW2YgO8iVcXiLT+qmNnjqGZuZnhzkMC2q9RnHrRfYMUO5bVOX bw0UqnEMo7vTLEN47FnImr6Jv9cQFXztJEVZjZcCgYAtQPrWEiC7Gj7885Tjh7uD QwfirDdT632zvm8Y4kr3eaQsHiLnZ7vcGiFFDnu1CkMTz0mn9dc/GTBrj0cbrMB6 q5DYL3sFPmDfGmy63wR8pu4p8aWzv48dO2H37sanGC6jZERD9bBKf9xRKJo3Y2Yo GS8Oc/DrtNJZvdQwDzERRQKBgGFd8c/hU1ABH7cezJrrEet8OxRorMQZkDmyg52h i4AWPL5Ql8Vp5JRtWA147L1XO9LQWTgRc6WNnMCaG9QiUEyPYMAtmjRO9BC+YQ3t GU8vrfKNNgLbkPk7lYvtjeRNJw71lJhCT0U0Pptz8CKh+NZgTNyz9kXxfPIioNqd rnhhAoGANfiSkuFuw2+WpBvTNah+wcZDNiMbvkQVhUwRvqIM6sLhRJhVZzJkTrYu YQTFeoqvepyHWE9e1Mb5dGFHMvXywZQR0hR2rpWxA2OgNaRhqL7Rh7th+V/owIi9 7lGXdUBnyY8tcLhla+Rbo7Y8yOsN6pp4grT1DP+8rG4G4vnJgbk= -----END RSA PRIVATE KEY----- ` client := fake.NewSimpleClientset() initSecret := createSecret("default", signingCert, signingKey, rootCert) _, err := client.CoreV1().Secrets("default").Create(initSecret) if err != nil { t.Errorf("Failed to create secret (error: %s)", err) } certTTL := 30 * time.Minute caCertTTL := time.Hour org := "test.ca.org" caNamespace := "default" ca, err := NewSelfSignedIstioCA(caCertTTL, certTTL, org, caNamespace, client.CoreV1()) if ca == nil || err != nil { t.Errorf("Expecting an error but an Istio CA is wrongly instantiated") } cert, err := pki.ParsePemEncodedCertificate([]byte(signingCert)) if err != nil { t.Errorf("Failed to parse cert (error: %s)", err) } if !cert.Equal(ca.signingCert) { t.Error("Cert does not match") } if len(ca.certChainBytes) > 0 { t.Error("CertChain should be empty") } rootCertBytes := copyBytes([]byte(rootCert)) if !bytes.Equal(ca.rootCertBytes, rootCertBytes) { t.Error("Root cert does not match") } } // Pass in unmatched chain and cert to make sure the `verify` method yeilds an error. func TestInvalidIstioCAOptions(t *testing.T) { rootCert := ` -----BEGIN CERTIFICATE----- MIIDXTCCAkWgAwIBAgIJAPa8VTmVboq0MA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMTcwMzE4MDAxMDI5WhcNMjcwMzE2MDAxMDI5WjBF MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAsBOcKtPZMB32Un0r0Ew8X4n12xgoW+2Z5f7p8reY80U6JrMPIK6yuQWk juGQsIFhWma0ELRB7xCQJZghEc6MyDR0PfESsljDZebYL7ZHlE9xWcZ2+qw3YFca wtRLa2Mud0Rx7pXMj07JGiyJ5bM5t1KJP4Wz04ZXHUDOa0NYsoFl8hJwXV/AIY0D 2+dcwa/XN0pWtgztoHL52XzliKpVPqHkgZNN7UAO6ym7pr1JRATW572YsnkLFwgg 4GJ6Nyoh3ZUghS918aZVXHQNfyvF5yAMOn47b5Zbk82ZT6ZDB2KLFJE4/F0OeryZ ncbW6HA2j0GBQPICl9+NW+Ud4KCzuwIDAQABo1AwTjAdBgNVHQ4EFgQU2Cr6Z6wH hBBYnid52DEESkDX4J0wHwYDVR0jBBgwFoAU2Cr6Z6wHhBBYnid52DEESkDX4J0w DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAB8nNUdDZ0pNX8ZGzQbgj 2wCjaX0Za0BNPvVoqpM3oR5BCXodS4HUgx2atpTjsSQlMJzR565OmoykboF5g+K3 hRW6cy4n6LdhY+WvyiyOlbLl+Qj8ceCaBbNrLrg1KbsTI3F8fL1gUzOOr+NNkOJz MDYxmuy/5kMVUp2uIx7aTigCouKgMyciA0a/FJcy1aLnW06yUj4NK0yBHXwpRMjF xcOPOXOTlDZkt88KRTveX9zUiCI9o6/lpZEjdHqT8uhXy2v+TY/akM/cuge/PMBz pspEEzvnu1mW6XEEPgRc8iFZCdtGli6Yfaixxb9oFb/T/vQ4HXh/cb5SddTBPCDS 5Q== -----END CERTIFICATE----- ` // This signing cert is not signed by the root cert. signingCert := ` -----BEGIN CERTIFICATE----- MIIC5TCCAc2gAwIBAgIQbnMGpidD8PvetlXnYSkUHjANBgkqhkiG9w0BAQsFADAT MREwDwYDVQQKEwhKdWp1IG9yZzAeFw0xNzAzMTgwMDE5MDZaFw0yNzAzMDYwMDE5 MDZaMBMxETAPBgNVBAoTCEp1anUgb3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEAoEf2+WIjOLOpVBdV6HpgdEgNklJWGNW5kpinW75F2U14/hznSqY+ JbtEPz7MXeWIagpC3gzSNM7Khtdm/jQjdnZuRhRzbBXILCrdRykewUhXsKdtpNpw bUkCgy7V861zOtwFo3Wm7J7UZIrNqYK8fJrE2YZve9rMyKj1zOVPv6Lm8ioomv2r DANX0F72+qpEAqxrD5YCexdhv+/WeO3YoEECgqRhCLbG71OzREfN2lrgl7vGpqTA bUDJK2RxL4yeARU9WcHT2mXplK5w0w63IdgM8kQdodEPHTlP//lafUDq87PjrcTY eUehLBvtclbEo9bmmnN4JOGNMywVXCw2lQIDAQABozUwMzAOBgNVHQ8BAf8EBAMC BaAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIwADANBgkqhkiG9w0B AQsFAAOCAQEABn9FAdcE+N7upOIU2yWalEe0YQgyTELF9MTstJAeJP/xSnCqF6TG /TfR0IuY/RJyXDLq2rHhrUEsRCCamlQyNkE8RSiHQD/kBf/xxSKobXQyMedXBKSC MHF2h+S/2HmZaOtgG4RnXplCpHegFOhcLORBLbyQJ72DPLvQcCo2A9uyboqKbZhs 0Gh5kSgZrvphvxIerbV5T/VWLO0llhFmU55BIalVpHD7YfMCOkjVL+Y/0fYKL5ij 68/BQAVGtO+1W1AW52eSMoH1gbvYemf+RsxdE/yKCmcTcZer8HswkQzPH03XcMwu V611eTJ/uJO6FTt9/5IN8G1qBj2bdNj/uA== -----END CERTIFICATE----- ` signingKey := ` -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAoEf2+WIjOLOpVBdV6HpgdEgNklJWGNW5kpinW75F2U14/hzn SqY+JbtEPz7MXeWIagpC3gzSNM7Khtdm/jQjdnZuRhRzbBXILCrdRykewUhXsKdt pNpwbUkCgy7V861zOtwFo3Wm7J7UZIrNqYK8fJrE2YZve9rMyKj1zOVPv6Lm8ioo mv2rDANX0F72+qpEAqxrD5YCexdhv+/WeO3YoEECgqRhCLbG71OzREfN2lrgl7vG pqTAbUDJK2RxL4yeARU9WcHT2mXplK5w0w63IdgM8kQdodEPHTlP//lafUDq87Pj rcTYeUehLBvtclbEo9bmmnN4JOGNMywVXCw2lQIDAQABAoIBAFzg9uwSg2iDK9dP 4ndiGuynKD4nOj8P8oZRsYGHZACFVVyjsR/f79l7iBPCNzkeHoucQJ1d/p2dS10S C1u5KOenv0Ua6ruyb5mwiSOIX4sPeckjbHUAI/AgQ7Vy+YZId6KfByFutvkdHOTa Tk0xNjpakUGgFpBF/S82QaGnLCxWtdSvuIZTzhC9bQGL+7TjgZknTqZUhYHLbgH3 XUBLV/Zavce77DJ02YtcZL9UphlWbuZuOF1RESn3Rk7MM3rzLTpjrDzp+EWM9T0H 4B1Zj4PIlVGdjEwUzHfK39KQYOGqhZE6O6Z8mm9H1V3+EaoCjFV6Nt3HwAXvJttc /K/HykECgYEAwg+zCnsPlfI0FuT5W7Fi4bLSRV1IxW/BueR3ct2KUVqieP9DzmZB NEI3ibn+/1MoUjyjAMROq8YBQ/oSpjvez/SqFbJ3xH1zQtAwhcO+3wU1GwftAah5 ZAtSJYRd6AQr1kaj+P5ZEqdxI9MJEPzsOR0eRKiPLVLF+OoDjpb0hkUCgYEA03Ap mjYXiVSzo0NVEcP7f4k+t2Wwoms7O4xZfLuSmvNjhrZmukuu3TIYaCbW8x4wyBe/ Vfe8W4HFuu5IyrHXt/7BYWtSFlKsUyc5sveSktAXuVnZePlowm/NPjJ0EE38I0WV aHWRlUW4H8j9ghwLKlea77+nfY/Q+pba8Ccc3BECgYEAqJD4hY8Vn7sOUiC9FU/F Q6WQDp6UGqQT1ARHWahkgHxJCu84l+2sj9dA5MqCXIiASsbPFFhwuba53LE5R9pT lbHBmC046Z3K4+txao/4mUKtuXguADW2lBddWKdc5q/Q4ETmI9/TwWde2K50fqQk EQxhAWSlUcpHmwqy4kXvyz0CgYBtRQDrBlthiJmRnUGAfeUigv4bb306Yupomt7A XHumgnQD8Y3jZyuGetYsNS5O1GJndgZW2kHIlKdoNK7/uar/FrQ/sWPpz23pR1NF Tza7krk/+9Qs9dAS9A6AvzhGGNdeLx7IrkG/gBloq8l/jRikGEQk9MoNVN6uMnoR NFVw0QKBgH2RW41bzJOJcWnArZR/qp6RT23SQeujOMcRGfH25jpoXU8fKup1Npt8 MnMxUAuP09HIovhn841Y7p+hlh4gSpsvYjLfgX0jyzJPhOmtBu0vEY7fLN6kQLiW RRoQIlr5T8PG4vXwsn2/hohILCJJyHAee/4gIq42jLu6hQsQxcoy -----END RSA PRIVATE KEY----- ` opts := &IstioCAOptions{ SigningCertBytes: []byte(signingCert), SigningKeyBytes: []byte(signingKey), RootCertBytes: []byte(rootCert), } ca, err := NewIstioCA(opts) if ca != nil || err == nil { t.Errorf("Expecting an error but an Istio CA is wrongly instantiated") } errMsg := "invalid parameters: cannot verify the signing cert with the provided root chain and cert pool" if err.Error() != errMsg { t.Errorf("Unexpected error message: expecting '%s' but the actual is '%s'", errMsg, err.Error()) } } func TestSignCSR(t *testing.T) { host := "spiffe://example.com/ns/foo/sa/bar" opts := CertOptions{ Host: host, Org: "istio.io", RSAKeySize: 512, } csrPEM, keyPEM, err := GenCSR(opts) if err != nil { t.Error(err) } ca, err := createCA() if err != nil { t.Error(err) } certPEM, err := ca.Sign(csrPEM) if err != nil { t.Error(err) } fields := &testutil.VerifyFields{ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, } if err = testutil.VerifyCertificate(keyPEM, certPEM, ca.GetRootCertificate(), host, fields); err != nil { t.Error(err) } cert, err := pki.ParsePemEncodedCertificate(certPEM) if err != nil { t.Error(err) } san := pki.ExtractSANExtension(cert.Extensions) if san == nil { t.Errorf("No SAN extension is found in the certificate") } expected := buildSubjectAltNameExtension(host) if !reflect.DeepEqual(expected, san) { t.Errorf("Unexpected extensions: wanted %v but got %v", expected, san) } } func createCA() (CertificateAuthority, error) { start := time.Now().Add(-5 * time.Minute) end := start.Add(24 * time.Hour) // Generate root CA key and cert. rootCAOpts := CertOptions{ IsCA: true, IsSelfSigned: true, NotAfter: end, NotBefore: start, Org: "Root CA", RSAKeySize: 1024, } rootCertBytes, rootKeyBytes := GenCert(rootCAOpts) rootCert, err := pki.ParsePemEncodedCertificate(rootCertBytes) if err != nil { return nil, err } rootKey, err := pki.ParsePemEncodedKey(rootKeyBytes) if err != nil { return nil, err } intermediateCAOpts := CertOptions{ IsCA: true, IsSelfSigned: false, NotAfter: end, NotBefore: start, Org: "Intermediate CA", RSAKeySize: 1024, SignerCert: rootCert, SignerPriv: rootKey, } intermediateCert, intermediateKey := GenCert(intermediateCAOpts) caOpts := &IstioCAOptions{ CertChainBytes: intermediateCert, CertTTL: time.Hour, SigningCertBytes: intermediateCert, SigningKeyBytes: intermediateKey, RootCertBytes: rootCertBytes, } return NewIstioCA(caOpts) } // TODO(wattli): move the two functions below as a util function to share with secret_test.go func createSecret(namespace, signingCert, signingKey, rootCert string) *v1.Secret { return &v1.Secret{ Data: map[string][]byte{ cACertID: []byte(signingCert), cAPrivateKeyID: []byte(signingKey), }, ObjectMeta: metav1.ObjectMeta{ Name: cASecret, Namespace: namespace, }, Type: istioCASecretType, } }
security/pkg/pki/ca/ca_test.go
1
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.006799598690122366, 0.0017116331728175282, 0.0001607469457667321, 0.0006027799681760371, 0.002011782256886363 ]
{ "id": 2, "code_window": [ "\n", "\tflags := rootCmd.Flags()\n", "\n", "\tflags.StringVar(&naConfig.ServiceIdentityOrg, \"org\", \"\", \"Organization for the cert\")\n", "\tflags.IntVar(&naConfig.RSAKeySize, \"key-size\", 1024, \"Size of generated private key\")\n", "\tflags.StringVar(&naConfig.IstioCAAddress,\n", "\t\t\"ca-address\", \"istio-ca:8060\", \"Istio CA address\")\n", "\tflags.StringVar(&naConfig.Env, \"env\", \"onprem\", \"Node Environment : onprem | gcp | aws\")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tflags.IntVar(&naConfig.RSAKeySize, \"key-size\", 2048, \"Size of generated private key\")\n" ], "file_path": "security/cmd/node_agent/main.go", "type": "replace", "edit_start_line_idx": 42 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "bytes" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" rpc "github.com/googleapis/googleapis/google/rpc" "istio.io/istio/mixer/pkg/adapter" "istio.io/istio/mixer/pkg/config/descriptor" pb "istio.io/istio/mixer/pkg/config/proto" "istio.io/istio/mixer/pkg/template" ) func makeAPIRequest(handler http.Handler, method, url string, data []byte, t *testing.T) (int, []byte) { httpRequest, err := http.NewRequest(method, url, bytes.NewBuffer(data)) httpRequest.Header.Set("Content-Type", "application/json") if err != nil { t.Fatal(err) } httpWriter := httptest.NewRecorder() handler.ServeHTTP(httpWriter, httpRequest) result := httpWriter.Result() body, err := ioutil.ReadAll(result.Body) if err != nil { t.Fatal(err) } return result.StatusCode, body } var rulesSC = &pb.ServiceConfig{ Rules: []*pb.AspectRule{ { Selector: "true", Aspects: []*pb.Aspect{ { Kind: "quotas", Params: map[string]interface{}{ "quotas": []map[string]interface{}{ {"descriptor_name": "RequestCount"}, }, }, }, }, }, }, } func TestAPI_getRules(t *testing.T) { uri := "/scopes/scope/subjects/subject/rules" bval, _ := json.Marshal(rulesSC) val := string(bval) for _, ctx := range []struct { key string val string status int }{ {uri, val, http.StatusOK}, {uri, "<Unparseable> </Unparseable>", http.StatusInternalServerError}, {"/scopes/cluster/subjects/DOESNOTEXIST.cluster.local/rules", val, http.StatusNotFound}, {"/unable_to_route_url_should_get_json_response", val, http.StatusNotFound}, } { t.Run(ctx.key, func(t *testing.T) { store := &fakeMemStore{ data: map[string]string{ uri: ctx.val, }, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) sc, body := makeAPIRequest(api.handler, "GET", api.rootPath+ctx.key, []byte{}, t) apiResp := &struct { Data *pb.ServiceConfig `json:"data,omitempty"` *APIResponse }{} if err := json.Unmarshal(body, apiResp); err != nil { t.Fatalf("Unable to unmarshal json %s\n%s", err.Error(), string(body)) } if rpc.Code(apiResp.Status.Code) != httpStatusToRPC(ctx.status) { t.Errorf("got %s, want %s", rpc.Code(apiResp.Status.Code), httpStatusToRPC(ctx.status)) } if sc != ctx.status { t.Errorf("http status got %d, want %d", sc, ctx.status) } if sc != http.StatusOK { return } bd, _ := json.Marshal(apiResp.Data) if string(bd) != ctx.val { t.Errorf("incorrect value got [%#v]\nwant [%#v]", string(bd), ctx.val) } }) } } func TestAPI_getScopes(t *testing.T) { for _, ctx := range []struct { key string val string status int }{ {"/scopes", "", http.StatusNotImplemented}, // TODO expect http.StatusOK } { t.Run(ctx.key, func(t *testing.T) { store := &fakeMemStore{ data: map[string]string{ ctx.key: ctx.val, }, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) sc, _ := makeAPIRequest(api.handler, "GET", api.rootPath+ctx.key, []byte{}, t) if sc != ctx.status { t.Errorf("http status got %d, want %d", sc, ctx.status) } // TODO validate the returned body }) } } func TestAPI_createPolicy(t *testing.T) { for _, ctx := range []struct { key string body []byte status int }{ {"/scopes/global/subjects/newTestSubject", []byte(`{"scope":"global","subject":"subject001","revision":"some-uuid","rules":[]}`), http.StatusNotImplemented}, // TODO expect http.StatusCreated } { t.Run(ctx.key, func(t *testing.T) { store := &fakeMemStore{ data: map[string]string{}, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) sc, _ := makeAPIRequest(api.handler, "POST", api.rootPath+ctx.key, ctx.body, t) if sc != ctx.status { t.Errorf("http status got %d, want %d", sc, ctx.status) } else if sc <= http.StatusAccepted { // TODO verify the expected data is present in store rather than just non-empty if len(store.data) == 0 { t.Errorf("%v did not create %v", ctx.key, string(ctx.body)) } } }) } } func TestAPI_putAspect(t *testing.T) { for _, ctx := range []struct { key string body []byte status int }{ {"/scopes/global/subjects/subject001/rules/rule001/aspects/aspect001", []byte(`{"scope":"global","subject":"subject001","ruleid":"rule001","aspect":"aspect001","revision":"some-uuid","aspects":[]}`), http.StatusNotImplemented}, // TODO expect http.StatusCreated } { t.Run(ctx.key, func(t *testing.T) { store := &fakeMemStore{ data: map[string]string{}, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) sc, _ := makeAPIRequest(api.handler, "PUT", api.rootPath+ctx.key, ctx.body, t) if sc != ctx.status { t.Errorf("http status got %d, want %d", sc, ctx.status) } else if sc <= http.StatusAccepted { // TODO verify the expected data is present in store rather than just non-empty if len(store.data) == 0 { t.Errorf("%v did not create %v", ctx.key, string(ctx.body)) } } }) } } func TestAPI_deleteRules(t *testing.T) { for _, ctx := range []struct { key string val string err error status int }{ {"/scopes/global/subjects/testSubject/rules", "", nil, http.StatusOK}, // cannot use http.StatusNoContent, because our response always contains json {"/scopes/global/subjects/testSubject/rules", "", errors.New("could not delete key"), http.StatusInternalServerError}, } { t.Run(fmt.Sprintf("%s_%s", ctx.key, ctx.err), func(t *testing.T) { store := &fakeMemStore{ data: map[string]string{ ctx.key: ctx.val, }, err: ctx.err, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) sc, _ := makeAPIRequest(api.handler, "DELETE", api.rootPath+ctx.key, []byte{}, t) if sc != ctx.status { t.Errorf("http status got %d, want %d", sc, ctx.status) } }) } } func TestAPI_deleteRule(t *testing.T) { for _, ctx := range []struct { key string val string status int }{ {"/scopes/global/subjects/testSubject/rules/rule001", "", http.StatusNotImplemented}, // TODO expect http.StatusNoContent } { t.Run(ctx.key, func(t *testing.T) { store := &fakeMemStore{ data: map[string]string{ ctx.key: ctx.val, }, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) sc, _ := makeAPIRequest(api.handler, "DELETE", api.rootPath+ctx.key, []byte{}, t) if sc != ctx.status { t.Errorf("http status got %d, want %d", sc, ctx.status) } }) } } func TestAPI_putAdapter(t *testing.T) { for _, ctx := range []struct { key string body []byte status int }{ {"/scopes/global/adapters/adapter001/config001", []byte(`{"params":{}}`), http.StatusNotImplemented}, // TODO expect http.StatusCreated } { t.Run(ctx.key, func(t *testing.T) { store := &fakeMemStore{ data: map[string]string{}, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) sc, _ := makeAPIRequest(api.handler, "PUT", api.rootPath+ctx.key, ctx.body, t) if sc != ctx.status { t.Errorf("http status got %d, want %d", sc, ctx.status) } else if sc <= http.StatusAccepted { // TODO verify the expected data is present in store rather than just non-empty if len(store.data) == 0 { t.Errorf("%v did not create %v", ctx.key, string(ctx.body)) } } }) } } func TestAPI_getDescriptor(t *testing.T) { for _, ctx := range []struct { key string val string status int }{ {"/scopes/global/descriptors/type001/descriptor001", "", http.StatusNotImplemented}, // TODO expect http.StatusOK } { t.Run(ctx.key, func(t *testing.T) { store := &fakeMemStore{ data: map[string]string{ ctx.key: ctx.val, }, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) sc, _ := makeAPIRequest(api.handler, "GET", api.rootPath+ctx.key, []byte{}, t) if sc != ctx.status { t.Errorf("http status got %d, want %d", sc, ctx.status) } // TODO validate the returned body }) } } func TestAPI_putDescriptor(t *testing.T) { for _, ctx := range []struct { key string body []byte status int }{ {"/scopes/global/descriptors/type001/descriptor001", []byte(`{}`), http.StatusNotImplemented}, // TODO expect http.StatusCreated } { t.Run(ctx.key, func(t *testing.T) { store := &fakeMemStore{ data: map[string]string{}, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) sc, _ := makeAPIRequest(api.handler, "PUT", api.rootPath+ctx.key, ctx.body, t) if sc != ctx.status { t.Errorf("http status got %d, want %d", sc, ctx.status) } else if sc <= http.StatusAccepted { // TODO verify the expected data is present in store rather than just non-empty if len(store.data) == 0 { t.Errorf("%v did not create %v", ctx.key, string(ctx.body)) } } }) } } func readBody(err string) readBodyFunc { return func(r io.Reader) (b []byte, e error) { if err != "" { e = errors.New(err) } return } } func validate(err string) validateFunc { return func(cfg map[string]string) (rt *Validated, desc descriptor.Finder, ce *adapter.ConfigErrors) { if err != "" { ce = ce.Appendf("main", err) } return } } type errorPhase int const ( errNone errorPhase = iota errStoreRead errStoreWrite errReadyBody errValidate ) func TestAPI_getAdaptersOrDescriptors(t *testing.T) { key := "/scopes/%s/adapters" val := "{}" for _, tst := range []struct { msg string scope string status int }{ {"ok", "global", http.StatusOK}, } { t.Run(tst.msg, func(t *testing.T) { k := fmt.Sprintf(key, tst.scope) store := &fakeMemStore{ data: map[string]string{ k: val, }, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) sc, bbody := makeAPIRequest(api.handler, "GET", "/api/v1"+k, []byte{}, t) if sc != tst.status { t.Fatalf("http status got %d\nwant %d \nmsg: %s", sc, tst.status, string(bbody)) } apiResp := &APIResponse{} if err := json.Unmarshal(bbody, apiResp); err != nil { t.Fatalf("Unable to unmarshal json %s", err.Error()) } if !strings.Contains(apiResp.Status.Message, tst.msg) { t.Errorf("got %v\nwant %s", apiResp.Status, tst.msg) } }) } } func TestAPI_putAdaptersOrDescriptors(t *testing.T) { key := "/scopes/%s/adapters" val := "Value" for _, tst := range []struct { msg string scope string status int }{ {"Created", "global", http.StatusOK}, {"only supports global", "local", http.StatusBadRequest}, } { t.Run(tst.msg, func(t *testing.T) { k := fmt.Sprintf(key, tst.scope) store := &fakeMemStore{ data: map[string]string{ k: val, }, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) sc, bbody := makeAPIRequest(api.handler, "PUT", "/api/v1"+k, []byte{}, t) if sc != tst.status { t.Fatalf("http status got %d\nwant %d", sc, tst.status) } apiResp := &APIResponse{} if err := json.Unmarshal(bbody, apiResp); err != nil { t.Fatalf("Unable to unmarshal json %s", err.Error()) } if !strings.Contains(apiResp.Status.Message, tst.msg) { t.Errorf("got %v\nwant %s", apiResp.Status, tst.msg) } }) } } func TestAPI_putRules(t *testing.T) { key := "/scopes/scope/subjects/subject/rules" val := "Value" for _, tst := range []struct { msg string phase errorPhase status int }{ {"Created ", errNone, http.StatusOK}, {"store write error", errStoreWrite, http.StatusInternalServerError}, {"store read error", errStoreRead, http.StatusInternalServerError}, {"request read error", errReadyBody, http.StatusInternalServerError}, {"config validation error", errValidate, http.StatusBadRequest}, } { t.Run(tst.msg, func(t *testing.T) { store := &fakeMemStore{ data: map[string]string{ key: val, }, } api := NewAPI("v1", 0, nil, nil, nil, nil, nil, store, template.NewRepository(nil)) switch tst.phase { case errStoreRead: store.err = errors.New(tst.msg) case errStoreWrite: store.writeErr = errors.New(tst.msg) case errReadyBody: api.readBody = readBody(tst.msg) case errValidate: api.validate = validate(tst.msg) } sc, bbody := makeAPIRequest(api.handler, "PUT", "/api/v1"+key, []byte{}, t) if sc != tst.status { t.Fatalf("http status got %d\nwant %d", sc, tst.status) } apiResp := &APIResponse{} if err := json.Unmarshal(bbody, apiResp); err != nil { t.Fatalf("Unable to unmarshal json %s", err.Error()) } if !strings.Contains(apiResp.Status.Message, tst.msg) { t.Errorf("got %v\nwant %s", apiResp.Status, tst.msg) } }) } } // TODO define a new envelope message // with a place for preparsed message? func TestAPI_httpStatusToRPC(t *testing.T) { for _, tst := range []struct { http int code rpc.Code }{ {http.StatusOK, rpc.OK}, {http.StatusTeapot, rpc.UNKNOWN}, } { t.Run(tst.code.String(), func(t *testing.T) { c := httpStatusToRPC(tst.http) if c != tst.code { t.Errorf("got %s\nwant %s", c, tst.code) } }) } } type fakeresp struct { err error value interface{} } // bin/linter.sh has a lint exclude for this. func (f *fakeresp) WriteHeaderAndJson(status int, value interface{}, contentType string) error { f.value = value return f.err } func (f *fakeresp) Write(bytes []byte) (int, error) { f.value = bytes return 0, f.err } // Ensures that writes responses correctly and error are logged func TestAPI_writeErrorResponse(t *testing.T) { // ensures that logging is performed err := errors.New("always error") for _, tst := range []struct { http int code rpc.Code message string }{ {http.StatusTeapot, rpc.UNKNOWN, "Teapot"}, {http.StatusOK, rpc.OK, "OK"}, {http.StatusNotFound, rpc.NOT_FOUND, "Not Found"}, } { t.Run(tst.code.String(), func(t *testing.T) { resp := &fakeresp{err: err} writeErrorResponse(tst.http, tst.message, resp) apiResp, ok := resp.value.(*APIResponse) if !ok { t.Error("failed to produce APIResponse") return } if apiResp.Status.Code != int32(tst.code) { t.Errorf("got %d\nwant %s", apiResp.Status.Code, tst.code) } }) } } func TestAPI_Run(t *testing.T) { api := NewAPI("v1", 9094, nil, nil, nil, nil, nil, nil, template.NewRepository(nil)) go api.Run() err := api.server.Close() if err != nil { t.Errorf("unexpected failure while closing %s", err) } } // CURL examples // curl http://localhost:9094/api/v1/scopes/global/subjects/svc2.ns.cluster.local/rules // --data-binary "{}<code></code>" -X PUT -H "Content-Type: application/yaml"
mixer/pkg/config/apiserver_test.go
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.0002963801089208573, 0.00017019965162035078, 0.00015782902482897043, 0.00016787476488389075, 0.000016887603123905137 ]
{ "id": 2, "code_window": [ "\n", "\tflags := rootCmd.Flags()\n", "\n", "\tflags.StringVar(&naConfig.ServiceIdentityOrg, \"org\", \"\", \"Organization for the cert\")\n", "\tflags.IntVar(&naConfig.RSAKeySize, \"key-size\", 1024, \"Size of generated private key\")\n", "\tflags.StringVar(&naConfig.IstioCAAddress,\n", "\t\t\"ca-address\", \"istio-ca:8060\", \"Istio CA address\")\n", "\tflags.StringVar(&naConfig.Env, \"env\", \"onprem\", \"Node Environment : onprem | gcp | aws\")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tflags.IntVar(&naConfig.RSAKeySize, \"key-size\", 2048, \"Size of generated private key\")\n" ], "file_path": "security/cmd/node_agent/main.go", "type": "replace", "edit_start_line_idx": 42 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package promgen generates service graphs from a prometheus backend. package promgen import ( "context" "fmt" "log" "net/http" "strconv" "strings" "time" "github.com/prometheus/client_golang/api" "github.com/prometheus/client_golang/api/prometheus/v1" "github.com/prometheus/common/model" "istio.io/istio/mixer/example/servicegraph" ) const reqsFmt = "sum(rate(istio_request_count[%s])) by (source_service, destination_service, source_version, destination_version)" const tcpFmt = "sum(rate(istio_tcp_bytes_received[%s])) by (source_service, destination_service, source_version, destination_version)" const emptyFilter = " > 0" type genOpts struct { timeHorizon string filterEmpty bool } type promHandler struct { addr string static *servicegraph.Static writer servicegraph.SerializeFn } // NewPromHandler returns a new http.Handler that will serve servicegraph data // based on queries against a prometheus backend. func NewPromHandler(addr string, static *servicegraph.Static, writer servicegraph.SerializeFn) http.Handler { return &promHandler{addr, static, writer} } func (p *promHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { timeHorizon := r.URL.Query().Get("time_horizon") if timeHorizon == "" { timeHorizon = "5m" } filterEmpty := false filterEmptyStr := r.URL.Query().Get("filter_empty") if filterEmptyStr == "true" { filterEmpty = true } // validate time_horizon if _, err := model.ParseDuration(timeHorizon); err != nil { writeError(w, fmt.Errorf("could not parse time_horizon: %v", err)) return } g, err := p.generate(genOpts{timeHorizon, filterEmpty}) g.Merge(p.static) if err != nil { writeError(w, err) return } err = p.writer(w, g) if err != nil { writeError(w, err) return } } func writeError(w http.ResponseWriter, err error) { w.WriteHeader(http.StatusInternalServerError) _, writeErr := w.Write([]byte(err.Error())) log.Print(writeErr) } func (p *promHandler) generate(opts genOpts) (*servicegraph.Dynamic, error) { client, err := api.NewClient(api.Config{Address: p.addr}) if err != nil { return nil, err } api := v1.NewAPI(client) query := fmt.Sprintf(reqsFmt, opts.timeHorizon) if opts.filterEmpty { query += emptyFilter fmt.Println(query) } graph, err := extractGraph(api, query, "reqs/sec") if err != nil { return nil, err } query = fmt.Sprintf(tcpFmt, opts.timeHorizon) if opts.filterEmpty { query += emptyFilter fmt.Println(query) } tcpGraph, err := extractGraph(api, query, "bytes/sec") if err != nil { return nil, err } return merge(graph, tcpGraph) } func merge(g1, g2 *servicegraph.Dynamic) (*servicegraph.Dynamic, error) { d := servicegraph.Dynamic{Nodes: map[string]struct{}{}, Edges: []*servicegraph.Edge{}} d.Edges = append(d.Edges, g1.Edges...) d.Edges = append(d.Edges, g2.Edges...) for nodeName, nodeValue := range g1.Nodes { d.Nodes[nodeName] = nodeValue } for nodeName, nodeValue := range g2.Nodes { d.Nodes[nodeName] = nodeValue } return &d, nil } func extractGraph(api v1.API, query, label string) (*servicegraph.Dynamic, error) { val, err := api.Query(context.Background(), query, time.Now()) if err != nil { return nil, err } switch val.Type() { case model.ValVector: matrix := val.(model.Vector) d := servicegraph.Dynamic{Nodes: map[string]struct{}{}, Edges: []*servicegraph.Edge{}} for _, sample := range matrix { // todo: add error checking here metric := sample.Metric src := strings.Replace(string(metric["source_service"]), ".svc.cluster.local", "", -1) srcVer := string(metric["source_version"]) dst := strings.Replace(string(metric["destination_service"]), ".svc.cluster.local", "", -1) dstVer := string(metric["destination_version"]) value := sample.Value d.AddEdge( src+" ("+srcVer+")", dst+" ("+dstVer+")", servicegraph.Attributes{ label: strconv.FormatFloat(float64(value), 'f', 6, 64), }) } return &d, nil default: return nil, fmt.Errorf("unknown value type returned from query: %#v", val) } }
mixer/example/servicegraph/promgen/promgen.go
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00018948130309581757, 0.0001723247696645558, 0.0001638287358218804, 0.00017288827802985907, 0.000005716945452149957 ]
{ "id": 2, "code_window": [ "\n", "\tflags := rootCmd.Flags()\n", "\n", "\tflags.StringVar(&naConfig.ServiceIdentityOrg, \"org\", \"\", \"Organization for the cert\")\n", "\tflags.IntVar(&naConfig.RSAKeySize, \"key-size\", 1024, \"Size of generated private key\")\n", "\tflags.StringVar(&naConfig.IstioCAAddress,\n", "\t\t\"ca-address\", \"istio-ca:8060\", \"Istio CA address\")\n", "\tflags.StringVar(&naConfig.Env, \"env\", \"onprem\", \"Node Environment : onprem | gcp | aws\")\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tflags.IntVar(&naConfig.RSAKeySize, \"key-size\", 2048, \"Size of generated private key\")\n" ], "file_path": "security/cmd/node_agent/main.go", "type": "replace", "edit_start_line_idx": 42 }
destination: name: world httpReqTimeout: simpleTimeout: timeout: 30s httpReqRetries: simple_retry: attempts: 1 perTryTimeout: 5s
pilot/proxy/envoy/testdata/timeout-route-rule.yaml.golden
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00016983223031274974, 0.00016983223031274974, 0.00016983223031274974, 0.00016983223031274974, 0 ]
{ "id": 3, "code_window": [ "\tid := fmt.Sprintf(\"spiffe://cluster.local/ns/%s/sa/%s\", namespace, name)\n", "\toptions := CertOptions{\n", "\t\tHost: id,\n", "\t\tRSAKeySize: 1024,\n", "\t}\n", "\tcsr, _, err := GenCSR(options)\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 48 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package controller import ( "bytes" "fmt" "reflect" "time" "github.com/golang/glog" "istio.io/istio/security/pkg/pki" "istio.io/istio/security/pkg/pki/ca" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" corev1 "k8s.io/client-go/kubernetes/typed/core/v1" "k8s.io/api/core/v1" "k8s.io/client-go/tools/cache" ) /* #nosec: disable gas linter */ const ( // The Istio secret annotation type IstioSecretType = "istio.io/key-and-cert" // The ID/name for the certificate chain file. CertChainID = "cert-chain.pem" // The ID/name for the private key file. PrivateKeyID = "key.pem" // The ID/name for the CA root certificate file. RootCertID = "root-cert.pem" secretNamePrefix = "istio." secretResyncPeriod = time.Minute serviceAccountNameAnnotationKey = "istio.io/service-account.name" // The size of a private key for a leaf certificate. keySize = 1024 ) // SecretController manages the service accounts' secrets that contains Istio keys and certificates. type SecretController struct { ca ca.CertificateAuthority core corev1.CoreV1Interface // Controller and store for service account objects. saController cache.Controller saStore cache.Store // Controller and store for secret objects. scrtController cache.Controller scrtStore cache.Store } // NewSecretController returns a pointer to a newly constructed SecretController instance. func NewSecretController(ca ca.CertificateAuthority, core corev1.CoreV1Interface, namespace string) *SecretController { c := &SecretController{ ca: ca, core: core, } saLW := &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return core.ServiceAccounts(namespace).List(options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return core.ServiceAccounts(namespace).Watch(options) }, } rehf := cache.ResourceEventHandlerFuncs{ AddFunc: c.saAdded, DeleteFunc: c.saDeleted, UpdateFunc: c.saUpdated, } c.saStore, c.saController = cache.NewInformer(saLW, &v1.ServiceAccount{}, time.Minute, rehf) istioSecretSelector := fields.SelectorFromSet(map[string]string{"type": IstioSecretType}).String() scrtLW := &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { options.FieldSelector = istioSecretSelector return core.Secrets(namespace).List(options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { options.FieldSelector = istioSecretSelector return core.Secrets(namespace).Watch(options) }, } c.scrtStore, c.scrtController = cache.NewInformer(scrtLW, &v1.Secret{}, secretResyncPeriod, cache.ResourceEventHandlerFuncs{ DeleteFunc: c.scrtDeleted, UpdateFunc: c.scrtUpdated, }) return c } // Run starts the SecretController until stopCh is closed. func (sc *SecretController) Run(stopCh chan struct{}) { go sc.scrtController.Run(stopCh) go sc.saController.Run(stopCh) } // Handles the event where a service account is added. func (sc *SecretController) saAdded(obj interface{}) { acct := obj.(*v1.ServiceAccount) sc.upsertSecret(acct.GetName(), acct.GetNamespace()) } // Handles the event where a service account is deleted. func (sc *SecretController) saDeleted(obj interface{}) { acct := obj.(*v1.ServiceAccount) sc.deleteSecret(acct.GetName(), acct.GetNamespace()) } // Handles the event where a service account is updated. func (sc *SecretController) saUpdated(oldObj, curObj interface{}) { if reflect.DeepEqual(oldObj, curObj) { // Nothing is changed. The method is invoked by periodical re-sync with the apiserver. return } oldSa := oldObj.(*v1.ServiceAccount) curSa := curObj.(*v1.ServiceAccount) curName := curSa.GetName() curNamespace := curSa.GetNamespace() oldName := oldSa.GetName() oldNamespace := oldSa.GetNamespace() // We only care the name and namespace of a service account. if curName != oldName || curNamespace != oldNamespace { sc.deleteSecret(oldName, oldNamespace) sc.upsertSecret(curName, curNamespace) glog.Infof("Service account \"%s\" in namespace \"%s\" has been updated to \"%s\" in namespace \"%s\"", oldName, oldNamespace, curName, curNamespace) } } func (sc *SecretController) upsertSecret(saName, saNamespace string) { secret := &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{serviceAccountNameAnnotationKey: saName}, Name: getSecretName(saName), Namespace: saNamespace, }, Type: IstioSecretType, } _, exists, err := sc.scrtStore.Get(secret) if err != nil { glog.Errorf("Failed to get secret from the store (error %v)", err) } if exists { // Do nothing for existing secrets. Rotating expiring certs are handled by the `scrtUpdated` method. return } // Now we know the secret does not exist yet. So we create a new one. chain, key, err := sc.generateKeyAndCert(saName, saNamespace) if err != nil { glog.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)", saName, saNamespace, err) return } rootCert := sc.ca.GetRootCertificate() secret.Data = map[string][]byte{ CertChainID: chain, PrivateKeyID: key, RootCertID: rootCert, } _, err = sc.core.Secrets(saNamespace).Create(secret) if err != nil { glog.Errorf("Failed to create secret (error: %s)", err) return } glog.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been created", saName, saNamespace) } func (sc *SecretController) deleteSecret(saName, saNamespace string) { err := sc.core.Secrets(saNamespace).Delete(getSecretName(saName), nil) // kube-apiserver returns NotFound error when the secret is successfully deleted. if err == nil || errors.IsNotFound(err) { glog.Infof("Istio secret for service account \"%s\" in namespace \"%s\" has been deleted", saName, saNamespace) return } glog.Errorf("Failed to delete Istio secret for service account \"%s\" in namespace \"%s\" (error: %s)", saName, saNamespace, err) } func (sc *SecretController) scrtDeleted(obj interface{}) { scrt, ok := obj.(*v1.Secret) if !ok { glog.Warning("Failed to convert to secret object: %v", obj) return } glog.Infof("Re-create deleted Istio secret") saName := scrt.Annotations[serviceAccountNameAnnotationKey] sc.upsertSecret(saName, scrt.GetNamespace()) } func (sc *SecretController) generateKeyAndCert(saName string, saNamespace string) ([]byte, []byte, error) { id := fmt.Sprintf("%s://cluster.local/ns/%s/sa/%s", ca.URIScheme, saNamespace, saName) options := ca.CertOptions{ Host: id, RSAKeySize: keySize, } csrPEM, keyPEM, err := ca.GenCSR(options) if err != nil { return nil, nil, err } certPEM, err := sc.ca.Sign(csrPEM) if err != nil { return nil, nil, err } return certPEM, keyPEM, nil } func (sc *SecretController) scrtUpdated(oldObj, newObj interface{}) { scrt, ok := newObj.(*v1.Secret) if !ok { glog.Warning("Failed to convert to secret object: %v", newObj) return } certBytes := scrt.Data[CertChainID] cert, err := pki.ParsePemEncodedCertificate(certBytes) if err != nil { // TODO: we should refresh secret in this case since the secret contains an // invalid cert. glog.Error(err) return } ttl := time.Until(cert.NotAfter) rootCertificate := sc.ca.GetRootCertificate() // Refresh the secret if 1) the certificate contained in the secret is about // to expire, or 2) the root certificate in the secret is different than the // one held by the ca (this may happen when the CA is restarted and // a new self-signed CA cert is generated). if ttl.Seconds() < secretResyncPeriod.Seconds() || !bytes.Equal(rootCertificate, scrt.Data[RootCertID]) { namespace := scrt.GetNamespace() name := scrt.GetName() glog.Infof("Refreshing secret %s/%s, either the leaf certificate is about to expire "+ "or the root certificate is outdated", namespace, name) saName := scrt.Annotations[serviceAccountNameAnnotationKey] chain, key, err := sc.generateKeyAndCert(saName, namespace) if err != nil { glog.Errorf("Failed to generate key and certificate for service account %q in namespace %q (error %v)", saName, namespace, err) return } scrt.Data[CertChainID] = chain scrt.Data[PrivateKeyID] = key scrt.Data[RootCertID] = rootCertificate if _, err = sc.core.Secrets(namespace).Update(scrt); err != nil { glog.Errorf("Failed to update secret %s/%s (error: %s)", namespace, name, err) } } } func getSecretName(saName string) string { return secretNamePrefix + saName }
security/pkg/pki/ca/controller/secret.go
1
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.9941192865371704, 0.15673072636127472, 0.00016484021034557372, 0.000340528175001964, 0.3452109396457672 ]
{ "id": 3, "code_window": [ "\tid := fmt.Sprintf(\"spiffe://cluster.local/ns/%s/sa/%s\", namespace, name)\n", "\toptions := CertOptions{\n", "\t\tHost: id,\n", "\t\tRSAKeySize: 1024,\n", "\t}\n", "\tcsr, _, err := GenCSR(options)\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 48 }
# Istio [![CircleCI](https://circleci.com/gh/istio/istio.svg?style=svg)](https://circleci.com/gh/istio/istio) [![Go Report Card](https://goreportcard.com/badge/github.com/istio/istio)](https://goreportcard.com/report/github.com/istio/istio) [![GoDoc](https://godoc.org/github.com/istio/istio?status.svg)](https://godoc.org/github.com/istio/istio) [![codecov.io](https://codecov.io/github/istio/istio/coverage.svg?branch=master)](https://codecov.io/github/istio/istio?branch=master) An open platform to connect, manage, and secure microservices. - [Introduction](#introduction) - [Istio authors](#istio-authors) - [Repositories](#repositories) - [Issue management](#issue-management) - [Community and support](#community-and-support) In addition, here are some other docs you may wish to read: - [Istio Working Groups](GROUPS.md) - how we partition work in the project - [Contribution Guidelines](CONTRIBUTING.md) - explains the process for contributing to the Istio code base - [Reviewing and Merging Pull Requests](REVIEWING.md) - explains the process we use to review code changes - [Istio Developer's Guide](DEV-GUIDE.md) - explains how to setup and use an Istio development environment - [Project Conventions](DEV-CONVENTIONS.md) - describes the conventions we use within the code base - [Creating Fast and Lean Code](DEV-PERF.md) - performance-oriented advice and guidelines for the code base ## Introduction Istio is an open platform for providing a uniform way to integrate microservices, manage traffic flow across microservices, enforce policies and aggregate telemetry data. Istio's control plane provides an abstraction layer over the underlying cluster management platform, such as Kubernetes, Mesos, etc. Visit [istio.io](https://istio.io) for in-depth information about using Istio. Istio is composed of these components: * **Envoy** - Sidecar proxies per microservice to handle ingress/egress traffic between services in the cluster and from a service to external services. The proxies form a _secure microservice mesh_ providing a rich set of functions like discovery, rich layer-7 routing, circuit breakers, policy enforcement and telemetry recording/reporting functions. > Note: The service mesh is not an overlay network. It > simplifies and enhances how microservices in an application talk to each > other over the network provided by the underlying platform. * **Mixer** - Central component that is leveraged by the proxies and microservices to enforce policies such as ACLs, rate limits, quotas, authentication, request tracing and telemetry collection. * **Pilot** - A component responsible for configuring the proxies at runtime. * **CA** - A component responsible for cert issuance and rotation. * **Broker** - A component implementing the open service broker API for Istio-based services. (Under development) Istio currently supports Kubernetes, Consul, and Eureka-based environments. We plan support for additional platforms such as Cloud Foundry, and Mesos in the near future. ## Istio authors Istio is an open source project with an active development community. The project was started by teams from Google and IBM, in partnership with the Envoy team at Lyft. ## Repositories The Istio project is divided across a few GitHub repositories. - [istio/istio](README.md). This is the main repo that you are currently looking at. It hosts Istio's core components and also the sample programs and the various documents that govern the Istio open source project. It includes: - [security](security/). This directory contains security related code, including CA (Cert Authority), node agent, etc. - [pilot](pilot/). This directory contains platform-specific code to populate the [abstract service model](https://istio.io/docs/concepts/traffic-management/overview.html), dynamically reconfigure the proxies when the application topology changes, as well as translate [routing rules](https://istio.io/docs/reference/config/traffic-rules/routing-rules.html) into proxy specific configuration. The [_istioctl_](https://istio.io/docs/reference/commands/istioctl.html) command line utility is also available in this directory. - [mixer](mixer/). This directory contains code to enforce various policies for traffic passing through the proxies, and collect telemetry data from proxies and services. There are plugins for interfacing with various cloud platforms, policy management services, and monitoring services. - [broker](broker/). This directory contains code for Istio's implementation of the Open Service Broker API. - [istio/api](https://github.com/istio/api). This repository defines component-level APIs and common configuration formats for the Istio platform. - [istio/mixerclient](https://github.com/istio/mixerclient). Client libraries for Mixer's API. - [istio/proxy](https://github.com/istio/proxy). The Istio proxy contains extensions to the [Envoy proxy](https://github.com/lyft/envoy) (in the form of Envoy filters), that allow the proxy to delegate policy enforcement decisions to Mixer. ## Issue management We use GitHub combined with ZenHub to track all of our bugs and feature requests. Each issue we track has a variety of metadata: - **Epic**. An epic represents a feature area for Istio as a whole. Epics are fairly broad in scope and are basically product-level things. Each issue is ultimately part of an epic. - **Milestone**. Each issue is assigned a milestone. This is 0.1, 0.2, 0.3, or 'Nebulous Future'. The milestone indicates when we think the issue should get addressed. - **Priority/Pipeline**. Each issue has a priority which is represented by the Pipeline field within GitHub. Priority can be one of P0, P1, P2, or >P2. The priority indicates how important it is to address the issue within the milestone. P0 says that the milestone cannot be considered achieved if the issue isn't resolved. We don't annotate issues with Releases; Milestones are used instead. We don't use GitHub projects at all, that support is disabled for our organization. ## Community and support There are several [communication channels](https://istio.io/community/) available to get support for Istio or to participate in its evolution.
README.md
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00017452937026973814, 0.00016895851877052337, 0.0001624993165023625, 0.00016831938410177827, 0.000003666567863547243 ]
{ "id": 3, "code_window": [ "\tid := fmt.Sprintf(\"spiffe://cluster.local/ns/%s/sa/%s\", namespace, name)\n", "\toptions := CertOptions{\n", "\t\tHost: id,\n", "\t\tRSAKeySize: 1024,\n", "\t}\n", "\tcsr, _, err := GenCSR(options)\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 48 }
{ "listeners": [ { "address": "tcp://0.0.0.0:15001", "name": "virtual", "filters": [], "bind_to_port": true, "use_original_dst": true }, { "address": "tcp://0.0.0.0:443", "name": "http_0.0.0.0_443", "filters": [ { "type": "read", "name": "http_connection_manager", "config": { "codec_type": "auto", "stat_prefix": "http", "generate_request_id": true, "tracing": { "operation_name": "egress" }, "rds": { "cluster": "rds", "route_config_name": "443", "refresh_delay_ms": 10 }, "filters": [ { "type": "decoder", "name": "mixer", "config": { "mixer_attributes": { "destination.ip": "10.1.1.1", "destination.service": "hello.default.svc.cluster.local", "destination.uid": "kubernetes://v1.default" }, "forward_attributes": { "source.ip": "10.1.1.1", "source.uid": "kubernetes://v1.default" }, "quota_name": "RequestCount" } }, { "type": "", "name": "cors", "config": {} }, { "type": "decoder", "name": "router", "config": {} } ], "access_log": [ { "path": "/dev/stdout" } ] } } ], "bind_to_port": false }, { "address": "tcp://0.0.0.0:80", "name": "http_0.0.0.0_80", "filters": [ { "type": "read", "name": "http_connection_manager", "config": { "codec_type": "auto", "stat_prefix": "http", "generate_request_id": true, "tracing": { "operation_name": "egress" }, "rds": { "cluster": "rds", "route_config_name": "80", "refresh_delay_ms": 10 }, "filters": [ { "type": "decoder", "name": "mixer", "config": { "mixer_attributes": { "destination.ip": "10.1.1.1", "destination.service": "hello.default.svc.cluster.local", "destination.uid": "kubernetes://v1.default" }, "forward_attributes": { "source.ip": "10.1.1.1", "source.uid": "kubernetes://v1.default" }, "quota_name": "RequestCount" } }, { "type": "", "name": "cors", "config": {} }, { "type": "decoder", "name": "router", "config": {} } ], "access_log": [ { "path": "/dev/stdout" } ] } } ], "bind_to_port": false }, { "address": "tcp://0.0.0.0:81", "name": "http_0.0.0.0_81", "filters": [ { "type": "read", "name": "http_connection_manager", "config": { "codec_type": "auto", "stat_prefix": "http", "generate_request_id": true, "tracing": { "operation_name": "egress" }, "rds": { "cluster": "rds", "route_config_name": "81", "refresh_delay_ms": 10 }, "filters": [ { "type": "decoder", "name": "mixer", "config": { "mixer_attributes": { "destination.ip": "10.1.1.1", "destination.service": "hello.default.svc.cluster.local", "destination.uid": "kubernetes://v1.default" }, "forward_attributes": { "source.ip": "10.1.1.1", "source.uid": "kubernetes://v1.default" }, "quota_name": "RequestCount" } }, { "type": "", "name": "cors", "config": {} }, { "type": "decoder", "name": "router", "config": {} } ], "access_log": [ { "path": "/dev/stdout" } ] } } ], "bind_to_port": false }, { "address": "tcp://10.1.0.0:100", "name": "mongo_10.1.0.0_100", "filters": [ { "type": "both", "name": "mongo_proxy", "config": { "stat_prefix": "mongo" } }, { "type": "read", "name": "tcp_proxy", "config": { "stat_prefix": "tcp", "route_config": { "routes": [ { "cluster": "out.hello.default.svc.cluster.local|mongo", "destination_ip_list": [ "10.1.0.0/32" ] } ] } } } ], "bind_to_port": false }, { "address": "tcp://10.1.0.0:110", "name": "redis_10.1.0.0_110", "filters": [ { "type": "both", "name": "redis_proxy", "config": { "cluster_name": "out.hello.default.svc.cluster.local|redis", "conn_pool": { "op_timeout_ms": 30000 }, "stat_prefix": "redis" } } ], "bind_to_port": false }, { "address": "tcp://10.1.0.0:90", "name": "tcp_10.1.0.0_90", "filters": [ { "type": "read", "name": "tcp_proxy", "config": { "stat_prefix": "tcp", "route_config": { "routes": [ { "cluster": "out.hello.default.svc.cluster.local|custom", "destination_ip_list": [ "10.1.0.0/32" ] } ] } } } ], "bind_to_port": false }, { "address": "tcp://10.1.1.1:1081", "name": "http_10.1.1.1_1081", "filters": [ { "type": "read", "name": "http_connection_manager", "config": { "codec_type": "auto", "stat_prefix": "http", "generate_request_id": true, "tracing": { "operation_name": "ingress" }, "route_config": { "virtual_hosts": [ { "name": "inbound|1081", "domains": [ "*" ], "routes": [ { "prefix": "/", "cluster": "in.1081", "opaque_config": { "mixer_check": "on", "mixer_forward": "off", "mixer_report": "on" }, "decorator": { "operation": "default-route" } } ] } ] }, "filters": [ { "type": "decoder", "name": "mixer", "config": { "mixer_attributes": { "destination.ip": "10.1.1.1", "destination.service": "hello.default.svc.cluster.local", "destination.uid": "kubernetes://v1.default" }, "forward_attributes": { "source.ip": "10.1.1.1", "source.uid": "kubernetes://v1.default" }, "quota_name": "RequestCount" } }, { "type": "", "name": "cors", "config": {} }, { "type": "decoder", "name": "router", "config": {} } ], "access_log": [ { "path": "/dev/stdout" } ] } } ], "ssl_context": { "cert_chain_file": "/etc/certs/cert-chain.pem", "private_key_file": "/etc/certs/key.pem", "ca_cert_file": "/etc/certs/root-cert.pem", "require_client_certificate": true }, "bind_to_port": false }, { "address": "tcp://10.1.1.1:1090", "name": "tcp_10.1.1.1_1090", "filters": [ { "type": "both", "name": "mixer", "config": { "mixer_attributes": { "destination.ip": "10.1.1.1", "destination.uid": "kubernetes://v1.default" } } }, { "type": "read", "name": "tcp_proxy", "config": { "stat_prefix": "tcp", "route_config": { "routes": [ { "cluster": "in.1090", "destination_ip_list": [ "10.1.1.1/32" ] } ] } } } ], "ssl_context": { "cert_chain_file": "/etc/certs/cert-chain.pem", "private_key_file": "/etc/certs/key.pem", "ca_cert_file": "/etc/certs/root-cert.pem", "require_client_certificate": true }, "bind_to_port": false }, { "address": "tcp://10.1.1.1:1100", "name": "mongo_10.1.1.1_1100", "filters": [ { "type": "both", "name": "mixer", "config": { "mixer_attributes": { "destination.ip": "10.1.1.1", "destination.uid": "kubernetes://v1.default" } } }, { "type": "both", "name": "mongo_proxy", "config": { "stat_prefix": "mongo" } }, { "type": "read", "name": "tcp_proxy", "config": { "stat_prefix": "tcp", "route_config": { "routes": [ { "cluster": "in.1100", "destination_ip_list": [ "10.1.1.1/32" ] } ] } } } ], "ssl_context": { "cert_chain_file": "/etc/certs/cert-chain.pem", "private_key_file": "/etc/certs/key.pem", "ca_cert_file": "/etc/certs/root-cert.pem", "require_client_certificate": true }, "bind_to_port": false }, { "address": "tcp://10.1.1.1:1110", "name": "redis_10.1.1.1_1110", "filters": [ { "type": "both", "name": "mixer", "config": { "mixer_attributes": { "destination.ip": "10.1.1.1", "destination.uid": "kubernetes://v1.default" } } }, { "type": "both", "name": "redis_proxy", "config": { "cluster_name": "in.1110", "conn_pool": { "op_timeout_ms": 30000 }, "stat_prefix": "redis" } } ], "ssl_context": { "cert_chain_file": "/etc/certs/cert-chain.pem", "private_key_file": "/etc/certs/key.pem", "ca_cert_file": "/etc/certs/root-cert.pem", "require_client_certificate": true }, "bind_to_port": false }, { "address": "tcp://10.1.1.1:3333", "name": "tcp_10.1.1.1_3333", "filters": [ { "type": "read", "name": "tcp_proxy", "config": { "stat_prefix": "tcp", "route_config": { "routes": [ { "cluster": "in.3333", "destination_ip_list": [ "10.1.1.1/32" ] } ] } } } ], "bind_to_port": false }, { "address": "tcp://10.1.1.1:80", "name": "http_10.1.1.1_80", "filters": [ { "type": "read", "name": "http_connection_manager", "config": { "codec_type": "auto", "stat_prefix": "http", "generate_request_id": true, "tracing": { "operation_name": "ingress" }, "route_config": { "virtual_hosts": [ { "name": "inbound|80", "domains": [ "*" ], "routes": [ { "prefix": "/", "cluster": "in.80", "opaque_config": { "mixer_check": "on", "mixer_forward": "off", "mixer_report": "on" }, "decorator": { "operation": "default-route" } } ] } ] }, "filters": [ { "type": "decoder", "name": "mixer", "config": { "mixer_attributes": { "destination.ip": "10.1.1.1", "destination.service": "hello.default.svc.cluster.local", "destination.uid": "kubernetes://v1.default" }, "forward_attributes": { "source.ip": "10.1.1.1", "source.uid": "kubernetes://v1.default" }, "quota_name": "RequestCount" } }, { "type": "", "name": "cors", "config": {} }, { "type": "decoder", "name": "router", "config": {} } ], "access_log": [ { "path": "/dev/stdout" } ] } } ], "ssl_context": { "cert_chain_file": "/etc/certs/cert-chain.pem", "private_key_file": "/etc/certs/key.pem", "ca_cert_file": "/etc/certs/root-cert.pem", "require_client_certificate": true }, "bind_to_port": false }, { "address": "tcp://10.1.1.1:9999", "name": "tcp_10.1.1.1_9999", "filters": [ { "type": "read", "name": "tcp_proxy", "config": { "stat_prefix": "tcp", "route_config": { "routes": [ { "cluster": "in.9999", "destination_ip_list": [ "10.1.1.1/32" ] } ] } } } ], "bind_to_port": false }, { "address": "tcp://10.2.0.0:100", "name": "mongo_10.2.0.0_100", "filters": [ { "type": "both", "name": "mongo_proxy", "config": { "stat_prefix": "mongo" } }, { "type": "read", "name": "tcp_proxy", "config": { "stat_prefix": "tcp", "route_config": { "routes": [ { "cluster": "out.world.default.svc.cluster.local|mongo", "destination_ip_list": [ "10.2.0.0/32" ] } ] } } } ], "bind_to_port": false }, { "address": "tcp://10.2.0.0:110", "name": "redis_10.2.0.0_110", "filters": [ { "type": "both", "name": "redis_proxy", "config": { "cluster_name": "out.world.default.svc.cluster.local|redis", "conn_pool": { "op_timeout_ms": 30000 }, "stat_prefix": "redis" } } ], "bind_to_port": false }, { "address": "tcp://10.2.0.0:90", "name": "tcp_10.2.0.0_90", "filters": [ { "type": "read", "name": "tcp_proxy", "config": { "stat_prefix": "tcp", "route_config": { "routes": [ { "cluster": "out.world.default.svc.cluster.local|custom", "destination_ip_list": [ "10.2.0.0/32" ] } ] } } } ], "bind_to_port": false } ] }
pilot/proxy/envoy/testdata/lds-v1-weighted-auth.json.golden
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00017900987586472183, 0.00017156773537863046, 0.0001656766253290698, 0.0001725050969980657, 0.0000033683754736557603 ]
{ "id": 3, "code_window": [ "\tid := fmt.Sprintf(\"spiffe://cluster.local/ns/%s/sa/%s\", namespace, name)\n", "\toptions := CertOptions{\n", "\t\tHost: id,\n", "\t\tRSAKeySize: 1024,\n", "\t}\n", "\tcsr, _, err := GenCSR(options)\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 48 }
// Copyright 2017 Istio Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package descriptor import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "strings" "github.com/ghodss/yaml" "github.com/gogo/protobuf/jsonpb" "github.com/gogo/protobuf/proto" "github.com/golang/glog" dpb "istio.io/api/mixer/v1/config/descriptor" "istio.io/istio/mixer/pkg/adapter" pb "istio.io/istio/mixer/pkg/config/proto" "istio.io/istio/mixer/pkg/expr" ) // Finder describes anything that can provide a view into the config's descriptors by name and type. type Finder interface { expr.AttributeDescriptorFinder // GetLog retrieves the log descriptor named `name` GetLog(name string) *dpb.LogEntryDescriptor // GetMetric retrieves the metric descriptor named `name` GetMetric(name string) *dpb.MetricDescriptor // GetMonitoredResource retrieves the monitored resource descriptor named `name` GetMonitoredResource(name string) *dpb.MonitoredResourceDescriptor // GetPrincipal retrieves the security principal descriptor named `name` GetPrincipal(name string) *dpb.PrincipalDescriptor // GetQuota retrieves the quota descriptor named `name` GetQuota(name string) *dpb.QuotaDescriptor } type dname string // NOTE: Update this list when new fields are added to the GlobalConfig message. const ( logs dname = "logs" metrics = "metrics" monitoredResources = "monitoredResources" principals = "principals" quotas = "quotas" manifests = "manifests" attributes = "attributes" ) type finder struct { logs map[string]*dpb.LogEntryDescriptor metrics map[string]*dpb.MetricDescriptor monitoredResources map[string]*dpb.MonitoredResourceDescriptor principals map[string]*dpb.PrincipalDescriptor quotas map[string]*dpb.QuotaDescriptor attributes map[string]*pb.AttributeManifest_AttributeInfo } // typeMap maps descriptor types to example messages of those types. var typeMap = map[dname]proto.Message{ logs: &dpb.LogEntryDescriptor{ Name: "accesslog.common", DisplayName: "Apache Common Log Format", LogTemplate: `{{or (.originIp) "-"}} - {{or (.sourceUser) "-"}}`, Labels: map[string]dpb.ValueType{ "sourceUser": dpb.STRING, "timestamp": dpb.TIMESTAMP, "originIp": dpb.IP_ADDRESS, }, }, metrics: &dpb.MetricDescriptor{ Kind: dpb.COUNTER, Value: dpb.DURATION, Description: "request latency by source, target, and service", Labels: map[string]dpb.ValueType{ "source": dpb.STRING, "target": dpb.STRING, "service": dpb.STRING, "response_code": dpb.INT64, }, }, // Add example for monitoredResources, principals descriptors. monitoredResources: &dpb.MonitoredResourceDescriptor{}, principals: &dpb.PrincipalDescriptor{}, quotas: &dpb.QuotaDescriptor{ Name: "RateLimitByService", DisplayName: "RateLimit", Description: "RateLimit By Service", Labels: map[string]dpb.ValueType{ "target": dpb.STRING, }, RateLimit: true, }, attributes: &pb.AttributeManifest_AttributeInfo{ ValueType: dpb.STRING, Description: "Intended destination of a request", }, manifests: &pb.AttributeManifest{ Attributes: map[string]*pb.AttributeManifest_AttributeInfo{ "target.service": { ValueType: dpb.STRING, Description: "Intended destination of a request", }, }, }, } // Parse parses a descriptor config into its parts. // This entire function is equivalent to jsonpb.Unmarshal() // It provides better error reporting about which specific // object has the error func Parse(cfg string) (dcfg *pb.GlobalConfig, ce *adapter.ConfigErrors) { m := map[string]interface{}{} var err error if err = yaml.Unmarshal([]byte(cfg), &m); err != nil { return nil, ce.Append("descriptorConfig", err) } var cerr *adapter.ConfigErrors var oarr reflect.Value basemsg := map[string]interface{}{} // copy unhandled keys into basemsg for kk, v := range m { if typeMap[dname(kk)] == nil { basemsg[kk] = v } } dcfg = &pb.GlobalConfig{} ce = ce.Extend(updateMsg("descriptorConfig", basemsg, dcfg, nil, true)) //flatten manifest var k dname = manifests val := m[string(k)] if val != nil { mani := []*pb.AttributeManifest{} for midx, msft := range val.([]interface{}) { mname := fmt.Sprintf("%s[%d]", k, midx) manifest := msft.(map[string]interface{}) attr := manifest[attributes].(map[string]interface{}) delete(manifest, attributes) ma := &pb.AttributeManifest{} if cerr = updateMsg(mname, manifest, ma, typeMap[k], false); cerr != nil { ce = ce.Extend(cerr) } if oarr, cerr = processMap(mname+"."+attributes, attr, typeMap[attributes]); cerr != nil { ce = ce.Extend(cerr) continue } ma.Attributes = oarr.Interface().(map[string]*pb.AttributeManifest_AttributeInfo) mani = append(mani, ma) } dcfg.Manifests = mani } for k, kfn := range typeMap { if k == manifests { continue } val = m[string(k)] if val == nil { if glog.V(2) { glog.Warningf("%s missing", k) } continue } if oarr, cerr = processArray(string(k), val.([]interface{}), kfn); cerr != nil { ce = ce.Extend(cerr) continue } fld := reflect.ValueOf(dcfg).Elem().FieldByName(strings.Title(string(k))) if !fld.IsValid() { continue } fld.Set(oarr) } return dcfg, ce } // updateMsg updates a proto.Message using a json message // of type []interface{} or map[string]interface{} // obj must be previously obtained from a json.Unmarshal func updateMsg(ctx string, obj interface{}, dm proto.Message, example proto.Message, allowUnknownFields bool) (ce *adapter.ConfigErrors) { var enc []byte var err error if enc, err = json.Marshal(obj); err != nil { return ce.Append(ctx, err) } um := &jsonpb.Unmarshaler{AllowUnknownFields: allowUnknownFields} if err = um.Unmarshal(bytes.NewReader(enc), dm); err != nil { msg := fmt.Sprintf("%v: %s", err, string(enc)) if example != nil { um := &jsonpb.Marshaler{} exampleStr, _ := um.MarshalToString(example) // nolint: gas msg += ", example: " + exampleStr } return ce.Append(ctx, errors.New(msg)) } return nil } // processArray and return typed array func processArray(name string, arr []interface{}, nm proto.Message) (reflect.Value, *adapter.ConfigErrors) { var ce *adapter.ConfigErrors ptrType := reflect.TypeOf(nm) valType := reflect.Indirect(reflect.ValueOf(nm)).Type() outarr := reflect.MakeSlice(reflect.SliceOf(ptrType), 0, len(arr)) for idx, attr := range arr { dm := reflect.New(valType).Interface().(proto.Message) if cerr := updateMsg(fmt.Sprintf("%s[%d]", name, idx), attr, dm, nm, false); cerr != nil { ce = ce.Extend(cerr) continue } outarr = reflect.Append(outarr, reflect.ValueOf(dm)) } return outarr, ce } // processMap and return a typed map. func processMap(name string, arr map[string]interface{}, value proto.Message) (reflect.Value, *adapter.ConfigErrors) { var ce *adapter.ConfigErrors ptrType := reflect.TypeOf(value) valueType := reflect.Indirect(reflect.ValueOf(value)).Type() outmap := reflect.MakeMap(reflect.MapOf(reflect.ValueOf("").Type(), ptrType)) for vname, val := range arr { dm := reflect.New(valueType).Interface().(proto.Message) if cerr := updateMsg(fmt.Sprintf("%s[%s]", name, vname), val, dm, value, false); cerr != nil { ce = ce.Extend(cerr) continue } outmap.SetMapIndex(reflect.ValueOf(vname), reflect.ValueOf(dm)) } return outmap, ce } // NewFinder constructs a new Finder for the provided global config. func NewFinder(cfg *pb.GlobalConfig) Finder { f := &finder{ logs: make(map[string]*dpb.LogEntryDescriptor), metrics: make(map[string]*dpb.MetricDescriptor), monitoredResources: make(map[string]*dpb.MonitoredResourceDescriptor), principals: make(map[string]*dpb.PrincipalDescriptor), quotas: make(map[string]*dpb.QuotaDescriptor), attributes: make(map[string]*pb.AttributeManifest_AttributeInfo), } if cfg == nil { return f } for _, desc := range cfg.Logs { f.logs[desc.Name] = desc } for _, desc := range cfg.Metrics { f.metrics[desc.Name] = desc } for _, desc := range cfg.MonitoredResources { f.monitoredResources[desc.Name] = desc } for _, desc := range cfg.Principals { f.principals[desc.Name] = desc } for _, desc := range cfg.Quotas { f.quotas[desc.Name] = desc } for _, manifest := range cfg.Manifests { for name, info := range manifest.Attributes { f.attributes[name] = info } } return f } func (d *finder) GetLog(name string) *dpb.LogEntryDescriptor { return d.logs[name] } func (d *finder) GetMetric(name string) *dpb.MetricDescriptor { return d.metrics[name] } func (d *finder) GetMonitoredResource(name string) *dpb.MonitoredResourceDescriptor { return d.monitoredResources[name] } func (d *finder) GetPrincipal(name string) *dpb.PrincipalDescriptor { return d.principals[name] } func (d *finder) GetQuota(name string) *dpb.QuotaDescriptor { return d.quotas[name] } func (d *finder) GetAttribute(name string) *pb.AttributeManifest_AttributeInfo { return d.attributes[name] }
mixer/pkg/config/descriptor/descriptor.go
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00045861004036851227, 0.00019965166575275362, 0.0001606989826541394, 0.0001730673830024898, 0.00007325957267312333 ]
{ "id": 4, "code_window": [ "func TestSignCSR(t *testing.T) {\n", "\thost := \"spiffe://example.com/ns/foo/sa/bar\"\n", "\topts := CertOptions{\n", "\t\tHost: host,\n", "\t\tOrg: \"istio.io\",\n", "\t\tRSAKeySize: 512,\n", "\t}\n", "\tcsrPEM, keyPEM, err := GenCSR(opts)\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 323 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ca import ( "bytes" "crypto/x509" "encoding/asn1" "fmt" "reflect" "testing" "time" "istio.io/istio/security/pkg/pki" "istio.io/istio/security/pkg/pki/testutil" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" "k8s.io/api/core/v1" ) func TestSelfSignedIstioCAWithoutSecret(t *testing.T) { certTTL := 30 * time.Minute caCertTTL := time.Hour org := "test.ca.org" caNamespace := "default" client := fake.NewSimpleClientset() ca, err := NewSelfSignedIstioCA(caCertTTL, certTTL, org, caNamespace, client.CoreV1()) if err != nil { t.Errorf("Failed to create a self-signed CA: %v", err) } name := "foo" namespace := "bar" id := fmt.Sprintf("spiffe://cluster.local/ns/%s/sa/%s", namespace, name) options := CertOptions{ Host: id, RSAKeySize: 1024, } csr, _, err := GenCSR(options) if err != nil { t.Error(err) } cb, err := ca.Sign(csr) if err != nil { t.Error(err) } rcb := ca.GetRootCertificate() certPool := x509.NewCertPool() certPool.AppendCertsFromPEM(cb) rootPool := x509.NewCertPool() rootPool.AppendCertsFromPEM(rcb) cert, err := pki.ParsePemEncodedCertificate(cb) if err != nil { t.Error(err) } if ttl := cert.NotAfter.Sub(cert.NotBefore); ttl != certTTL { t.Errorf("Unexpected certificate TTL (expecting %v, actual %v)", certTTL, ttl) } rootCert, err := pki.ParsePemEncodedCertificate(rcb) if err != nil { t.Error(err) } if ttl := rootCert.NotAfter.Sub(rootCert.NotBefore); ttl != caCertTTL { t.Errorf("Unexpected CA certificate TTL (expecting %v, actual %v)", caCertTTL, ttl) } if certOrg := rootCert.Issuer.Organization[0]; certOrg != org { t.Errorf("Unexpected CA certificate organization (expecting %v, actual %v)", org, certOrg) } chain, err := cert.Verify(x509.VerifyOptions{ Intermediates: certPool, Roots: rootPool, }) if len(chain) == 0 || err != nil { t.Error("Failed to verify generated cert") } san := pki.ExtractSANExtension(cert.Extensions) if san == nil { t.Errorf("Generated certificate does not contain a SAN field") } rv := asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(id)} bs, err := asn1.Marshal([]asn1.RawValue{rv}) if err != nil { t.Error(err) } if !bytes.Equal(bs, san.Value) { t.Errorf("SAN field does not match: %s is expected but actual is %s", bs, san.Value) } caSecret, err := client.CoreV1().Secrets("default").Get(cASecret, metav1.GetOptions{}) if err != nil { t.Errorf("Failed to get secret (error: %s)", err) } signingCert, err := pki.ParsePemEncodedCertificate(caSecret.Data[cACertID]) if err != nil { t.Errorf("Failed to parse cert (error: %s)", err) } if !signingCert.Equal(ca.signingCert) { t.Error("Cert does not match") } if len(ca.certChainBytes) > 0 { t.Error("CertChain should be empty") } rootCertBytes := copyBytes(caSecret.Data[cACertID]) if !bytes.Equal(ca.rootCertBytes, rootCertBytes) { t.Error("Root cert does not match") } } func TestSelfSignedIstioCAWithSecret(t *testing.T) { rootCert := ` -----BEGIN CERTIFICATE----- MIIC5jCCAc6gAwIBAgIRAO1DMLWq99XL/B2kRlNpnikwDQYJKoZIhvcNAQELBQAw HDEaMBgGA1UEChMRazhzLmNsdXN0ZXIubG9jYWwwHhcNMTcwOTIwMjMxODQwWhcN MTgwOTIwMjMxODQwWjAcMRowGAYDVQQKExFrOHMuY2x1c3Rlci5sb2NhbDCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKYSyDbjRlYuyyYJOuZQHiG9wOsn M4Rx/wWTJUOQthYz3uIBnR0WSMdyJ25VdpitHqDOR4hJo33DxNmknMnXhAuyVZoq YpoSx/UdlOBYNQivy6OCRxe3LuDbJ5+wNZ4y3OoEqMQjxWPWcL6iyaYHyVEJprMm IhjHD9yedJaX3F7pN0hosdtkfEsBkfcK5VPx99ekbAEo8DcsopG+XvNuT4nb7ww9 wd9VtGA8upmgNOCJvkLGVHwybw67LL4T7nejdUQd9T7o7CfAXGmBlkuGWHnsbeOe QtCfHD3+6iCmRjcSUK6AfGnfcHTjbwzGjv48JPFaNbjm2hLixC0TdAdPousCAwEA AaMjMCEwDgYDVR0PAQH/BAQDAgIEMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN AQELBQADggEBAHV5DdWspKxjeE4BsjnsA3oSkTBnbmUkMGFUtIgAvSlULYy3Wl4O bAj7VfxIegZbE3tnkuky9BwVCoBD+d2zIqCZ5Xl17+ki6cttLAFWni85cg9gX8a6 2p/EMefUYxLXEdZTw80eAB56/34Xkt6g/CnB531W8vOvjTzg25qClkA7TjVIil2+ kLAXl8xEp48cvAxX4FslgAlBPagpJYbjVM0BjQbgmGLg1rjoH/jbkQJyIabX5dSq 9fdQYxkTzYnvcvgHf4WSl/awopjsI1NhNv07+qE8ie86EoYJgXPrNtlytyqSvIXQ 2ETBxlxOg3DdlBwhBz/Hg31tCLv8E8U8fqQ= -----END CERTIFICATE----- ` // Use the same signing cert and root cert for self-signed CA. signingCert := rootCert signingKey := ` -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAphLINuNGVi7LJgk65lAeIb3A6yczhHH/BZMlQ5C2FjPe4gGd HRZIx3InblV2mK0eoM5HiEmjfcPE2aScydeEC7JVmipimhLH9R2U4Fg1CK/Lo4JH F7cu4Nsnn7A1njLc6gSoxCPFY9ZwvqLJpgfJUQmmsyYiGMcP3J50lpfcXuk3SGix 22R8SwGR9wrlU/H316RsASjwNyyikb5e825PidvvDD3B31W0YDy6maA04Im+QsZU fDJvDrssvhPud6N1RB31PujsJ8BcaYGWS4ZYeext455C0J8cPf7qIKZGNxJQroB8 ad9wdONvDMaO/jwk8Vo1uObaEuLELRN0B0+i6wIDAQABAoIBAHzHVelvoFR2uips +vU7MziU0xOcE6gq4rr0kSYP39AUzx0uqzbEnJBGY/wReJdEU+PsuXBcK9v9sLT6 atd493y2VH0N5aHwBI9V15ssi0RomW/UHchi2XUXFNF12wNvIe8u6wLcAZ5+651A wJPf+9HIl5i5SRsmzfMsl1ri5S/lgnjUQty4GYnT/Y53uaZoquX+sUhZ3pW8SkzX ZvKvMbj6UOiXlelDgtEGOCgftjdm916OfnQDnSOJsh/0UvM/Bn3kQJEOgwzhMy2/ +TOIB04wVN7K6ZEbSaV7gkciiDyjg0XhJqfkmOUm8kLhLFgervjrBdkUSuukdGmq TZmP1EkCgYEA194D0hslC//Qu0XtUCcJgLV4a41U/PDYIStf92FRXcqqYGBHDtzJ 1J86BuO/cjOdp+jZBjIIoECvY3n3TCacUiKvjmszMtanwz42eFPpVgSi3pZcyBF+ cLPB08dnUWxrxA46ss1g6gjPXjUXuEFkxuogrPiNwQPuwZnjrPWa580CgYEAxPLg oXZ7BFVUxDEUjokj9HsvSToJNAIu7XAc84Z00yJ8z/B/muCZtpC5CZ2ZhejwBioR AbpPEVRXFs9M2W1jW2YgO8iVcXiLT+qmNnjqGZuZnhzkMC2q9RnHrRfYMUO5bVOX bw0UqnEMo7vTLEN47FnImr6Jv9cQFXztJEVZjZcCgYAtQPrWEiC7Gj7885Tjh7uD QwfirDdT632zvm8Y4kr3eaQsHiLnZ7vcGiFFDnu1CkMTz0mn9dc/GTBrj0cbrMB6 q5DYL3sFPmDfGmy63wR8pu4p8aWzv48dO2H37sanGC6jZERD9bBKf9xRKJo3Y2Yo GS8Oc/DrtNJZvdQwDzERRQKBgGFd8c/hU1ABH7cezJrrEet8OxRorMQZkDmyg52h i4AWPL5Ql8Vp5JRtWA147L1XO9LQWTgRc6WNnMCaG9QiUEyPYMAtmjRO9BC+YQ3t GU8vrfKNNgLbkPk7lYvtjeRNJw71lJhCT0U0Pptz8CKh+NZgTNyz9kXxfPIioNqd rnhhAoGANfiSkuFuw2+WpBvTNah+wcZDNiMbvkQVhUwRvqIM6sLhRJhVZzJkTrYu YQTFeoqvepyHWE9e1Mb5dGFHMvXywZQR0hR2rpWxA2OgNaRhqL7Rh7th+V/owIi9 7lGXdUBnyY8tcLhla+Rbo7Y8yOsN6pp4grT1DP+8rG4G4vnJgbk= -----END RSA PRIVATE KEY----- ` client := fake.NewSimpleClientset() initSecret := createSecret("default", signingCert, signingKey, rootCert) _, err := client.CoreV1().Secrets("default").Create(initSecret) if err != nil { t.Errorf("Failed to create secret (error: %s)", err) } certTTL := 30 * time.Minute caCertTTL := time.Hour org := "test.ca.org" caNamespace := "default" ca, err := NewSelfSignedIstioCA(caCertTTL, certTTL, org, caNamespace, client.CoreV1()) if ca == nil || err != nil { t.Errorf("Expecting an error but an Istio CA is wrongly instantiated") } cert, err := pki.ParsePemEncodedCertificate([]byte(signingCert)) if err != nil { t.Errorf("Failed to parse cert (error: %s)", err) } if !cert.Equal(ca.signingCert) { t.Error("Cert does not match") } if len(ca.certChainBytes) > 0 { t.Error("CertChain should be empty") } rootCertBytes := copyBytes([]byte(rootCert)) if !bytes.Equal(ca.rootCertBytes, rootCertBytes) { t.Error("Root cert does not match") } } // Pass in unmatched chain and cert to make sure the `verify` method yeilds an error. func TestInvalidIstioCAOptions(t *testing.T) { rootCert := ` -----BEGIN CERTIFICATE----- MIIDXTCCAkWgAwIBAgIJAPa8VTmVboq0MA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMTcwMzE4MDAxMDI5WhcNMjcwMzE2MDAxMDI5WjBF MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAsBOcKtPZMB32Un0r0Ew8X4n12xgoW+2Z5f7p8reY80U6JrMPIK6yuQWk juGQsIFhWma0ELRB7xCQJZghEc6MyDR0PfESsljDZebYL7ZHlE9xWcZ2+qw3YFca wtRLa2Mud0Rx7pXMj07JGiyJ5bM5t1KJP4Wz04ZXHUDOa0NYsoFl8hJwXV/AIY0D 2+dcwa/XN0pWtgztoHL52XzliKpVPqHkgZNN7UAO6ym7pr1JRATW572YsnkLFwgg 4GJ6Nyoh3ZUghS918aZVXHQNfyvF5yAMOn47b5Zbk82ZT6ZDB2KLFJE4/F0OeryZ ncbW6HA2j0GBQPICl9+NW+Ud4KCzuwIDAQABo1AwTjAdBgNVHQ4EFgQU2Cr6Z6wH hBBYnid52DEESkDX4J0wHwYDVR0jBBgwFoAU2Cr6Z6wHhBBYnid52DEESkDX4J0w DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAB8nNUdDZ0pNX8ZGzQbgj 2wCjaX0Za0BNPvVoqpM3oR5BCXodS4HUgx2atpTjsSQlMJzR565OmoykboF5g+K3 hRW6cy4n6LdhY+WvyiyOlbLl+Qj8ceCaBbNrLrg1KbsTI3F8fL1gUzOOr+NNkOJz MDYxmuy/5kMVUp2uIx7aTigCouKgMyciA0a/FJcy1aLnW06yUj4NK0yBHXwpRMjF xcOPOXOTlDZkt88KRTveX9zUiCI9o6/lpZEjdHqT8uhXy2v+TY/akM/cuge/PMBz pspEEzvnu1mW6XEEPgRc8iFZCdtGli6Yfaixxb9oFb/T/vQ4HXh/cb5SddTBPCDS 5Q== -----END CERTIFICATE----- ` // This signing cert is not signed by the root cert. signingCert := ` -----BEGIN CERTIFICATE----- MIIC5TCCAc2gAwIBAgIQbnMGpidD8PvetlXnYSkUHjANBgkqhkiG9w0BAQsFADAT MREwDwYDVQQKEwhKdWp1IG9yZzAeFw0xNzAzMTgwMDE5MDZaFw0yNzAzMDYwMDE5 MDZaMBMxETAPBgNVBAoTCEp1anUgb3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEAoEf2+WIjOLOpVBdV6HpgdEgNklJWGNW5kpinW75F2U14/hznSqY+ JbtEPz7MXeWIagpC3gzSNM7Khtdm/jQjdnZuRhRzbBXILCrdRykewUhXsKdtpNpw bUkCgy7V861zOtwFo3Wm7J7UZIrNqYK8fJrE2YZve9rMyKj1zOVPv6Lm8ioomv2r DANX0F72+qpEAqxrD5YCexdhv+/WeO3YoEECgqRhCLbG71OzREfN2lrgl7vGpqTA bUDJK2RxL4yeARU9WcHT2mXplK5w0w63IdgM8kQdodEPHTlP//lafUDq87PjrcTY eUehLBvtclbEo9bmmnN4JOGNMywVXCw2lQIDAQABozUwMzAOBgNVHQ8BAf8EBAMC BaAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIwADANBgkqhkiG9w0B AQsFAAOCAQEABn9FAdcE+N7upOIU2yWalEe0YQgyTELF9MTstJAeJP/xSnCqF6TG /TfR0IuY/RJyXDLq2rHhrUEsRCCamlQyNkE8RSiHQD/kBf/xxSKobXQyMedXBKSC MHF2h+S/2HmZaOtgG4RnXplCpHegFOhcLORBLbyQJ72DPLvQcCo2A9uyboqKbZhs 0Gh5kSgZrvphvxIerbV5T/VWLO0llhFmU55BIalVpHD7YfMCOkjVL+Y/0fYKL5ij 68/BQAVGtO+1W1AW52eSMoH1gbvYemf+RsxdE/yKCmcTcZer8HswkQzPH03XcMwu V611eTJ/uJO6FTt9/5IN8G1qBj2bdNj/uA== -----END CERTIFICATE----- ` signingKey := ` -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAoEf2+WIjOLOpVBdV6HpgdEgNklJWGNW5kpinW75F2U14/hzn SqY+JbtEPz7MXeWIagpC3gzSNM7Khtdm/jQjdnZuRhRzbBXILCrdRykewUhXsKdt pNpwbUkCgy7V861zOtwFo3Wm7J7UZIrNqYK8fJrE2YZve9rMyKj1zOVPv6Lm8ioo mv2rDANX0F72+qpEAqxrD5YCexdhv+/WeO3YoEECgqRhCLbG71OzREfN2lrgl7vG pqTAbUDJK2RxL4yeARU9WcHT2mXplK5w0w63IdgM8kQdodEPHTlP//lafUDq87Pj rcTYeUehLBvtclbEo9bmmnN4JOGNMywVXCw2lQIDAQABAoIBAFzg9uwSg2iDK9dP 4ndiGuynKD4nOj8P8oZRsYGHZACFVVyjsR/f79l7iBPCNzkeHoucQJ1d/p2dS10S C1u5KOenv0Ua6ruyb5mwiSOIX4sPeckjbHUAI/AgQ7Vy+YZId6KfByFutvkdHOTa Tk0xNjpakUGgFpBF/S82QaGnLCxWtdSvuIZTzhC9bQGL+7TjgZknTqZUhYHLbgH3 XUBLV/Zavce77DJ02YtcZL9UphlWbuZuOF1RESn3Rk7MM3rzLTpjrDzp+EWM9T0H 4B1Zj4PIlVGdjEwUzHfK39KQYOGqhZE6O6Z8mm9H1V3+EaoCjFV6Nt3HwAXvJttc /K/HykECgYEAwg+zCnsPlfI0FuT5W7Fi4bLSRV1IxW/BueR3ct2KUVqieP9DzmZB NEI3ibn+/1MoUjyjAMROq8YBQ/oSpjvez/SqFbJ3xH1zQtAwhcO+3wU1GwftAah5 ZAtSJYRd6AQr1kaj+P5ZEqdxI9MJEPzsOR0eRKiPLVLF+OoDjpb0hkUCgYEA03Ap mjYXiVSzo0NVEcP7f4k+t2Wwoms7O4xZfLuSmvNjhrZmukuu3TIYaCbW8x4wyBe/ Vfe8W4HFuu5IyrHXt/7BYWtSFlKsUyc5sveSktAXuVnZePlowm/NPjJ0EE38I0WV aHWRlUW4H8j9ghwLKlea77+nfY/Q+pba8Ccc3BECgYEAqJD4hY8Vn7sOUiC9FU/F Q6WQDp6UGqQT1ARHWahkgHxJCu84l+2sj9dA5MqCXIiASsbPFFhwuba53LE5R9pT lbHBmC046Z3K4+txao/4mUKtuXguADW2lBddWKdc5q/Q4ETmI9/TwWde2K50fqQk EQxhAWSlUcpHmwqy4kXvyz0CgYBtRQDrBlthiJmRnUGAfeUigv4bb306Yupomt7A XHumgnQD8Y3jZyuGetYsNS5O1GJndgZW2kHIlKdoNK7/uar/FrQ/sWPpz23pR1NF Tza7krk/+9Qs9dAS9A6AvzhGGNdeLx7IrkG/gBloq8l/jRikGEQk9MoNVN6uMnoR NFVw0QKBgH2RW41bzJOJcWnArZR/qp6RT23SQeujOMcRGfH25jpoXU8fKup1Npt8 MnMxUAuP09HIovhn841Y7p+hlh4gSpsvYjLfgX0jyzJPhOmtBu0vEY7fLN6kQLiW RRoQIlr5T8PG4vXwsn2/hohILCJJyHAee/4gIq42jLu6hQsQxcoy -----END RSA PRIVATE KEY----- ` opts := &IstioCAOptions{ SigningCertBytes: []byte(signingCert), SigningKeyBytes: []byte(signingKey), RootCertBytes: []byte(rootCert), } ca, err := NewIstioCA(opts) if ca != nil || err == nil { t.Errorf("Expecting an error but an Istio CA is wrongly instantiated") } errMsg := "invalid parameters: cannot verify the signing cert with the provided root chain and cert pool" if err.Error() != errMsg { t.Errorf("Unexpected error message: expecting '%s' but the actual is '%s'", errMsg, err.Error()) } } func TestSignCSR(t *testing.T) { host := "spiffe://example.com/ns/foo/sa/bar" opts := CertOptions{ Host: host, Org: "istio.io", RSAKeySize: 512, } csrPEM, keyPEM, err := GenCSR(opts) if err != nil { t.Error(err) } ca, err := createCA() if err != nil { t.Error(err) } certPEM, err := ca.Sign(csrPEM) if err != nil { t.Error(err) } fields := &testutil.VerifyFields{ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, } if err = testutil.VerifyCertificate(keyPEM, certPEM, ca.GetRootCertificate(), host, fields); err != nil { t.Error(err) } cert, err := pki.ParsePemEncodedCertificate(certPEM) if err != nil { t.Error(err) } san := pki.ExtractSANExtension(cert.Extensions) if san == nil { t.Errorf("No SAN extension is found in the certificate") } expected := buildSubjectAltNameExtension(host) if !reflect.DeepEqual(expected, san) { t.Errorf("Unexpected extensions: wanted %v but got %v", expected, san) } } func createCA() (CertificateAuthority, error) { start := time.Now().Add(-5 * time.Minute) end := start.Add(24 * time.Hour) // Generate root CA key and cert. rootCAOpts := CertOptions{ IsCA: true, IsSelfSigned: true, NotAfter: end, NotBefore: start, Org: "Root CA", RSAKeySize: 1024, } rootCertBytes, rootKeyBytes := GenCert(rootCAOpts) rootCert, err := pki.ParsePemEncodedCertificate(rootCertBytes) if err != nil { return nil, err } rootKey, err := pki.ParsePemEncodedKey(rootKeyBytes) if err != nil { return nil, err } intermediateCAOpts := CertOptions{ IsCA: true, IsSelfSigned: false, NotAfter: end, NotBefore: start, Org: "Intermediate CA", RSAKeySize: 1024, SignerCert: rootCert, SignerPriv: rootKey, } intermediateCert, intermediateKey := GenCert(intermediateCAOpts) caOpts := &IstioCAOptions{ CertChainBytes: intermediateCert, CertTTL: time.Hour, SigningCertBytes: intermediateCert, SigningKeyBytes: intermediateKey, RootCertBytes: rootCertBytes, } return NewIstioCA(caOpts) } // TODO(wattli): move the two functions below as a util function to share with secret_test.go func createSecret(namespace, signingCert, signingKey, rootCert string) *v1.Secret { return &v1.Secret{ Data: map[string][]byte{ cACertID: []byte(signingCert), cAPrivateKeyID: []byte(signingKey), }, ObjectMeta: metav1.ObjectMeta{ Name: cASecret, Namespace: namespace, }, Type: istioCASecretType, } }
security/pkg/pki/ca/ca_test.go
1
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.9987916350364685, 0.13920816779136658, 0.00016028333629947156, 0.0005393117316998541, 0.3398783802986145 ]
{ "id": 4, "code_window": [ "func TestSignCSR(t *testing.T) {\n", "\thost := \"spiffe://example.com/ns/foo/sa/bar\"\n", "\topts := CertOptions{\n", "\t\tHost: host,\n", "\t\tOrg: \"istio.io\",\n", "\t\tRSAKeySize: 512,\n", "\t}\n", "\tcsrPEM, keyPEM, err := GenCSR(opts)\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 323 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package crd import ( "context" "errors" "reflect" "sync" "sync/atomic" "testing" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/discovery" "k8s.io/client-go/discovery/fake" "k8s.io/client-go/rest" k8stesting "k8s.io/client-go/testing" "k8s.io/client-go/tools/cache" "istio.io/istio/mixer/pkg/config/store" ) // The "retryTimeout" used by the test. const testingRetryTimeout = 10 * time.Millisecond // The timeout for "waitFor" function, waiting for the expected event to come. const waitForTimeout = time.Second func createFakeDiscovery(*rest.Config) (discovery.DiscoveryInterface, error) { return &fake.FakeDiscovery{ Fake: &k8stesting.Fake{ Resources: []*metav1.APIResourceList{ { GroupVersion: apiGroupVersion, APIResources: []metav1.APIResource{ {Name: "handlers", SingularName: "handler", Kind: "Handler", Namespaced: true}, {Name: "actions", SingularName: "action", Kind: "Action", Namespaced: true}, }, }, }, }, }, nil } type dummyListerWatcherBuilder struct { mu sync.RWMutex data map[store.Key]*unstructured.Unstructured watchers map[string]*watch.RaceFreeFakeWatcher } func (d *dummyListerWatcherBuilder) build(res metav1.APIResource) cache.ListerWatcher { w := watch.NewRaceFreeFake() d.mu.Lock() d.watchers[res.Kind] = w d.mu.Unlock() return &cache.ListWatch{ ListFunc: func(metav1.ListOptions) (runtime.Object, error) { list := &unstructured.UnstructuredList{} d.mu.RLock() for k, v := range d.data { if k.Kind == res.Kind { list.Items = append(list.Items, *v) } } d.mu.RUnlock() return list, nil }, WatchFunc: func(metav1.ListOptions) (watch.Interface, error) { return w, nil }, } } func (d *dummyListerWatcherBuilder) put(key store.Key, spec map[string]interface{}) error { res := &unstructured.Unstructured{} res.SetKind(key.Kind) res.SetAPIVersion(apiGroupVersion) res.SetName(key.Name) res.SetNamespace(key.Namespace) res.Object["spec"] = spec d.mu.Lock() defer d.mu.Unlock() _, existed := d.data[key] d.data[key] = res w, ok := d.watchers[key.Kind] if !ok { return nil } if existed { w.Modify(res) } else { w.Add(res) } return nil } func (d *dummyListerWatcherBuilder) delete(key store.Key) { d.mu.Lock() defer d.mu.Unlock() value, ok := d.data[key] if !ok { return } delete(d.data, key) w, ok := d.watchers[key.Kind] if !ok { return } w.Delete(value) } func getTempClient() (*Store, string, *dummyListerWatcherBuilder) { retryInterval = 0 ns := "istio-mixer-testing" lw := &dummyListerWatcherBuilder{ data: map[store.Key]*unstructured.Unstructured{}, watchers: map[string]*watch.RaceFreeFakeWatcher{}, } client := &Store{ conf: &rest.Config{}, retryTimeout: testingRetryTimeout, discoveryBuilder: createFakeDiscovery, listerWatcherBuilder: func(*rest.Config) (listerWatcherBuilderInterface, error) { return lw, nil }, } return client, ns, lw } func waitFor(wch <-chan store.BackendEvent, ct store.ChangeType, key store.Key) error { timeout := time.After(waitForTimeout) for { select { case ev := <-wch: if ev.Key == key && ev.Type == ct { return nil } case <-timeout: return context.DeadlineExceeded } } } func TestStore(t *testing.T) { s, ns, lw := getTempClient() ctx, cancel := context.WithCancel(context.Background()) defer cancel() if err := s.Init(ctx, []string{"Handler", "Action"}); err != nil { t.Fatal(err.Error()) } wch, err := s.Watch(ctx) if err != nil { t.Fatal(err.Error()) } k := store.Key{Kind: "Handler", Namespace: ns, Name: "default"} if _, err = s.Get(k); err != store.ErrNotFound { t.Errorf("Got %v, Want ErrNotFound", err) } h := map[string]interface{}{"name": "default", "adapter": "noop"} if err = lw.put(k, h); err != nil { t.Errorf("Got %v, Want nil", err) } if err = waitFor(wch, store.Update, k); err != nil { t.Errorf("Got %v, Want nil", err) } h2, err := s.Get(k) if err != nil { t.Errorf("Got %v, Want nil", err) } if !reflect.DeepEqual(h, h2.Spec) { t.Errorf("Got %+v, Want %+v", h2.Spec, h) } want := map[store.Key]*store.BackEndResource{k: h2} if lst := s.List(); !reflect.DeepEqual(lst, want) { t.Errorf("Got %+v, Want %+v", lst, want) } h["adapter"] = "noop2" if err = lw.put(k, h); err != nil { t.Errorf("Got %v, Want nil", err) } h2, err = s.Get(k) if err != nil { t.Errorf("Got %v, Want nil", err) } if !reflect.DeepEqual(h, h2.Spec) { t.Errorf("Got %+v, Want %+v", h2.Spec, h) } lw.delete(k) if err = waitFor(wch, store.Delete, k); err != nil { t.Errorf("Got %v, Want nil", err) } if _, err := s.Get(k); err != store.ErrNotFound { t.Errorf("Got %v, Want ErrNotFound", err) } } func TestStoreWrongKind(t *testing.T) { s, ns, lw := getTempClient() ctx, cancel := context.WithCancel(context.Background()) defer cancel() if err := s.Init(ctx, []string{"Action"}); err != nil { t.Fatal(err.Error()) } k := store.Key{Kind: "Handler", Namespace: ns, Name: "default"} h := map[string]interface{}{"name": "default", "adapter": "noop"} if err := lw.put(k, h); err != nil { t.Error("Got nil, Want error") } if _, err := s.Get(k); err == nil { t.Errorf("Got nil, Want error") } } func TestStoreNamespaces(t *testing.T) { s, ns, lw := getTempClient() otherNS := "other-namespace" s.ns = map[string]bool{ns: true, otherNS: true} ctx, cancel := context.WithCancel(context.Background()) defer cancel() if err := s.Init(ctx, []string{"Action", "Handler"}); err != nil { t.Fatal(err) } wch, err := s.Watch(ctx) if err != nil { t.Fatal(err) } k1 := store.Key{Kind: "Handler", Namespace: ns, Name: "default"} k2 := store.Key{Kind: "Handler", Namespace: otherNS, Name: "default"} k3 := store.Key{Kind: "Handler", Namespace: "irrelevant-namespace", Name: "default"} h := map[string]interface{}{"name": "default", "adapter": "noop"} for _, k := range []store.Key{k1, k2, k3} { if err = lw.put(k, h); err != nil { t.Errorf("Got %v, Want nil", err) } } if err = waitFor(wch, store.Update, k3); err == nil { t.Error("Got nil, Want error") } list := s.List() for _, c := range []struct { key store.Key ok bool }{ {k1, true}, {k2, true}, {k3, false}, } { if _, ok := list[c.key]; ok != c.ok { t.Errorf("For key %s, Got %v, Want %v", c.key, ok, c.ok) } if _, err = s.Get(c.key); (err == nil) != c.ok { t.Errorf("For key %s, Got %v error, Want %v", c.key, err, c.ok) } } } func TestStoreFailToInit(t *testing.T) { s, _, _ := getTempClient() ctx, cancel := context.WithCancel(context.Background()) defer cancel() s.discoveryBuilder = func(*rest.Config) (discovery.DiscoveryInterface, error) { return nil, errors.New("dummy") } if err := s.Init(ctx, []string{"Handler", "Action"}); err.Error() != "dummy" { t.Errorf("Got %v, Want dummy error", err) } s.discoveryBuilder = createFakeDiscovery s.listerWatcherBuilder = func(*rest.Config) (listerWatcherBuilderInterface, error) { return nil, errors.New("dummy2") } if err := s.Init(ctx, []string{"Handler", "Action"}); err.Error() != "dummy2" { t.Errorf("Got %v, Want dummy2 error", err) } } func TestCrdsAreNotReady(t *testing.T) { emptyDiscovery := &fake.FakeDiscovery{Fake: &k8stesting.Fake{}} s, _, _ := getTempClient() s.discoveryBuilder = func(*rest.Config) (discovery.DiscoveryInterface, error) { return emptyDiscovery, nil } ctx, cancel := context.WithCancel(context.Background()) defer cancel() start := time.Now() err := s.Init(ctx, []string{"Handler", "Action"}) d := time.Since(start) if err != nil { t.Errorf("Got %v, Want nil", err) } if d < testingRetryTimeout { t.Errorf("Duration for Init %v is too short, maybe not retrying", d) } } func TestCrdsRetryMakeSucceed(t *testing.T) { fakeDiscovery := &fake.FakeDiscovery{ Fake: &k8stesting.Fake{ Resources: []*metav1.APIResourceList{ {GroupVersion: apiGroupVersion}, }, }, } callCount := 0 // Gradually increase the number of API resources. fakeDiscovery.AddReactor("get", "resource", func(k8stesting.Action) (bool, runtime.Object, error) { callCount++ if callCount == 2 { fakeDiscovery.Resources[0].APIResources = append( fakeDiscovery.Resources[0].APIResources, metav1.APIResource{Name: "handlers", SingularName: "handler", Kind: "Handler", Namespaced: true}, ) } else if callCount == 3 { fakeDiscovery.Resources[0].APIResources = append( fakeDiscovery.Resources[0].APIResources, metav1.APIResource{Name: "actions", SingularName: "action", Kind: "Action", Namespaced: true}, ) } return true, nil, nil }) s, _, _ := getTempClient() s.discoveryBuilder = func(*rest.Config) (discovery.DiscoveryInterface, error) { return fakeDiscovery, nil } // Should set a longer timeout to avoid early quitting retry loop due to lack of computational power. s.retryTimeout = 2 * time.Second ctx, cancel := context.WithCancel(context.Background()) defer cancel() err := s.Init(ctx, []string{"Handler", "Action"}) if err != nil { t.Errorf("Got %v, Want nil", err) } if callCount != 3 { t.Errorf("Got %d, Want 3", callCount) } } func TestCrdsRetryAsynchronously(t *testing.T) { fakeDiscovery := &fake.FakeDiscovery{ Fake: &k8stesting.Fake{ Resources: []*metav1.APIResourceList{ { GroupVersion: apiGroupVersion, APIResources: []metav1.APIResource{ {Name: "handlers", SingularName: "handler", Kind: "Handler", Namespaced: true}, }, }, }, }, } var count int32 // Gradually increase the number of API resources. fakeDiscovery.AddReactor("get", "resource", func(k8stesting.Action) (bool, runtime.Object, error) { if atomic.LoadInt32(&count) != 0 { fakeDiscovery.Resources[0].APIResources = append( fakeDiscovery.Resources[0].APIResources, metav1.APIResource{Name: "actions", SingularName: "action", Kind: "Action", Namespaced: true}, ) } return true, nil, nil }) s, ns, lw := getTempClient() s.discoveryBuilder = func(*rest.Config) (discovery.DiscoveryInterface, error) { return fakeDiscovery, nil } k1 := store.Key{Kind: "Handler", Namespace: ns, Name: "default"} if err := lw.put(k1, map[string]interface{}{"adapter": "noop"}); err != nil { t.Fatal(err) } ctx, cancel := context.WithCancel(context.Background()) defer cancel() if err := s.Init(ctx, []string{"Handler", "Action"}); err != nil { t.Fatal(err) } s.cacheMutex.Lock() ncaches := len(s.caches) s.cacheMutex.Unlock() if ncaches != 1 { t.Errorf("Has %d caches, Want 1 caches", ncaches) } wch, err := s.Watch(ctx) if err != nil { t.Fatal(err) } atomic.StoreInt32(&count, 1) after := time.After(time.Second / 10) tick := time.Tick(time.Millisecond) loop: for { select { case <-after: break loop case <-tick: s.cacheMutex.Lock() ncaches = len(s.caches) s.cacheMutex.Unlock() if ncaches > 1 { break loop } } } if ncaches != 2 { t.Fatalf("Has %d caches, Want 2 caches", ncaches) } k2 := store.Key{Kind: "Action", Namespace: ns, Name: "default"} if err = lw.put(k2, map[string]interface{}{"test": "value"}); err != nil { t.Error(err) } if err = waitFor(wch, store.Update, k2); err != nil { t.Errorf("Got %v, Want nil", err) } }
mixer/pkg/config/crd/store_test.go
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.0006473137182183564, 0.00019711133791133761, 0.00016173197946045548, 0.0001722616725601256, 0.00009359495743410662 ]
{ "id": 4, "code_window": [ "func TestSignCSR(t *testing.T) {\n", "\thost := \"spiffe://example.com/ns/foo/sa/bar\"\n", "\topts := CertOptions{\n", "\t\tHost: host,\n", "\t\tOrg: \"istio.io\",\n", "\t\tRSAKeySize: 512,\n", "\t}\n", "\tcsrPEM, keyPEM, err := GenCSR(opts)\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 323 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // THIS FILE IS AUTOMATICALLY GENERATED. package istio_mixer_adapter_quota import ( "context" "time" "istio.io/istio/mixer/pkg/adapter" ) // Fully qualified name of the template const TemplateName = "quota" // Instance is constructed by Mixer for the 'quota' template. // // template ... type Instance struct { // Name of the instance as specified in configuration. Name string // dimensions are ... Dimensions map[string]interface{} Int64Primitive int64 BoolPrimitive bool DoublePrimitive float64 StringPrimitive string AnotherValueType interface{} DimensionsFixedInt64ValueDType map[string]int64 TimeStamp time.Time Duration time.Duration } // HandlerBuilder must be implemented by adapters if they want to // process data associated with the 'quota' template. // // Mixer uses this interface to call into the adapter at configuration time to configure // it with adapter-specific configuration as well as all template-specific type information. type HandlerBuilder interface { adapter.HandlerBuilder // SetQuotaTypes is invoked by Mixer to pass the template-specific Type information for instances that an adapter // may receive at runtime. The type information describes the shape of the instance. SetQuotaTypes(map[string]*Type /*Instance name -> Type*/) } // Handler must be implemented by adapter code if it wants to // process data associated with the 'quota' template. // // Mixer uses this interface to call into the adapter at request time in order to dispatch // created instances to the adapter. Adapters take the incoming instances and do what they // need to achieve their primary function. // // The name of each instance can be used as a key into the Type map supplied to the adapter // at configuration time via the method 'SetQuotaTypes'. // These Type associated with an instance describes the shape of the instance type Handler interface { adapter.Handler // HandleQuota is called by Mixer at request time to deliver instances to // to an adapter. HandleQuota(context.Context, *Instance, adapter.QuotaArgs) (adapter.QuotaResult, error) }
mixer/tools/codegen/pkg/interfacegen/testdata/quota_handler.gen.go
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00022039485338609666, 0.00017471324827056378, 0.00016162052634172142, 0.000168946324265562, 0.000016997915736283176 ]
{ "id": 4, "code_window": [ "func TestSignCSR(t *testing.T) {\n", "\thost := \"spiffe://example.com/ns/foo/sa/bar\"\n", "\topts := CertOptions{\n", "\t\tHost: host,\n", "\t\tOrg: \"istio.io\",\n", "\t\tRSAKeySize: 512,\n", "\t}\n", "\tcsrPEM, keyPEM, err := GenCSR(opts)\n", "\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 323 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // THIS FILE IS AUTOMATICALLY GENERATED. package metric import ( "context" "istio.io/istio/mixer/pkg/adapter" ) // Fully qualified name of the template const TemplateName = "metric" // Instance is constructed by Mixer for the 'metric' template. // // Metric represents a single piece of data to report. // // When writing the configuration, the value for the fields associated with this template can either be a // literal or an [expression](https://istio.io/docs/reference/config/mixer/expression-language.html). Please note that if the datatype of a field is not istio.mixer.v1.config.descriptor.ValueType, // then the expression's [inferred type](https://istio.io/docs/reference/config/mixer/expression-language.html#type-checking) must match the datatype of the field. // // Example config: // ``` // apiVersion: "config.istio.io/v1alpha2" // kind: metric // metadata: // name: requestsize // namespace: istio-system // spec: // value: request.size | 0 // dimensions: // source_service: source.service | "unknown" // source_version: source.labels["version"] | "unknown" // destination_service: destination.service | "unknown" // destination_version: destination.labels["version"] | "unknown" // response_code: response.code | 200 // monitored_resource_type: '"UNSPECIFIED"' // ``` type Instance struct { // Name of the instance as specified in configuration. Name string // The value being reported. Value interface{} // The unique identity of the particular metric to report. Dimensions map[string]interface{} // Optional. An expression to compute the type of the monitored resource this metric is being reported on. // If the metric backend supports monitored resources, these fields are used to populate that resource. Otherwise // these fields will be ignored by the adapter. MonitoredResourceType string // Optional. A set of expressions that will form the dimensions of the monitored resource this metric is being reported on. // If the metric backend supports monitored resources, these fields are used to populate that resource. Otherwise // these fields will be ignored by the adapter. MonitoredResourceDimensions map[string]interface{} } // HandlerBuilder must be implemented by adapters if they want to // process data associated with the 'metric' template. // // Mixer uses this interface to call into the adapter at configuration time to configure // it with adapter-specific configuration as well as all template-specific type information. type HandlerBuilder interface { adapter.HandlerBuilder // SetMetricTypes is invoked by Mixer to pass the template-specific Type information for instances that an adapter // may receive at runtime. The type information describes the shape of the instance. SetMetricTypes(map[string]*Type /*Instance name -> Type*/) } // Handler must be implemented by adapter code if it wants to // process data associated with the 'metric' template. // // Mixer uses this interface to call into the adapter at request time in order to dispatch // created instances to the adapter. Adapters take the incoming instances and do what they // need to achieve their primary function. // // The name of each instance can be used as a key into the Type map supplied to the adapter // at configuration time via the method 'SetMetricTypes'. // These Type associated with an instance describes the shape of the instance type Handler interface { adapter.Handler // HandleMetric is called by Mixer at request time to deliver instances to // to an adapter. HandleMetric(context.Context, []*Instance) error }
mixer/template/metric/go_default_library_handler.gen.go
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00024975393898785114, 0.0001781091559678316, 0.00016163500549737364, 0.00017064645362552255, 0.000023297319785342552 ]
{ "id": 5, "code_window": [ "\t\tIsCA: true,\n", "\t\tIsSelfSigned: true,\n", "\t\tNotAfter: end,\n", "\t\tNotBefore: start,\n", "\t\tOrg: \"Root CA\",\n", "\t\tRSAKeySize: 1024,\n", "\t}\n", "\trootCertBytes, rootKeyBytes := GenCert(rootCAOpts)\n", "\n", "\trootCert, err := pki.ParsePemEncodedCertificate(rootCertBytes)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 374 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Provide a tool to generate X.509 CSR with different options. package main import ( "flag" "fmt" "io/ioutil" "istio.io/istio/security/pkg/pki/ca" "github.com/golang/glog" ) var ( host = flag.String("host", "", "Comma-separated hostnames and IPs to generate a certificate for.") org = flag.String("organization", "Juju org", "Organization for the cert.") outCsr = flag.String("out-csr", "csr.pem", "Output csr file.") outPriv = flag.String("out-priv", "priv.pem", "Output private key file.") keySize = flag.Int("key-size", 1024, "Size of the generated private key") ) func saveCreds(csrPem []byte, privPem []byte) { err := ioutil.WriteFile(*outCsr, csrPem, 0644) if err != nil { glog.Fatalf("Could not write output certificate request: %s.", err) } err = ioutil.WriteFile(*outPriv, privPem, 0600) if err != nil { glog.Fatalf("Could not write output private key: %s.", err) } } func main() { flag.Parse() csrPem, privPem, err := ca.GenCSR(ca.CertOptions{ Host: *host, Org: *org, RSAKeySize: *keySize, }) if err != nil { glog.Fatalf("Failed to generate CSR: %s.", err) } saveCreds(csrPem, privPem) fmt.Printf("Certificate and private files successfully saved in %s and %s\n", *outCsr, *outPriv) }
security/cmd/generate_csr/main.go
1
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.0004356384160928428, 0.0002352233714191243, 0.00016481617058161646, 0.00017897351062856615, 0.00009345112630398944 ]
{ "id": 5, "code_window": [ "\t\tIsCA: true,\n", "\t\tIsSelfSigned: true,\n", "\t\tNotAfter: end,\n", "\t\tNotBefore: start,\n", "\t\tOrg: \"Root CA\",\n", "\t\tRSAKeySize: 1024,\n", "\t}\n", "\trootCertBytes, rootKeyBytes := GenCert(rootCAOpts)\n", "\n", "\trootCert, err := pki.ParsePemEncodedCertificate(rootCertBytes)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 374 }
// Copyright 2017 Istio Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aspect import ( "errors" "net" "reflect" "testing" dpb "istio.io/api/mixer/v1/config/descriptor" "istio.io/istio/mixer/pkg/adapter" "istio.io/istio/mixer/pkg/adapter/test" apb "istio.io/istio/mixer/pkg/aspect/config" atest "istio.io/istio/mixer/pkg/aspect/test" "istio.io/istio/mixer/pkg/attribute" "istio.io/istio/mixer/pkg/config" cfgpb "istio.io/istio/mixer/pkg/config/proto" "istio.io/istio/mixer/pkg/expr" "istio.io/istio/mixer/pkg/status" ) var ( requestCountDesc = &dpb.MetricDescriptor{ Name: "request_count", Kind: dpb.COUNTER, Value: dpb.INT64, Description: "request count by source, target, service, and code", Labels: map[string]dpb.ValueType{ "source": dpb.STRING, "target": dpb.STRING, "service": dpb.STRING, "method": dpb.STRING, "response_code": dpb.INT64, }, } requestLatencyDesc = &dpb.MetricDescriptor{ Name: "request_latency", Kind: dpb.COUNTER, Value: dpb.DURATION, Description: "request latency by source, target, and service", Labels: map[string]dpb.ValueType{ "source": dpb.STRING, "target": dpb.STRING, "service": dpb.STRING, "method": dpb.STRING, "response_code": dpb.INT64, }, } df = atest.NewDescriptorFinder(map[string]interface{}{ "request_count": requestCountDesc, "request_latency": requestLatencyDesc, }) ) func TestAttributeGeneratorManager(t *testing.T) { m := newAttrGenMgr() if m.Kind() != config.AttributesKind { t.Errorf("m.Kind() = %s; wanted %s", m.Kind(), config.AttributesKindName) } eval, _ := expr.NewCEXLEvaluator(expr.DefaultCacheSize) if err := m.ValidateConfig(m.DefaultConfig(), eval, nil); err != nil { t.Errorf("ValidateConfig(DefaultConfig()) produced an error: %v", err) } if err := m.ValidateConfig(&apb.AttributesGeneratorParams{}, eval, df); err != nil { t.Error("ValidateConfig(AttributeGeneratorsParams{}) should not produce an error.") } } func TestAttrGenMgr_ValidateConfig(t *testing.T) { dfind := atest.NewDescriptorFinder(map[string]interface{}{ "int64": &cfgpb.AttributeManifest_AttributeInfo{ValueType: dpb.INT64}, "duration": &cfgpb.AttributeManifest_AttributeInfo{ValueType: dpb.DURATION}, "source_ip": &cfgpb.AttributeManifest_AttributeInfo{}, }) validExpr := &apb.AttributesGeneratorParams{ InputExpressions: map[string]string{ "valid_int": "42 | int64", "valid_duration": "\"42ms\" | duration", }, } badExpr := &apb.AttributesGeneratorParams{ InputExpressions: map[string]string{ "bad_expr": "int64 | duration", }, } foundAttr := &apb.AttributesGeneratorParams{ AttributeBindings: map[string]string{"source_ip": "srcPodIP"}, } notFoundAttr := &apb.AttributesGeneratorParams{ AttributeBindings: map[string]string{"not_found": "srcPodIP"}, } tests := []struct { name string params *apb.AttributesGeneratorParams wantErr bool }{ {"valid input expressions", validExpr, false}, {"invalid input expressions", badExpr, true}, {"valid attribute binding", foundAttr, false}, {"invalid attribute binding", notFoundAttr, true}, } m := newAttrGenMgr() for _, v := range tests { t.Run(v.name, func(t *testing.T) { eval, _ := expr.NewCEXLEvaluator(expr.DefaultCacheSize) err := m.ValidateConfig(v.params, eval, dfind) if err != nil && !v.wantErr { t.Errorf("Unexpected error '%v' for config: %#v", err, v.params) } if err == nil && v.wantErr { t.Errorf("Expected error for config: %#v", v.params) } }) } } type testAttrGen struct { adapter.AttributesGenerator out map[string]interface{} closed bool returnErr bool } type testAttrGenBuilder struct { adapter.DefaultBuilder returnErr bool } func newTestAttrGenBuilder(returnErr bool) testAttrGenBuilder { return testAttrGenBuilder{adapter.NewDefaultBuilder("test", "test", nil), returnErr} } func (t testAttrGenBuilder) BuildAttributesGenerator(env adapter.Env, c adapter.Config) (adapter.AttributesGenerator, error) { if t.returnErr { return nil, errors.New("error") } return &testAttrGen{}, nil } func TestAttributeGeneratorManager_NewPreprocessExecutor(t *testing.T) { tests := []struct { name string builder adapter.Builder wantErr bool }{ {"no error", newTestAttrGenBuilder(false), false}, {"build error", newTestAttrGenBuilder(true), true}, } m := newAttrGenMgr() c := &cfgpb.Combined{ Builder: &cfgpb.Adapter{Params: &apb.AttributesGeneratorParams{}}, Aspect: &cfgpb.Aspect{Params: &apb.AttributesGeneratorParams{ AttributeBindings: map[string]string{"service_found": "found", "source_service": "srcSvc"}, }}, } for _, v := range tests { t.Run(v.name, func(t *testing.T) { f, _ := FromBuilder(v.builder, config.AttributesKind) exec, err := m.NewPreprocessExecutor(c, f, test.NewEnv(t), nil) if err == nil && v.wantErr { t.Error("Expected to receive error") } if err != nil { if !v.wantErr { t.Errorf("Unexpected error: %v", err) } return } for attrName, valName := range c.Aspect.Params.(*apb.AttributesGeneratorParams).AttributeBindings { found := false for boundVal, boundAttr := range exec.(*attrGenExec).bindings { if boundVal == valName && boundAttr == attrName { found = true break } } if found { continue } t.Errorf("Bindings map missing binding from %s to %s", valName, attrName) } }) } } func (t testAttrGen) Generate(map[string]interface{}) (map[string]interface{}, error) { if t.returnErr { return nil, errors.New("generate error") } return t.out, nil } func TestAttributeGeneratorExecutor_Execute(t *testing.T) { genParams := &apb.AttributesGeneratorParams{ InputExpressions: map[string]string{"pod.ip": "source_ip"}, AttributeBindings: map[string]string{ "service_found": "found", "source_service": "srcSvc", "destination_ip": "destIP", "ip_v6": "v6IP", }, } bMap := map[string]string{"found": "service_found", "srcSvc": "source_service", "destIP": "destination_ip", "v6IP": "ip_v6"} inBag := attribute.GetFakeMutableBagForTesting(map[string]interface{}{"source_ip": []byte(net.IP("10.1.1.10").To4())}) outMap := map[string]interface{}{ "found": true, "srcSvc": "service1", "destIP": net.ParseIP("10.34.23.3"), "v6IP": net.ParseIP("2001:db8::1"), } wantBag := attribute.GetMutableBag(nil) wantBag.Set("service_found", true) wantBag.Set("source_service", "service1") wantBag.Set("destination_ip", []byte{0xa, 0x22, 0x17, 0x3}) wantBag.Set("ip_v6", []byte{0x20, 0x1, 0xd, 0xb8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1}) extraOutMap := map[string]interface{}{ "found": true, "srcSvc": "service1", "destIP": net.ParseIP("10.34.23.3"), "v6IP": net.ParseIP("2001:db8::1"), "shouldBeStripped": "never_used", } tests := []struct { name string exec attrGenExec attrs attribute.Bag eval expr.Evaluator wantAttrs attribute.Bag wantErr bool }{ {"no error", attrGenExec{&testAttrGen{out: outMap}, genParams, bMap}, inBag, atest.NewIDEval(), wantBag, false}, {"strippped attrs", attrGenExec{&testAttrGen{out: extraOutMap}, genParams, bMap}, inBag, atest.NewIDEval(), wantBag, false}, {"generate error", attrGenExec{&testAttrGen{out: outMap, returnErr: true}, genParams, bMap}, inBag, atest.NewIDEval(), wantBag, true}, {"eval error", attrGenExec{&testAttrGen{}, genParams, bMap}, inBag, atest.NewErrEval(), wantBag, true}, } for _, v := range tests { t.Run(v.name, func(t *testing.T) { got, s := v.exec.Execute(v.attrs, v.eval) if status.IsOK(s) && v.wantErr { t.Fatal("Expected to receive error") } if !status.IsOK(s) { if !v.wantErr { t.Fatalf("Unexpected status returned: %v", s) } return } for _, n := range v.wantAttrs.Names() { wantVal, _ := v.wantAttrs.Get(n) gotVal, ok := got.Attrs.Get(n) if !ok { t.Errorf("Generated attribute.Bag missing attribute %s", n) } if !reflect.DeepEqual(gotVal, wantVal) { t.Errorf("For attribute '%s': got value %v, want %v", n, gotVal, wantVal) } } }) } } func (t *testAttrGen) Close() error { t.closed = true return nil } func TestAttributeGeneratorExecutor_Close(t *testing.T) { inner := &testAttrGen{closed: false} executor := &attrGenExec{aspect: inner} if err := executor.Close(); err != nil { t.Errorf("Close() returned an error: %v", err) } if !inner.closed { t.Error("Close() should propagate to wrapped aspect.") } }
mixer/pkg/aspect/attrgenmgr_test.go
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00018731133604887873, 0.00017328133981209248, 0.00016150929150171578, 0.00017296808073297143, 0.000004900129624729743 ]
{ "id": 5, "code_window": [ "\t\tIsCA: true,\n", "\t\tIsSelfSigned: true,\n", "\t\tNotAfter: end,\n", "\t\tNotBefore: start,\n", "\t\tOrg: \"Root CA\",\n", "\t\tRSAKeySize: 1024,\n", "\t}\n", "\trootCertBytes, rootKeyBytes := GenCert(rootCAOpts)\n", "\n", "\trootCert, err := pki.ParsePemEncodedCertificate(rootCertBytes)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 374 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package status import ( "errors" "testing" "github.com/gogo/protobuf/proto" rpc "github.com/googleapis/googleapis/google/rpc" multierror "github.com/hashicorp/go-multierror" ) func TestStatus(t *testing.T) { if !IsOK(OK) { t.Error("Expecting the OK status to actually be, well, you know, OK...") } s := New(rpc.ABORTED) if s.Code != int32(rpc.ABORTED) { t.Errorf("Got %v, expected rpc.ABORTED", s.Code) } s = WithMessage(rpc.ABORTED, "Aborted!") if s.Code != int32(rpc.ABORTED) || s.Message != "Aborted!" { t.Errorf("Got %v %v, expected rpc.ABORTED Aborted!", s.Code, s.Message) } s = WithError(errors.New("aborted")) if s.Code != int32(rpc.INTERNAL) || s.Message != "aborted" { t.Errorf("Got %v %v, expected rpc.INTERNAL aborted", s.Code, s.Message) } s = WithInternal("Aborted!") if s.Code != int32(rpc.INTERNAL) || s.Message != "Aborted!" { t.Errorf("Got %v %v, expected rpc.INTERNAL Aborted!", s.Code, s.Message) } s = WithCancelled("Aborted!") if s.Code != int32(rpc.CANCELLED) || s.Message != "Aborted!" { t.Errorf("Got %v %v, expected rpc.CANCELLED Aborted!", s.Code, s.Message) } s = WithPermissionDenied("Aborted!") if s.Code != int32(rpc.PERMISSION_DENIED) || s.Message != "Aborted!" { t.Errorf("Got %v %v, expected rpc.PERMISSION_DENIED Aborted!", s.Code, s.Message) } s = WithInvalidArgument("Aborted!") if s.Code != int32(rpc.INVALID_ARGUMENT) || s.Message != "Aborted!" { t.Errorf("Got %v %v, expected rpc.INVALID_ARGUMENT Aborted!", s.Code, s.Message) } s = WithResourceExhausted("Aborted!") if s.Code != int32(rpc.RESOURCE_EXHAUSTED) || s.Message != "Aborted!" { t.Errorf("Got %v %v, expected rpc.RESOURCE_EXHAUSTED Aborted!", s.Code, s.Message) } s = WithDeadlineExceeded("Aborted!") if s.Code != int32(rpc.DEADLINE_EXCEEDED) || s.Message != "Aborted!" { t.Errorf("Got %v %v, expected rpc.DEADLINE_EXCEEDED Aborted!", s.Code, s.Message) } s = InvalidWithDetails("Invalid", NewBadRequest("test", errors.New("error"))) if s.Code != int32(rpc.INVALID_ARGUMENT) && s.Message != "Invalid" && len(s.Details) != 1 { t.Errorf("Got %v, expected status with code = rpc.INVALID_ARGUMENT and populated details", s) } } func TestNewBadRequest(t *testing.T) { me := multierror.Append(errors.New("error one"), errors.New("error two")) cases := []struct { name string field string err error want *rpc.BadRequest }{ {"simple error", "field", errors.New("error"), newBadReq(newViolation("error"))}, {"go-multierror", "field", me, newBadReq(newViolation("error one"), newViolation("error two"))}, } for _, v := range cases { t.Run(v.name, func(t *testing.T) { got := NewBadRequest(v.field, v.err) if !proto.Equal(got, v.want) { t.Fatalf("Got %v, want %v", got, v.want) } }) } } func newViolation(desc string) *rpc.BadRequest_FieldViolation { return &rpc.BadRequest_FieldViolation{Field: "field", Description: desc} } func newBadReq(violations ...*rpc.BadRequest_FieldViolation) *rpc.BadRequest { return &rpc.BadRequest{FieldViolations: violations} }
mixer/pkg/status/status_test.go
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00017897351062856615, 0.00017347362881992012, 0.00016510352725163102, 0.00017442257376387715, 0.000003312589115012088 ]
{ "id": 5, "code_window": [ "\t\tIsCA: true,\n", "\t\tIsSelfSigned: true,\n", "\t\tNotAfter: end,\n", "\t\tNotBefore: start,\n", "\t\tOrg: \"Root CA\",\n", "\t\tRSAKeySize: 1024,\n", "\t}\n", "\trootCertBytes, rootKeyBytes := GenCert(rootCAOpts)\n", "\n", "\trootCert, err := pki.ParsePemEncodedCertificate(rootCertBytes)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 374 }
#!/bin/bash set -ex WORKSPACE="$(bazel info workspace)" source "${WORKSPACE}/bin/use_bazel_go.sh" cd ${WORKSPACE} bazel ${BAZEL_STARTUP_ARGS} build ${BAZEL_RUN_ARGS} \ //... $(bazel query 'tests(//...)') @com_github_bazelbuild_buildtools//buildifier buildifier="$(bazel info bazel-bin)/external/com_github_bazelbuild_buildtools/buildifier/buildifier" NUM_CPU=$(getconf _NPROCESSORS_ONLN) if [[ -z $SKIP_INIT ]];then bin/init.sh fi echo 'Running linters .... in advisory mode' docker run\ -v $(bazel info output_base):$(bazel info output_base)\ -v $(pwd):/go/src/istio.io/istio\ -w /go/src/istio.io/istio\ gcr.io/istio-testing/linter:bfcc1d6942136fd86eb6f1a6fb328de8398fbd80\ --config=./lintconfig.json \ ./... || true echo 'linters OK' echo 'Checking licences' bin/check_license.sh || true echo 'licences OK' echo 'Running buildifier ...' ${buildifier} -showlog -mode=check $(git ls-files \ | grep -e 'BUILD' -e 'WORKSPACE' -e '.*\.bazel' -e '.*\.bzl' \ | grep -v vendor) || true echo 'buildifer OK'
bin/linters.sh
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00017548519826959819, 0.00017235256382264197, 0.0001671776844887063, 0.00017337370081804693, 0.0000031096139991859673 ]
{ "id": 6, "code_window": [ "\t\tIsSelfSigned: false,\n", "\t\tNotAfter: end,\n", "\t\tNotBefore: start,\n", "\t\tOrg: \"Intermediate CA\",\n", "\t\tRSAKeySize: 1024,\n", "\t\tSignerCert: rootCert,\n", "\t\tSignerPriv: rootKey,\n", "\t}\n", "\tintermediateCert, intermediateKey := GenCert(intermediateCAOpts)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 394 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ca import ( "bytes" "crypto/x509" "encoding/asn1" "fmt" "reflect" "testing" "time" "istio.io/istio/security/pkg/pki" "istio.io/istio/security/pkg/pki/testutil" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" "k8s.io/api/core/v1" ) func TestSelfSignedIstioCAWithoutSecret(t *testing.T) { certTTL := 30 * time.Minute caCertTTL := time.Hour org := "test.ca.org" caNamespace := "default" client := fake.NewSimpleClientset() ca, err := NewSelfSignedIstioCA(caCertTTL, certTTL, org, caNamespace, client.CoreV1()) if err != nil { t.Errorf("Failed to create a self-signed CA: %v", err) } name := "foo" namespace := "bar" id := fmt.Sprintf("spiffe://cluster.local/ns/%s/sa/%s", namespace, name) options := CertOptions{ Host: id, RSAKeySize: 1024, } csr, _, err := GenCSR(options) if err != nil { t.Error(err) } cb, err := ca.Sign(csr) if err != nil { t.Error(err) } rcb := ca.GetRootCertificate() certPool := x509.NewCertPool() certPool.AppendCertsFromPEM(cb) rootPool := x509.NewCertPool() rootPool.AppendCertsFromPEM(rcb) cert, err := pki.ParsePemEncodedCertificate(cb) if err != nil { t.Error(err) } if ttl := cert.NotAfter.Sub(cert.NotBefore); ttl != certTTL { t.Errorf("Unexpected certificate TTL (expecting %v, actual %v)", certTTL, ttl) } rootCert, err := pki.ParsePemEncodedCertificate(rcb) if err != nil { t.Error(err) } if ttl := rootCert.NotAfter.Sub(rootCert.NotBefore); ttl != caCertTTL { t.Errorf("Unexpected CA certificate TTL (expecting %v, actual %v)", caCertTTL, ttl) } if certOrg := rootCert.Issuer.Organization[0]; certOrg != org { t.Errorf("Unexpected CA certificate organization (expecting %v, actual %v)", org, certOrg) } chain, err := cert.Verify(x509.VerifyOptions{ Intermediates: certPool, Roots: rootPool, }) if len(chain) == 0 || err != nil { t.Error("Failed to verify generated cert") } san := pki.ExtractSANExtension(cert.Extensions) if san == nil { t.Errorf("Generated certificate does not contain a SAN field") } rv := asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(id)} bs, err := asn1.Marshal([]asn1.RawValue{rv}) if err != nil { t.Error(err) } if !bytes.Equal(bs, san.Value) { t.Errorf("SAN field does not match: %s is expected but actual is %s", bs, san.Value) } caSecret, err := client.CoreV1().Secrets("default").Get(cASecret, metav1.GetOptions{}) if err != nil { t.Errorf("Failed to get secret (error: %s)", err) } signingCert, err := pki.ParsePemEncodedCertificate(caSecret.Data[cACertID]) if err != nil { t.Errorf("Failed to parse cert (error: %s)", err) } if !signingCert.Equal(ca.signingCert) { t.Error("Cert does not match") } if len(ca.certChainBytes) > 0 { t.Error("CertChain should be empty") } rootCertBytes := copyBytes(caSecret.Data[cACertID]) if !bytes.Equal(ca.rootCertBytes, rootCertBytes) { t.Error("Root cert does not match") } } func TestSelfSignedIstioCAWithSecret(t *testing.T) { rootCert := ` -----BEGIN CERTIFICATE----- MIIC5jCCAc6gAwIBAgIRAO1DMLWq99XL/B2kRlNpnikwDQYJKoZIhvcNAQELBQAw HDEaMBgGA1UEChMRazhzLmNsdXN0ZXIubG9jYWwwHhcNMTcwOTIwMjMxODQwWhcN MTgwOTIwMjMxODQwWjAcMRowGAYDVQQKExFrOHMuY2x1c3Rlci5sb2NhbDCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKYSyDbjRlYuyyYJOuZQHiG9wOsn M4Rx/wWTJUOQthYz3uIBnR0WSMdyJ25VdpitHqDOR4hJo33DxNmknMnXhAuyVZoq YpoSx/UdlOBYNQivy6OCRxe3LuDbJ5+wNZ4y3OoEqMQjxWPWcL6iyaYHyVEJprMm IhjHD9yedJaX3F7pN0hosdtkfEsBkfcK5VPx99ekbAEo8DcsopG+XvNuT4nb7ww9 wd9VtGA8upmgNOCJvkLGVHwybw67LL4T7nejdUQd9T7o7CfAXGmBlkuGWHnsbeOe QtCfHD3+6iCmRjcSUK6AfGnfcHTjbwzGjv48JPFaNbjm2hLixC0TdAdPousCAwEA AaMjMCEwDgYDVR0PAQH/BAQDAgIEMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN AQELBQADggEBAHV5DdWspKxjeE4BsjnsA3oSkTBnbmUkMGFUtIgAvSlULYy3Wl4O bAj7VfxIegZbE3tnkuky9BwVCoBD+d2zIqCZ5Xl17+ki6cttLAFWni85cg9gX8a6 2p/EMefUYxLXEdZTw80eAB56/34Xkt6g/CnB531W8vOvjTzg25qClkA7TjVIil2+ kLAXl8xEp48cvAxX4FslgAlBPagpJYbjVM0BjQbgmGLg1rjoH/jbkQJyIabX5dSq 9fdQYxkTzYnvcvgHf4WSl/awopjsI1NhNv07+qE8ie86EoYJgXPrNtlytyqSvIXQ 2ETBxlxOg3DdlBwhBz/Hg31tCLv8E8U8fqQ= -----END CERTIFICATE----- ` // Use the same signing cert and root cert for self-signed CA. signingCert := rootCert signingKey := ` -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAphLINuNGVi7LJgk65lAeIb3A6yczhHH/BZMlQ5C2FjPe4gGd HRZIx3InblV2mK0eoM5HiEmjfcPE2aScydeEC7JVmipimhLH9R2U4Fg1CK/Lo4JH F7cu4Nsnn7A1njLc6gSoxCPFY9ZwvqLJpgfJUQmmsyYiGMcP3J50lpfcXuk3SGix 22R8SwGR9wrlU/H316RsASjwNyyikb5e825PidvvDD3B31W0YDy6maA04Im+QsZU fDJvDrssvhPud6N1RB31PujsJ8BcaYGWS4ZYeext455C0J8cPf7qIKZGNxJQroB8 ad9wdONvDMaO/jwk8Vo1uObaEuLELRN0B0+i6wIDAQABAoIBAHzHVelvoFR2uips +vU7MziU0xOcE6gq4rr0kSYP39AUzx0uqzbEnJBGY/wReJdEU+PsuXBcK9v9sLT6 atd493y2VH0N5aHwBI9V15ssi0RomW/UHchi2XUXFNF12wNvIe8u6wLcAZ5+651A wJPf+9HIl5i5SRsmzfMsl1ri5S/lgnjUQty4GYnT/Y53uaZoquX+sUhZ3pW8SkzX ZvKvMbj6UOiXlelDgtEGOCgftjdm916OfnQDnSOJsh/0UvM/Bn3kQJEOgwzhMy2/ +TOIB04wVN7K6ZEbSaV7gkciiDyjg0XhJqfkmOUm8kLhLFgervjrBdkUSuukdGmq TZmP1EkCgYEA194D0hslC//Qu0XtUCcJgLV4a41U/PDYIStf92FRXcqqYGBHDtzJ 1J86BuO/cjOdp+jZBjIIoECvY3n3TCacUiKvjmszMtanwz42eFPpVgSi3pZcyBF+ cLPB08dnUWxrxA46ss1g6gjPXjUXuEFkxuogrPiNwQPuwZnjrPWa580CgYEAxPLg oXZ7BFVUxDEUjokj9HsvSToJNAIu7XAc84Z00yJ8z/B/muCZtpC5CZ2ZhejwBioR AbpPEVRXFs9M2W1jW2YgO8iVcXiLT+qmNnjqGZuZnhzkMC2q9RnHrRfYMUO5bVOX bw0UqnEMo7vTLEN47FnImr6Jv9cQFXztJEVZjZcCgYAtQPrWEiC7Gj7885Tjh7uD QwfirDdT632zvm8Y4kr3eaQsHiLnZ7vcGiFFDnu1CkMTz0mn9dc/GTBrj0cbrMB6 q5DYL3sFPmDfGmy63wR8pu4p8aWzv48dO2H37sanGC6jZERD9bBKf9xRKJo3Y2Yo GS8Oc/DrtNJZvdQwDzERRQKBgGFd8c/hU1ABH7cezJrrEet8OxRorMQZkDmyg52h i4AWPL5Ql8Vp5JRtWA147L1XO9LQWTgRc6WNnMCaG9QiUEyPYMAtmjRO9BC+YQ3t GU8vrfKNNgLbkPk7lYvtjeRNJw71lJhCT0U0Pptz8CKh+NZgTNyz9kXxfPIioNqd rnhhAoGANfiSkuFuw2+WpBvTNah+wcZDNiMbvkQVhUwRvqIM6sLhRJhVZzJkTrYu YQTFeoqvepyHWE9e1Mb5dGFHMvXywZQR0hR2rpWxA2OgNaRhqL7Rh7th+V/owIi9 7lGXdUBnyY8tcLhla+Rbo7Y8yOsN6pp4grT1DP+8rG4G4vnJgbk= -----END RSA PRIVATE KEY----- ` client := fake.NewSimpleClientset() initSecret := createSecret("default", signingCert, signingKey, rootCert) _, err := client.CoreV1().Secrets("default").Create(initSecret) if err != nil { t.Errorf("Failed to create secret (error: %s)", err) } certTTL := 30 * time.Minute caCertTTL := time.Hour org := "test.ca.org" caNamespace := "default" ca, err := NewSelfSignedIstioCA(caCertTTL, certTTL, org, caNamespace, client.CoreV1()) if ca == nil || err != nil { t.Errorf("Expecting an error but an Istio CA is wrongly instantiated") } cert, err := pki.ParsePemEncodedCertificate([]byte(signingCert)) if err != nil { t.Errorf("Failed to parse cert (error: %s)", err) } if !cert.Equal(ca.signingCert) { t.Error("Cert does not match") } if len(ca.certChainBytes) > 0 { t.Error("CertChain should be empty") } rootCertBytes := copyBytes([]byte(rootCert)) if !bytes.Equal(ca.rootCertBytes, rootCertBytes) { t.Error("Root cert does not match") } } // Pass in unmatched chain and cert to make sure the `verify` method yeilds an error. func TestInvalidIstioCAOptions(t *testing.T) { rootCert := ` -----BEGIN CERTIFICATE----- MIIDXTCCAkWgAwIBAgIJAPa8VTmVboq0MA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMTcwMzE4MDAxMDI5WhcNMjcwMzE2MDAxMDI5WjBF MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAsBOcKtPZMB32Un0r0Ew8X4n12xgoW+2Z5f7p8reY80U6JrMPIK6yuQWk juGQsIFhWma0ELRB7xCQJZghEc6MyDR0PfESsljDZebYL7ZHlE9xWcZ2+qw3YFca wtRLa2Mud0Rx7pXMj07JGiyJ5bM5t1KJP4Wz04ZXHUDOa0NYsoFl8hJwXV/AIY0D 2+dcwa/XN0pWtgztoHL52XzliKpVPqHkgZNN7UAO6ym7pr1JRATW572YsnkLFwgg 4GJ6Nyoh3ZUghS918aZVXHQNfyvF5yAMOn47b5Zbk82ZT6ZDB2KLFJE4/F0OeryZ ncbW6HA2j0GBQPICl9+NW+Ud4KCzuwIDAQABo1AwTjAdBgNVHQ4EFgQU2Cr6Z6wH hBBYnid52DEESkDX4J0wHwYDVR0jBBgwFoAU2Cr6Z6wHhBBYnid52DEESkDX4J0w DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAB8nNUdDZ0pNX8ZGzQbgj 2wCjaX0Za0BNPvVoqpM3oR5BCXodS4HUgx2atpTjsSQlMJzR565OmoykboF5g+K3 hRW6cy4n6LdhY+WvyiyOlbLl+Qj8ceCaBbNrLrg1KbsTI3F8fL1gUzOOr+NNkOJz MDYxmuy/5kMVUp2uIx7aTigCouKgMyciA0a/FJcy1aLnW06yUj4NK0yBHXwpRMjF xcOPOXOTlDZkt88KRTveX9zUiCI9o6/lpZEjdHqT8uhXy2v+TY/akM/cuge/PMBz pspEEzvnu1mW6XEEPgRc8iFZCdtGli6Yfaixxb9oFb/T/vQ4HXh/cb5SddTBPCDS 5Q== -----END CERTIFICATE----- ` // This signing cert is not signed by the root cert. signingCert := ` -----BEGIN CERTIFICATE----- MIIC5TCCAc2gAwIBAgIQbnMGpidD8PvetlXnYSkUHjANBgkqhkiG9w0BAQsFADAT MREwDwYDVQQKEwhKdWp1IG9yZzAeFw0xNzAzMTgwMDE5MDZaFw0yNzAzMDYwMDE5 MDZaMBMxETAPBgNVBAoTCEp1anUgb3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEAoEf2+WIjOLOpVBdV6HpgdEgNklJWGNW5kpinW75F2U14/hznSqY+ JbtEPz7MXeWIagpC3gzSNM7Khtdm/jQjdnZuRhRzbBXILCrdRykewUhXsKdtpNpw bUkCgy7V861zOtwFo3Wm7J7UZIrNqYK8fJrE2YZve9rMyKj1zOVPv6Lm8ioomv2r DANX0F72+qpEAqxrD5YCexdhv+/WeO3YoEECgqRhCLbG71OzREfN2lrgl7vGpqTA bUDJK2RxL4yeARU9WcHT2mXplK5w0w63IdgM8kQdodEPHTlP//lafUDq87PjrcTY eUehLBvtclbEo9bmmnN4JOGNMywVXCw2lQIDAQABozUwMzAOBgNVHQ8BAf8EBAMC BaAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIwADANBgkqhkiG9w0B AQsFAAOCAQEABn9FAdcE+N7upOIU2yWalEe0YQgyTELF9MTstJAeJP/xSnCqF6TG /TfR0IuY/RJyXDLq2rHhrUEsRCCamlQyNkE8RSiHQD/kBf/xxSKobXQyMedXBKSC MHF2h+S/2HmZaOtgG4RnXplCpHegFOhcLORBLbyQJ72DPLvQcCo2A9uyboqKbZhs 0Gh5kSgZrvphvxIerbV5T/VWLO0llhFmU55BIalVpHD7YfMCOkjVL+Y/0fYKL5ij 68/BQAVGtO+1W1AW52eSMoH1gbvYemf+RsxdE/yKCmcTcZer8HswkQzPH03XcMwu V611eTJ/uJO6FTt9/5IN8G1qBj2bdNj/uA== -----END CERTIFICATE----- ` signingKey := ` -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAoEf2+WIjOLOpVBdV6HpgdEgNklJWGNW5kpinW75F2U14/hzn SqY+JbtEPz7MXeWIagpC3gzSNM7Khtdm/jQjdnZuRhRzbBXILCrdRykewUhXsKdt pNpwbUkCgy7V861zOtwFo3Wm7J7UZIrNqYK8fJrE2YZve9rMyKj1zOVPv6Lm8ioo mv2rDANX0F72+qpEAqxrD5YCexdhv+/WeO3YoEECgqRhCLbG71OzREfN2lrgl7vG pqTAbUDJK2RxL4yeARU9WcHT2mXplK5w0w63IdgM8kQdodEPHTlP//lafUDq87Pj rcTYeUehLBvtclbEo9bmmnN4JOGNMywVXCw2lQIDAQABAoIBAFzg9uwSg2iDK9dP 4ndiGuynKD4nOj8P8oZRsYGHZACFVVyjsR/f79l7iBPCNzkeHoucQJ1d/p2dS10S C1u5KOenv0Ua6ruyb5mwiSOIX4sPeckjbHUAI/AgQ7Vy+YZId6KfByFutvkdHOTa Tk0xNjpakUGgFpBF/S82QaGnLCxWtdSvuIZTzhC9bQGL+7TjgZknTqZUhYHLbgH3 XUBLV/Zavce77DJ02YtcZL9UphlWbuZuOF1RESn3Rk7MM3rzLTpjrDzp+EWM9T0H 4B1Zj4PIlVGdjEwUzHfK39KQYOGqhZE6O6Z8mm9H1V3+EaoCjFV6Nt3HwAXvJttc /K/HykECgYEAwg+zCnsPlfI0FuT5W7Fi4bLSRV1IxW/BueR3ct2KUVqieP9DzmZB NEI3ibn+/1MoUjyjAMROq8YBQ/oSpjvez/SqFbJ3xH1zQtAwhcO+3wU1GwftAah5 ZAtSJYRd6AQr1kaj+P5ZEqdxI9MJEPzsOR0eRKiPLVLF+OoDjpb0hkUCgYEA03Ap mjYXiVSzo0NVEcP7f4k+t2Wwoms7O4xZfLuSmvNjhrZmukuu3TIYaCbW8x4wyBe/ Vfe8W4HFuu5IyrHXt/7BYWtSFlKsUyc5sveSktAXuVnZePlowm/NPjJ0EE38I0WV aHWRlUW4H8j9ghwLKlea77+nfY/Q+pba8Ccc3BECgYEAqJD4hY8Vn7sOUiC9FU/F Q6WQDp6UGqQT1ARHWahkgHxJCu84l+2sj9dA5MqCXIiASsbPFFhwuba53LE5R9pT lbHBmC046Z3K4+txao/4mUKtuXguADW2lBddWKdc5q/Q4ETmI9/TwWde2K50fqQk EQxhAWSlUcpHmwqy4kXvyz0CgYBtRQDrBlthiJmRnUGAfeUigv4bb306Yupomt7A XHumgnQD8Y3jZyuGetYsNS5O1GJndgZW2kHIlKdoNK7/uar/FrQ/sWPpz23pR1NF Tza7krk/+9Qs9dAS9A6AvzhGGNdeLx7IrkG/gBloq8l/jRikGEQk9MoNVN6uMnoR NFVw0QKBgH2RW41bzJOJcWnArZR/qp6RT23SQeujOMcRGfH25jpoXU8fKup1Npt8 MnMxUAuP09HIovhn841Y7p+hlh4gSpsvYjLfgX0jyzJPhOmtBu0vEY7fLN6kQLiW RRoQIlr5T8PG4vXwsn2/hohILCJJyHAee/4gIq42jLu6hQsQxcoy -----END RSA PRIVATE KEY----- ` opts := &IstioCAOptions{ SigningCertBytes: []byte(signingCert), SigningKeyBytes: []byte(signingKey), RootCertBytes: []byte(rootCert), } ca, err := NewIstioCA(opts) if ca != nil || err == nil { t.Errorf("Expecting an error but an Istio CA is wrongly instantiated") } errMsg := "invalid parameters: cannot verify the signing cert with the provided root chain and cert pool" if err.Error() != errMsg { t.Errorf("Unexpected error message: expecting '%s' but the actual is '%s'", errMsg, err.Error()) } } func TestSignCSR(t *testing.T) { host := "spiffe://example.com/ns/foo/sa/bar" opts := CertOptions{ Host: host, Org: "istio.io", RSAKeySize: 512, } csrPEM, keyPEM, err := GenCSR(opts) if err != nil { t.Error(err) } ca, err := createCA() if err != nil { t.Error(err) } certPEM, err := ca.Sign(csrPEM) if err != nil { t.Error(err) } fields := &testutil.VerifyFields{ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, } if err = testutil.VerifyCertificate(keyPEM, certPEM, ca.GetRootCertificate(), host, fields); err != nil { t.Error(err) } cert, err := pki.ParsePemEncodedCertificate(certPEM) if err != nil { t.Error(err) } san := pki.ExtractSANExtension(cert.Extensions) if san == nil { t.Errorf("No SAN extension is found in the certificate") } expected := buildSubjectAltNameExtension(host) if !reflect.DeepEqual(expected, san) { t.Errorf("Unexpected extensions: wanted %v but got %v", expected, san) } } func createCA() (CertificateAuthority, error) { start := time.Now().Add(-5 * time.Minute) end := start.Add(24 * time.Hour) // Generate root CA key and cert. rootCAOpts := CertOptions{ IsCA: true, IsSelfSigned: true, NotAfter: end, NotBefore: start, Org: "Root CA", RSAKeySize: 1024, } rootCertBytes, rootKeyBytes := GenCert(rootCAOpts) rootCert, err := pki.ParsePemEncodedCertificate(rootCertBytes) if err != nil { return nil, err } rootKey, err := pki.ParsePemEncodedKey(rootKeyBytes) if err != nil { return nil, err } intermediateCAOpts := CertOptions{ IsCA: true, IsSelfSigned: false, NotAfter: end, NotBefore: start, Org: "Intermediate CA", RSAKeySize: 1024, SignerCert: rootCert, SignerPriv: rootKey, } intermediateCert, intermediateKey := GenCert(intermediateCAOpts) caOpts := &IstioCAOptions{ CertChainBytes: intermediateCert, CertTTL: time.Hour, SigningCertBytes: intermediateCert, SigningKeyBytes: intermediateKey, RootCertBytes: rootCertBytes, } return NewIstioCA(caOpts) } // TODO(wattli): move the two functions below as a util function to share with secret_test.go func createSecret(namespace, signingCert, signingKey, rootCert string) *v1.Secret { return &v1.Secret{ Data: map[string][]byte{ cACertID: []byte(signingCert), cAPrivateKeyID: []byte(signingKey), }, ObjectMeta: metav1.ObjectMeta{ Name: cASecret, Namespace: namespace, }, Type: istioCASecretType, } }
security/pkg/pki/ca/ca_test.go
1
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.998528242111206, 0.04820498079061508, 0.00016115531616378576, 0.0006577994208782911, 0.20988141000270844 ]
{ "id": 6, "code_window": [ "\t\tIsSelfSigned: false,\n", "\t\tNotAfter: end,\n", "\t\tNotBefore: start,\n", "\t\tOrg: \"Intermediate CA\",\n", "\t\tRSAKeySize: 1024,\n", "\t\tSignerCert: rootCert,\n", "\t\tSignerPriv: rootKey,\n", "\t}\n", "\tintermediateCert, intermediateKey := GenCert(intermediateCAOpts)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 394 }
# This is used for internal Eureka testing. Mirrors k8s endpoint instances to an Eureka server. FROM scratch ADD eurekamirror /usr/local/bin/eurekamirror ENTRYPOINT ["/usr/local/bin/eurekamirror"]
pilot/docker/Dockerfile.eurekamirror
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00017090587061829865, 0.00017090587061829865, 0.00017090587061829865, 0.00017090587061829865, 0 ]
{ "id": 6, "code_window": [ "\t\tIsSelfSigned: false,\n", "\t\tNotAfter: end,\n", "\t\tNotBefore: start,\n", "\t\tOrg: \"Intermediate CA\",\n", "\t\tRSAKeySize: 1024,\n", "\t\tSignerCert: rootCert,\n", "\t\tSignerPriv: rootKey,\n", "\t}\n", "\tintermediateCert, intermediateKey := GenCert(intermediateCAOpts)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 394 }
## Copyright 2016 Istio Authors ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. SHELL := /bin/bash build: @bazel build //...:all clean: @bazel clean test: @bazel test //... lint: build @bin/linters.sh fmt: @bin/fmt.sh coverage: @bin/codecov.sh racetest: @bazel test --features=race //... gazelle: @bin/gazelle .PHONY: build clean test lint fmt coverage racetest gazelle
mixer/Makefile
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.0005624329205602407, 0.00025047644157893956, 0.00016133843746501952, 0.00017614098032936454, 0.000156085763592273 ]
{ "id": 6, "code_window": [ "\t\tIsSelfSigned: false,\n", "\t\tNotAfter: end,\n", "\t\tNotBefore: start,\n", "\t\tOrg: \"Intermediate CA\",\n", "\t\tRSAKeySize: 1024,\n", "\t\tSignerCert: rootCert,\n", "\t\tSignerPriv: rootKey,\n", "\t}\n", "\tintermediateCert, intermediateKey := GenCert(intermediateCAOpts)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tRSAKeySize: 2048,\n" ], "file_path": "security/pkg/pki/ca/ca_test.go", "type": "replace", "edit_start_line_idx": 394 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package test supplies a fake Mixer server for use in testing. It should NOT // be used outside of testing contexts. package test // import "istio.io/istio/mixer/test" import ( "errors" "fmt" "net" "time" rpc "github.com/googleapis/googleapis/google/rpc" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/codes" mixerpb "istio.io/api/mixer/v1" "istio.io/istio/mixer/pkg/attribute" "istio.io/istio/mixer/pkg/status" ) // DefaultAmount is the default quota amount to use in testing (1). var DefaultAmount = int64(1) // DefaultValidUseCount is the default number of valid uses to return for // quota allocs for testing (1). var DefaultValidUseCount = int32(10000) // DefaultValidDuration is the default duration to return for // quota allocs in testing (1s). var DefaultValidDuration = 5 * time.Second // AttributesServer implements the Mixer API to send mutable attributes bags to // a channel upon API requests. This can be used for tests that want to exercise // the Mixer API and validate server handling of supplied attributes. type AttributesServer struct { // GlobalDict controls the known global dictionary for attribute processing. GlobalDict map[string]int32 // GenerateGRPCError instructs the server whether or not to fail-fast with // an error that will manifest as a GRPC error. GenerateGRPCError bool // Handler is what the server will call to simulate passing attribute bags // and method args within the Mixer server. It allows tests to gain access // to the attribute handling pipeline within Mixer and to set the response // details. Handler AttributesHandler } // NewAttributesServer creates an AttributesServer. All channels are set to // default length. func NewAttributesServer(handler AttributesHandler) *AttributesServer { list := attribute.GlobalList() globalDict := make(map[string]int32, len(list)) for i := 0; i < len(list); i++ { globalDict[list[i]] = int32(i) } return &AttributesServer{ globalDict, false, handler, } } // Check sends a copy of the protocol buffers attributes wrapper for the preconditions // check as well as for each quotas check to the CheckAttributes channel. It also // builds a CheckResponse based on server fields. All channel sends timeout to // prevent problematic tests from blocking indefinitely. func (a *AttributesServer) Check(ctx context.Context, req *mixerpb.CheckRequest) (*mixerpb.CheckResponse, error) { if a.GenerateGRPCError { return nil, errors.New("error handling check call") } requestBag := attribute.NewProtoBag(&req.Attributes, a.GlobalDict, attribute.GlobalList()) defer requestBag.Done() responseBag := attribute.GetMutableBag(requestBag) result, out := a.Handler.Check(requestBag, responseBag) resp := &mixerpb.CheckResponse{ Precondition: mixerpb.CheckResponse_PreconditionResult{ Status: out, ValidUseCount: result.ValidUseCount, ValidDuration: result.ValidDuration, }, } if result.Referenced != nil { resp.Precondition.ReferencedAttributes = *result.Referenced } else { resp.Precondition.ReferencedAttributes = requestBag.GetReferencedAttributes(a.GlobalDict, int(req.GlobalWordCount)) } responseBag.ToProto(&resp.Precondition.Attributes, a.GlobalDict, int(req.GlobalWordCount)) requestBag.ClearReferencedAttributes() if len(req.Quotas) > 0 { resp.Quotas = make(map[string]mixerpb.CheckResponse_QuotaResult, len(req.Quotas)) for name, param := range req.Quotas { args := QuotaArgs{ Quota: name, Amount: param.Amount, DeduplicationID: req.DeduplicationId + name, BestEffort: param.BestEffort, } result, out := a.Handler.Quota(requestBag, args) if status.IsOK(resp.Precondition.Status) && !status.IsOK(out) { resp.Precondition.Status = out } qr := mixerpb.CheckResponse_QuotaResult{ GrantedAmount: result.Amount, ValidDuration: result.Expiration, ReferencedAttributes: requestBag.GetReferencedAttributes(a.GlobalDict, int(req.GlobalWordCount)), } if result.Referenced != nil { qr.ReferencedAttributes = *result.Referenced } else { qr.ReferencedAttributes = requestBag.GetReferencedAttributes(a.GlobalDict, int(req.GlobalWordCount)) } resp.Quotas[name] = qr requestBag.ClearReferencedAttributes() } } return resp, nil } // Report iterates through the supplied attributes sets, applying the deltas // appropriately, and sending the generated bags to the channel. func (a *AttributesServer) Report(ctx context.Context, req *mixerpb.ReportRequest) (*mixerpb.ReportResponse, error) { if a.GenerateGRPCError { return nil, errors.New("error handling report call") } if len(req.Attributes) == 0 { // early out return &mixerpb.ReportResponse{}, nil } // apply the request-level word list to each attribute message if needed for i := 0; i < len(req.Attributes); i++ { if len(req.Attributes[i].Words) == 0 { req.Attributes[i].Words = req.DefaultWords } } protoBag := attribute.NewProtoBag(&req.Attributes[0], a.GlobalDict, attribute.GlobalList()) requestBag := attribute.GetMutableBag(protoBag) defer requestBag.Done() defer protoBag.Done() out := a.Handler.Report(requestBag) for i := 1; i < len(req.Attributes); i++ { // the first attribute block is handled by the protoBag as a foundation, // deltas are applied to the child bag (i.e. requestBag) if err := requestBag.UpdateBagFromProto(&req.Attributes[i], attribute.GlobalList()); err != nil { return &mixerpb.ReportResponse{}, fmt.Errorf("could not apply attribute delta: %v", err) } out = a.Handler.Report(requestBag) } if !status.IsOK(out) { return nil, makeGRPCError(out) } return &mixerpb.ReportResponse{}, nil } // NewMixerServer creates a new grpc.Server with the supplied implementation // of the Mixer API. func NewMixerServer(impl mixerpb.MixerServer) *grpc.Server { gs := grpc.NewServer() mixerpb.RegisterMixerServer(gs, impl) return gs } // ListenerAndPort starts a listener on an available port and returns both the // listener and the port on which it is listening. func ListenerAndPort() (net.Listener, int, error) { lis, err := net.Listen("tcp", ":0") // nolint: gas if err != nil { return nil, 0, fmt.Errorf("could not find open port for server: %v", err) } return lis, lis.Addr().(*net.TCPAddr).Port, nil } func makeGRPCError(status rpc.Status) error { return grpc.Errorf(codes.Code(status.Code), status.Message) }
mixer/test/server.go
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00143245211802423, 0.0002457618247717619, 0.00016516525647602975, 0.00017325776570942253, 0.0002706692321226001 ]
{ "id": 7, "code_window": [ "\n", "\tserviceAccountNameAnnotationKey = \"istio.io/service-account.name\"\n", "\n", "\t// The size of a private key for a leaf certificate.\n", "\tkeySize = 1024\n", ")\n", "\n", "// SecretController manages the service accounts' secrets that contains Istio keys and certificates.\n", "type SecretController struct {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = 2048\n" ], "file_path": "security/pkg/pki/ca/controller/secret.go", "type": "replace", "edit_start_line_idx": 55 }
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "os" "github.com/golang/glog" "github.com/spf13/cobra" "istio.io/istio/security/cmd/node_agent/na" "istio.io/istio/security/pkg/cmd" ) var ( naConfig na.Config rootCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { runNodeAgent() }, } ) func init() { na.InitializeConfig(&naConfig) flags := rootCmd.Flags() flags.StringVar(&naConfig.ServiceIdentityOrg, "org", "", "Organization for the cert") flags.IntVar(&naConfig.RSAKeySize, "key-size", 1024, "Size of generated private key") flags.StringVar(&naConfig.IstioCAAddress, "ca-address", "istio-ca:8060", "Istio CA address") flags.StringVar(&naConfig.Env, "env", "onprem", "Node Environment : onprem | gcp | aws") flags.StringVar(&naConfig.PlatformConfig.CertChainFile, "cert-chain", "/etc/certs/cert-chain.pem", "Node Agent identity cert file") flags.StringVar(&naConfig.PlatformConfig.KeyFile, "key", "/etc/certs/key.pem", "Node identity private key file") flags.StringVar(&naConfig.PlatformConfig.RootCACertFile, "root-cert", "/etc/certs/root-cert.pem", "Root Certificate file") cmd.InitializeFlags(rootCmd) } func main() { if err := rootCmd.Execute(); err != nil { glog.Error(err) os.Exit(-1) } } func runNodeAgent() { nodeAgent, err := na.NewNodeAgent(&naConfig) if err != nil { glog.Error(err) os.Exit(-1) } glog.Infof("Starting Node Agent") if err := nodeAgent.Start(); err != nil { glog.Errorf("Node agent terminated with error: %v.", err) os.Exit(-1) } }
security/cmd/node_agent/main.go
1
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00018025163444690406, 0.00017232906247954816, 0.0001671650679782033, 0.00017162889707833529, 0.00000439525865658652 ]
{ "id": 7, "code_window": [ "\n", "\tserviceAccountNameAnnotationKey = \"istio.io/service-account.name\"\n", "\n", "\t// The size of a private key for a leaf certificate.\n", "\tkeySize = 1024\n", ")\n", "\n", "// SecretController manages the service accounts' secrets that contains Istio keys and certificates.\n", "type SecretController struct {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = 2048\n" ], "file_path": "security/pkg/pki/ca/controller/secret.go", "type": "replace", "edit_start_line_idx": 55 }
#!/usr/bin/python # Script to process Godeps.json into WORKSPACE # TODO: you need to manually remove duplicate entries if importpath is a directory in a repo import json import sys obj = json.load(sys.stdin) deps = obj['Deps'] for dep in deps: path = dep['ImportPath'] commit = dep['Rev'] # name: gopkg.in/inf.v0 -> in_gopkg_inf_v0 # name: github.com/googleapis/gax-go -> com_github_googleapis_gax_go slash = path.index('/') dns = path[:slash].split('.') dns.reverse() name = '_'.join(dns) + "_" + path[slash+1:].replace('.', '_').replace('-', '_').replace('/', '_') print("new_go_repository(") print(" name = \"" + name + "\",") print(" commit = \"" + commit + "\",") print(" importpath = \"" + path + "\",") print(")") print("")
pilot/bin/godeps-workspace.py
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.0001789016678230837, 0.00017561936692800373, 0.00017152377404272556, 0.00017643262981437147, 0.0000030664189125673147 ]
{ "id": 7, "code_window": [ "\n", "\tserviceAccountNameAnnotationKey = \"istio.io/service-account.name\"\n", "\n", "\t// The size of a private key for a leaf certificate.\n", "\tkeySize = 1024\n", ")\n", "\n", "// SecretController manages the service accounts' secrets that contains Istio keys and certificates.\n", "type SecretController struct {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = 2048\n" ], "file_path": "security/pkg/pki/ca/controller/secret.go", "type": "replace", "edit_start_line_idx": 55 }
syntax = "proto3"; package istio.mixer.v1.config.template; import "google/protobuf/descriptor.proto"; enum TemplateVariety { TEMPLATE_VARIETY_CHECK = 0; TEMPLATE_VARIETY_REPORT = 1; TEMPLATE_VARIETY_QUOTA = 2; } extend google.protobuf.FileOptions { TemplateVariety template_variety = 72295727; } message Expr { // This will be deleted in the next PR once the initial codegen implementation is fixed to not use it. Curren plan // is to treate field of type ValueType as expressions. }
mixer/pkg/adapter/template/TemplateExtensions.proto
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00017066305736079812, 0.0001700192951830104, 0.00016937553300522268, 0.0001700192951830104, 6.437621777877212e-7 ]
{ "id": 7, "code_window": [ "\n", "\tserviceAccountNameAnnotationKey = \"istio.io/service-account.name\"\n", "\n", "\t// The size of a private key for a leaf certificate.\n", "\tkeySize = 1024\n", ")\n", "\n", "// SecretController manages the service accounts' secrets that contains Istio keys and certificates.\n", "type SecretController struct {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tkeySize = 2048\n" ], "file_path": "security/pkg/pki/ca/controller/secret.go", "type": "replace", "edit_start_line_idx": 55 }
syntax = "proto3"; package foo.bar.mylistChecker; import "mixer/v1/config/descriptor/value_type.proto"; import "mixer/v1/template/extensions.proto"; import "google/protobuf/duration.proto"; import "google/protobuf/timestamp.proto"; option (istio.mixer.v1.template.template_variety) = TEMPLATE_VARIETY_CHECK; message Template { string check_expression = 1; map<string, istio.mixer.v1.config.descriptor.ValueType> dimensions = 2; int64 int64Primitive = 3; bool boolPrimitive = 4; double doublePrimitive = 5; string stringPrimitive = 6; istio.mixer.v1.config.descriptor.ValueType anotherValueType = 7; map<string, int64> dimensionsFixedInt64ValueDType = 8; google.protobuf.Timestamp timeStamp = 9; google.protobuf.Duration duration = 10; }
mixer/tools/codegen/pkg/interfacegen/testdata/CheckTmpl.proto
0
https://github.com/istio/istio/commit/61a7d039a991fc0125215184cc78cbd1fa6d15a7
[ 0.00017306128575000912, 0.00016779691213741899, 0.00016396219143643975, 0.00016708210750948638, 0.0000033410685773560544 ]
{ "id": 0, "code_window": [ "\tif err != nil {\n", "\t\tlog.Exitf(\"ReadFile %s: %v\", path, err);\n", "\t}\n", "\tt, err1 := template.Parse(string(data), fmap);\n", "\tif err1 != nil {\n", "\t\tlog.Exitf(\"%s: %v\", name, err);\n", "\t}\n", "\treturn t;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tt, err := template.Parse(string(data), fmap);\n", "\tif err != nil {\n" ], "file_path": "src/cmd/godoc/godoc.go", "type": "replace", "edit_start_line_idx": 448 }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Data-driven templates for generating textual output such as HTML. See http://code.google.com/p/json-template/wiki/Reference for full documentation of the template language. A summary: Templates are executed by applying them to a data structure. Annotations in the template refer to elements of the data structure (typically a field of a struct) to control execution and derive values to be displayed. The template walks the structure as it executes and the "cursor" @ represents the value at the current location in the structure. Data items may be values or pointers; the interface hides the indirection. Major constructs ({} are metacharacters; [] marks optional elements): {# comment } A one-line comment. {.section field} XXX [ {.or} YYY ] {.end} Set @ to the value of the field. It may be an explicit @ to stay at the same point in the data. If the field is nil or empty, execute YYY; otherwise execute XXX. {.repeated section field} XXX [ {.alternates with} ZZZ ] [ {.or} YYY ] {.end} Like .section, but field must be an array or slice. XXX is executed for each element. If the array is nil or empty, YYY is executed instead. If the {.alternates with} marker is present, ZZZ is executed between iterations of XXX. {field} {field|formatter} Insert the value of the field into the output. Field is first looked for in the cursor, as in .section and .repeated. If it is not found, the search continues in outer sections until the top level is reached. If a formatter is specified, it must be named in the formatter map passed to the template set up routines or in the default set ("html","str","") and is used to process the data for output. The formatter function has signature func(wr io.Write, data interface{}, formatter string) where wr is the destination for output, data is the field value, and formatter is its name at the invocation site. */ package template import ( "container/vector"; "fmt"; "io"; "os"; "reflect"; "runtime"; "strings"; ) // Errors returned during parsing and execution. Users may extract the information and reformat // if they desire. type Error struct { Line int; Msg string; } func (e *Error) String() string { return fmt.Sprintf("line %d: %s", e.Line, e.Msg) } // Most of the literals are aces. var lbrace = []byte{ '{' } var rbrace = []byte{ '}' } var space = []byte{ ' ' } var tab = []byte{ '\t' } // The various types of "tokens", which are plain text or (usually) brace-delimited descriptors const ( tokAlternates = iota; tokComment; tokEnd; tokLiteral; tokOr; tokRepeated; tokSection; tokText; tokVariable; ) // FormatterMap is the type describing the mapping from formatter // names to the functions that implement them. type FormatterMap map[string] func(io.Writer, interface{}, string) // Built-in formatters. var builtins = FormatterMap { "html" : HtmlFormatter, "str" : StringFormatter, "" : StringFormatter, } // The parsed state of a template is a vector of xxxElement structs. // Sections have line numbers so errors can be reported better during execution. // Plain text. type textElement struct { text []byte; } // A literal such as .meta-left or .meta-right type literalElement struct { text []byte; } // A variable to be evaluated type variableElement struct { linenum int; name string; formatter string; // TODO(r): implement pipelines } // A .section block, possibly with a .or type sectionElement struct { linenum int; // of .section itself field string; // cursor field for this block start int; // first element or int; // first element of .or block end int; // one beyond last element } // A .repeated block, possibly with a .or and a .alternates type repeatedElement struct { sectionElement; // It has the same structure... altstart int; // ... except for alternates altend int; } // Template is the type that represents a template definition. // It is unchanged after parsing. type Template struct { fmap FormatterMap; // formatters for variables // Used during parsing: ldelim, rdelim []byte; // delimiters; default {} buf []byte; // input text to process p int; // position in buf linenum int; // position in input error os.Error; // error during parsing (only) // Parsed results: elems *vector.Vector; } // Internal state for executing a Template. As we evaluate the struct, // the data item descends into the fields associated with sections, etc. // Parent is used to walk upwards to find variables higher in the tree. type state struct { parent *state; // parent in hierarchy data reflect.Value; // the driver data for this section etc. wr io.Writer; // where to send output errors chan os.Error; // for reporting errors during execute } func (parent *state) clone(data reflect.Value) *state { return &state{parent, data, parent.wr, parent.errors} } // New creates a new template with the specified formatter map (which // may be nil) to define auxiliary functions for formatting variables. func New(fmap FormatterMap) *Template { t := new(Template); t.fmap = fmap; t.ldelim = lbrace; t.rdelim = rbrace; t.elems = vector.New(0); return t; } // Report error and stop executing. The line number must be provided explicitly. func (t *Template) execError(st *state, line int, err string, args ...) { st.errors <- &Error{line, fmt.Sprintf(err, args)}; runtime.Goexit(); } // Report error, save in Template to terminate parsing. // The line number comes from the template state. func (t *Template) parseError(err string, args ...) { t.error = &Error{t.linenum, fmt.Sprintf(err, args)}; } // -- Lexical analysis // Is c a white space character? func white(c uint8) bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n' } // Safely, does s[n:n+len(t)] == t? func equal(s []byte, n int, t []byte) bool { b := s[n:len(s)]; if len(t) > len(b) { // not enough space left for a match. return false } for i , c := range t { if c != b[i] { return false } } return true } // nextItem returns the next item from the input buffer. If the returned // item is empty, we are at EOF. The item will be either a // delimited string or a non-empty string between delimited // strings. Tokens stop at (but include, if plain text) a newline. // Action tokens on a line by themselves drop the white space on // either side, up to and including the newline. func (t *Template) nextItem() []byte { sawLeft := false; // are we waiting for an opening delimiter? special := false; // is this a {.foo} directive, which means trim white space? // Delete surrounding white space if this {.foo} is the only thing on the line. trim_white := t.p == 0 || t.buf[t.p-1] == '\n'; only_white := true; // we have seen only white space so far var i int; start := t.p; Loop: for i = t.p; i < len(t.buf); i++ { switch { case t.buf[i] == '\n': t.linenum++; i++; break Loop; case white(t.buf[i]): // white space, do nothing case !sawLeft && equal(t.buf, i, t.ldelim): // sawLeft checked because delims may be equal // anything interesting already on the line? if !only_white { break Loop; } // is it a directive or comment? j := i + len(t.ldelim); // position after delimiter if j+1 < len(t.buf) && (t.buf[j] == '.' || t.buf[j] == '#') { special = true; if trim_white && only_white { start = i; } } else if i > t.p { // have some text accumulated so stop before delimiter break Loop; } sawLeft = true; i = j - 1; case equal(t.buf, i, t.rdelim): if !sawLeft { t.parseError("unmatched closing delimiter"); return nil; } sawLeft = false; i += len(t.rdelim); break Loop; default: only_white = false; } } if sawLeft { t.parseError("unmatched opening delimiter"); return nil; } item := t.buf[start:i]; if special && trim_white { // consume trailing white space for ; i < len(t.buf) && white(t.buf[i]); i++ { if t.buf[i] == '\n' { i++; break // stop after newline } } } t.p = i; return item } // Turn a byte array into a white-space-split array of strings. func words(buf []byte) []string { s := make([]string, 0, 5); p := 0; // position in buf // one word per loop for i := 0; ; i++ { // skip white space for ; p < len(buf) && white(buf[p]); p++ { } // grab word start := p; for ; p < len(buf) && !white(buf[p]); p++ { } if start == p { // no text left break } if i == cap(s) { ns := make([]string, 2*cap(s)); for j := range s { ns[j] = s[j] } s = ns; } s = s[0:i+1]; s[i] = string(buf[start:p]) } return s } // Analyze an item and return its token type and, if it's an action item, an array of // its constituent words. func (t *Template) analyze(item []byte) (tok int, w []string) { // item is known to be non-empty if !equal(item, 0, t.ldelim) { // doesn't start with left delimiter tok = tokText; return; } if !equal(item, len(item)-len(t.rdelim), t.rdelim) { // doesn't end with right delimiter t.parseError("internal error: unmatched opening delimiter"); // lexing should prevent this return; } if len(item) <= len(t.ldelim)+len(t.rdelim) { // no contents t.parseError("empty directive"); return; } // Comment if item[len(t.ldelim)] == '#' { tok = tokComment; return } // Split into words w = words(item[len(t.ldelim): len(item)-len(t.rdelim)]); // drop final delimiter if len(w) == 0 { t.parseError("empty directive"); return; } if len(w) == 1 && w[0][0] != '.' { tok = tokVariable; return; } switch w[0] { case ".meta-left", ".meta-right", ".space", ".tab": tok = tokLiteral; return; case ".or": tok = tokOr; return; case ".end": tok = tokEnd; return; case ".section": if len(w) != 2 { t.parseError("incorrect fields for .section: %s", item); return; } tok = tokSection; return; case ".repeated": if len(w) != 3 || w[1] != "section" { t.parseError("incorrect fields for .repeated: %s", item); return; } tok = tokRepeated; return; case ".alternates": if len(w) != 2 || w[1] != "with" { t.parseError("incorrect fields for .alternates: %s", item); return; } tok = tokAlternates; return; } t.parseError("bad directive: %s", item); return } // -- Parsing // Allocate a new variable-evaluation element. func (t *Template) newVariable(name_formatter string) (v *variableElement) { name := name_formatter; formatter := ""; bar := strings.Index(name_formatter, "|"); if bar >= 0 { name = name_formatter[0:bar]; formatter = name_formatter[bar+1:len(name_formatter)]; } // Probably ok, so let's build it. v = &variableElement{t.linenum, name, formatter}; // We could remember the function address here and avoid the lookup later, // but it's more dynamic to let the user change the map contents underfoot. // We do require the name to be present, though. // Is it in user-supplied map? if t.fmap != nil { if _, ok := t.fmap[formatter]; ok { return } } // Is it in builtin map? if _, ok := builtins[formatter]; ok { return } t.parseError("unknown formatter: %s", formatter); return } // Grab the next item. If it's simple, just append it to the template. // Otherwise return its details. func (t *Template) parseSimple(item []byte) (done bool, tok int, w []string) { tok, w = t.analyze(item); if t.error != nil { return } done = true; // assume for simplicity switch tok { case tokComment: return; case tokText: t.elems.Push(&textElement{item}); return; case tokLiteral: switch w[0] { case ".meta-left": t.elems.Push(&literalElement{t.ldelim}); case ".meta-right": t.elems.Push(&literalElement{t.rdelim}); case ".space": t.elems.Push(&literalElement{space}); case ".tab": t.elems.Push(&literalElement{tab}); default: t.parseError("internal error: unknown literal: %s", w[0]); return; } return; case tokVariable: t.elems.Push(t.newVariable(w[0])); return; } return false, tok, w } // parseRepeated and parseSection are mutually recursive func (t *Template) parseRepeated(words []string) *repeatedElement { r := new(repeatedElement); t.elems.Push(r); r.linenum = t.linenum; r.field = words[2]; // Scan section, collecting true and false (.or) blocks. r.start = t.elems.Len(); r.or = -1; r.altstart = -1; r.altend = -1; Loop: for t.error == nil { item := t.nextItem(); if t.error != nil { break; } if len(item) == 0 { t.parseError("missing .end for .repeated section"); break; } done, tok, w := t.parseSimple(item); if t.error != nil { break; } if done { continue } switch tok { case tokEnd: break Loop; case tokOr: if r.or >= 0 { t.parseError("extra .or in .repeated section"); break Loop; } r.altend = t.elems.Len(); r.or = t.elems.Len(); case tokSection: t.parseSection(w); case tokRepeated: t.parseRepeated(w); case tokAlternates: if r.altstart >= 0 { t.parseError("extra .alternates in .repeated section"); break Loop; } if r.or >= 0 { t.parseError(".alternates inside .or block in .repeated section"); break Loop; } r.altstart = t.elems.Len(); default: t.parseError("internal error: unknown repeated section item: %s", item); break Loop; } } if t.error != nil { return nil } if r.altend < 0 { r.altend = t.elems.Len() } r.end = t.elems.Len(); return r; } func (t *Template) parseSection(words []string) *sectionElement { s := new(sectionElement); t.elems.Push(s); s.linenum = t.linenum; s.field = words[1]; // Scan section, collecting true and false (.or) blocks. s.start = t.elems.Len(); s.or = -1; Loop: for t.error == nil { item := t.nextItem(); if t.error != nil { break; } if len(item) == 0 { t.parseError("missing .end for .section"); break; } done, tok, w := t.parseSimple(item); if t.error != nil { break; } if done { continue } switch tok { case tokEnd: break Loop; case tokOr: if s.or >= 0 { t.parseError("extra .or in .section"); break Loop; } s.or = t.elems.Len(); case tokSection: t.parseSection(w); case tokRepeated: t.parseRepeated(w); case tokAlternates: t.parseError(".alternates not in .repeated"); default: t.parseError("internal error: unknown section item: %s", item); } } if t.error != nil { return nil } s.end = t.elems.Len(); return s; } func (t *Template) parse() { for t.error == nil { item := t.nextItem(); if t.error != nil { break } if len(item) == 0 { break } done, tok, w := t.parseSimple(item); if done { continue } switch tok { case tokOr, tokEnd, tokAlternates: t.parseError("unexpected %s", w[0]); case tokSection: t.parseSection(w); case tokRepeated: t.parseRepeated(w); default: t.parseError("internal error: bad directive in parse: %s", item); } } } // -- Execution // If the data for this template is a struct, find the named variable. // Names of the form a.b.c are walked down the data tree. // The special name "@" (the "cursor") denotes the current data. // The value coming in (st.data) might need indirecting to reach // a struct while the return value is not indirected - that is, // it represents the actual named field. func (st *state) findVar(s string) reflect.Value { if s == "@" { return st.data } data := st.data; elems := strings.Split(s, ".", 0); for i := 0; i < len(elems); i++ { // Look up field; data must be a struct. data = reflect.Indirect(data); if data == nil { return nil } typ, ok := data.Type().(*reflect.StructType); if !ok { return nil } field, ok := typ.FieldByName(elems[i]); if !ok { return nil } data = data.(*reflect.StructValue).FieldByIndex(field.Index); } return data } // Is there no data to look at? func empty(v reflect.Value) bool { v = reflect.Indirect(v); if v == nil { return true } switch v := v.(type) { case *reflect.BoolValue: return v.Get() == false; case *reflect.StringValue: return v.Get() == ""; case *reflect.StructValue: return false; case *reflect.ArrayValue: return v.Len() == 0; case *reflect.SliceValue: return v.Len() == 0; } return true; } // Look up a variable, up through the parent if necessary. func (t *Template) varValue(name string, st *state) reflect.Value { field := st.findVar(name); if field == nil { if st.parent == nil { t.execError(st, t.linenum, "name not found: %s", name) } return t.varValue(name, st.parent); } return field; } // Evaluate a variable, looking up through the parent if necessary. // If it has a formatter attached ({var|formatter}) run that too. func (t *Template) writeVariable(v *variableElement, st *state) { formatter := v.formatter; val := t.varValue(v.name, st).Interface(); // is it in user-supplied map? if t.fmap != nil { if fn, ok := t.fmap[formatter]; ok { fn(st.wr, val, formatter); return; } } // is it in builtin map? if fn, ok := builtins[formatter]; ok { fn(st.wr, val, formatter); return; } t.execError(st, v.linenum, "missing formatter %s for variable %s", formatter, v.name) } // Execute element i. Return next index to execute. func (t *Template) executeElement(i int, st *state) int { switch elem := t.elems.At(i).(type) { case *textElement: st.wr.Write(elem.text); return i+1; case *literalElement: st.wr.Write(elem.text); return i+1; case *variableElement: t.writeVariable(elem, st); return i+1; case *sectionElement: t.executeSection(elem, st); return elem.end; case *repeatedElement: t.executeRepeated(elem, st); return elem.end; } e := t.elems.At(i); t.execError(st, 0, "internal error: bad directive in execute: %v %T\n", reflect.NewValue(e).Interface(), e); return 0 } // Execute the template. func (t *Template) execute(start, end int, st *state) { for i := start; i < end; { i = t.executeElement(i, st) } } // Execute a .section func (t *Template) executeSection(s *sectionElement, st *state) { // Find driver data for this section. It must be in the current struct. field := t.varValue(s.field, st); if field == nil { t.execError(st, s.linenum, ".section: cannot find field %s in %s", s.field, reflect.Indirect(st.data).Type()); } st = st.clone(field); start, end := s.start, s.or; if !empty(field) { // Execute the normal block. if end < 0 { end = s.end } } else { // Execute the .or block. If it's missing, do nothing. start, end = s.or, s.end; if start < 0 { return } } for i := start; i < end; { i = t.executeElement(i, st) } } // Return the result of calling the Iter method on v, or nil. func iter(v reflect.Value) *reflect.ChanValue { for j := 0; j < v.Type().NumMethod(); j++ { mth := v.Type().Method(j); fv := v.Method(j); ft := fv.Type().(*reflect.FuncType); // TODO(rsc): NumIn() should return 0 here, because ft is from a curried FuncValue. if mth.Name != "Iter" || ft.NumIn() != 1 || ft.NumOut() != 1 { continue } ct, ok := ft.Out(0).(*reflect.ChanType); if !ok || ct.Dir() & reflect.RecvDir == 0 { continue } return fv.Call(nil)[0].(*reflect.ChanValue) } return nil } // Execute a .repeated section func (t *Template) executeRepeated(r *repeatedElement, st *state) { // Find driver data for this section. It must be in the current struct. field := t.varValue(r.field, st); if field == nil { t.execError(st, r.linenum, ".repeated: cannot find field %s in %s", r.field, reflect.Indirect(st.data).Type()); } start, end := r.start, r.or; if end < 0 { end = r.end } if r.altstart >= 0 { end = r.altstart } first := true; if array, ok := field.(reflect.ArrayOrSliceValue); ok { for j := 0; j < array.Len(); j++ { newst := st.clone(array.Elem(j)); // .alternates between elements if !first && r.altstart >= 0 { for i := r.altstart; i < r.altend; { i = t.executeElement(i, newst) } } first = false; for i := start; i < end; { i = t.executeElement(i, newst) } } } else if ch := iter(field); ch != nil { for { e := ch.Recv(); if ch.Closed() { break } newst := st.clone(e); // .alternates between elements if !first && r.altstart >= 0 { for i := r.altstart; i < r.altend; { i = t.executeElement(i, newst) } } first = false; for i := start; i < end; { i = t.executeElement(i, newst) } } } else { t.execError(st, r.linenum, ".repeated: cannot repeat %s (type %s)", r.field, field.Type()); } if first { // Empty. Execute the .or block, once. If it's missing, do nothing. start, end := r.or, r.end; if start >= 0 { newst := st.clone(field); for i := start; i < end; { i = t.executeElement(i, newst) } } return } } // A valid delimiter must contain no white space and be non-empty. func validDelim(d []byte) bool { if len(d) == 0 { return false } for _, c := range d { if white(c) { return false } } return true; } // -- Public interface // Parse initializes a Template by parsing its definition. The string // s contains the template text. If any errors occur, Parse returns // the error. func (t *Template) Parse(s string) os.Error { if !validDelim(t.ldelim) || !validDelim(t.rdelim) { return &Error{1, fmt.Sprintf("bad delimiter strings %q %q", t.ldelim, t.rdelim)} } t.buf = strings.Bytes(s); t.p = 0; t.linenum = 0; t.parse(); return t.error; } // Execute applies a parsed template to the specified data object, // generating output to wr. func (t *Template) Execute(data interface{}, wr io.Writer) os.Error { // Extract the driver data. val := reflect.NewValue(data); errors := make(chan os.Error); go func() { t.p = 0; t.execute(0, t.elems.Len(), &state{nil, val, wr, errors}); errors <- nil; // clean return; }(); return <-errors; } // SetDelims sets the left and right delimiters for operations in the // template. They are validated during parsing. They could be // validated here but it's better to keep the routine simple. The // delimiters are very rarely invalid and Parse has the necessary // error-handling interface already. func (t *Template) SetDelims(left, right string) { t.ldelim = strings.Bytes(left); t.rdelim = strings.Bytes(right); } // Parse creates a Template with default parameters (such as {} for // metacharacters). The string s contains the template text while // the formatter map fmap, which may be nil, defines auxiliary functions // for formatting variables. The template is returned. If any errors // occur, err will be non-nil. func Parse(s string, fmap FormatterMap) (t *Template, err os.Error) { t = New(fmap); err = t.Parse(s); if err != nil { t = nil } return } // MustParse is like Parse but panics if the template cannot be parsed. func MustParse(s string, fmap FormatterMap) *Template { t , err := Parse(s, fmap); if err != nil { panic("template parse error: ", err); } return t }
src/pkg/template/template.go
1
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.9684282541275024, 0.15646237134933472, 0.00016483344370499253, 0.0017366111278533936, 0.3257547616958618 ]
{ "id": 0, "code_window": [ "\tif err != nil {\n", "\t\tlog.Exitf(\"ReadFile %s: %v\", path, err);\n", "\t}\n", "\tt, err1 := template.Parse(string(data), fmap);\n", "\tif err1 != nil {\n", "\t\tlog.Exitf(\"%s: %v\", name, err);\n", "\t}\n", "\treturn t;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tt, err := template.Parse(string(data), fmap);\n", "\tif err != nil {\n" ], "file_path": "src/cmd/godoc/godoc.go", "type": "replace", "edit_start_line_idx": 448 }
// errchk $G $D/$F.go // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main func main() { // should allow at most 2 sizes a := make([]int, 10, 20, 30, 40); // ERROR "too many" }
test/fixedbugs/bug122.go
0
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.00017298753664363176, 0.00016883815987966955, 0.0001646887685637921, 0.00016883815987966955, 0.000004149384039919823 ]
{ "id": 0, "code_window": [ "\tif err != nil {\n", "\t\tlog.Exitf(\"ReadFile %s: %v\", path, err);\n", "\t}\n", "\tt, err1 := template.Parse(string(data), fmap);\n", "\tif err1 != nil {\n", "\t\tlog.Exitf(\"%s: %v\", name, err);\n", "\t}\n", "\treturn t;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tt, err := template.Parse(string(data), fmap);\n", "\tif err != nil {\n" ], "file_path": "src/cmd/godoc/godoc.go", "type": "replace", "edit_start_line_idx": 448 }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package os import "syscall" // Time returns the current time, in whole seconds and // fractional nanoseconds, plus an Error if any. The current // time is thus 1e9*sec+nsec, in nanoseconds. The zero of // time is the Unix epoch. func Time() (sec int64, nsec int64, err Error) { var tv syscall.Timeval; if errno := syscall.Gettimeofday(&tv); errno != 0 { return 0, 0, NewSyscallError("gettimeofday", errno); } return int64(tv.Sec), int64(tv.Usec)*1000, err; }
src/pkg/os/time.go
0
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.00018047055345959961, 0.00017510901670902967, 0.00016478645557072014, 0.0001800700556486845, 0.000007300987817870919 ]
{ "id": 0, "code_window": [ "\tif err != nil {\n", "\t\tlog.Exitf(\"ReadFile %s: %v\", path, err);\n", "\t}\n", "\tt, err1 := template.Parse(string(data), fmap);\n", "\tif err1 != nil {\n", "\t\tlog.Exitf(\"%s: %v\", name, err);\n", "\t}\n", "\treturn t;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tt, err := template.Parse(string(data), fmap);\n", "\tif err != nil {\n" ], "file_path": "src/cmd/godoc/godoc.go", "type": "replace", "edit_start_line_idx": 448 }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This package implements the PEM data encoding, which originated in Privacy // Enhanced Mail. The most common use of PEM encoding today is in TLS keys and // certificates. See RFC 1421. package pem import ( "bytes"; "encoding/base64"; "strings"; ) // A Block represents a PEM encoded structure. // // The encoded form is: // -----BEGIN Type----- // Headers // base64-encoded Bytes // -----END Type----- // where Headers is a possibly empty sequence of Key: Value lines. type Block struct { Type string; // The type, taken from the preamble (i.e. "RSA PRIVATE KEY"). Headers map[string]string; // Optional headers. Bytes []byte; // The decoded bytes of the contents. Typically a DER encoded ASN.1 structure. } // getLine results the first \r\n or \n delineated line from the given byte // array. The line does not include the \r\n or \n. The remainder of the byte // array (also not including the new line bytes) is also returned and this will // always be smaller than the original argument. func getLine(data []byte) (line, rest []byte) { i := bytes.Index(data, []byte{'\n'}); var j int; if i < 0 { i = len(data); j = i; } else { j = i+1; if i > 0 && data[i-1] == '\r' { i--; } } return data[0:i], data[j:len(data)]; } // removeWhitespace returns a copy of its input with all spaces, tab and // newline characters removed. func removeWhitespace(data []byte) []byte { result := make([]byte, len(data)); n := 0; for _, b := range data { if b == ' ' || b == '\t' || b == '\r' || b == '\n' { continue; } result[n] = b; n++; } return result[0:n]; } var pemStart = strings.Bytes("\n-----BEGIN ") var pemEnd = strings.Bytes("\n-----END ") var pemEndOfLine = strings.Bytes("-----") // Decode will find the next PEM formatted block (certificate, private key // etc) in the input. It returns that block and the remainder of the input. If // no PEM data is found, p is nil and the whole of the input is returned in // rest. func Decode(data []byte) (p *Block, rest []byte) { // pemStart begins with a newline. However, at the very beginning of // the byte array, we'll accept the start string without it. rest = data; if bytes.HasPrefix(data, pemStart[1:len(pemStart)]) { rest = rest[len(pemStart)-1 : len(data)]; } else if i := bytes.Index(data, pemStart); i >= 0 { rest = rest[i+len(pemStart) : len(data)]; } else { return nil, data; } typeLine, rest := getLine(rest); if !bytes.HasSuffix(typeLine, pemEndOfLine) { goto Error; } typeLine = typeLine[0 : len(typeLine)-len(pemEndOfLine)]; p = &Block{ Headers: make(map[string]string), Type: string(typeLine), }; for { // This loop terminates because getLine's second result is // always smaller than it's argument. if len(rest) == 0 { return nil, data; } line, next := getLine(rest); i := bytes.Index(line, []byte{':'}); if i == -1 { break; } // TODO(agl): need to cope with values that spread across lines. key, val := line[0:i], line[i+1 : len(line)]; key = bytes.TrimSpace(key); val = bytes.TrimSpace(val); p.Headers[string(key)] = string(val); rest = next; } i := bytes.Index(rest, pemEnd); if i < 0 { goto Error; } base64Data := removeWhitespace(rest[0:i]); p.Bytes = make([]byte, base64.StdEncoding.DecodedLen(len(base64Data))); n, err := base64.StdEncoding.Decode(base64Data, p.Bytes); if err != nil { goto Error; } p.Bytes = p.Bytes[0:n]; _, rest = getLine(rest[i+len(pemEnd) : len(rest)]); return; Error: // If we get here then we have rejected a likely looking, but // ultimately invalid PEM block. We need to start over from a new // position. We have consumed the preamble line and will have consumed // any lines which could be header lines. However, a valid preamble // line is not a valid header line, therefore we cannot have consumed // the preamble line for the any subsequent block. Thus, we will always // find any valid block, no matter what bytes preceed it. // // For example, if the input is // // -----BEGIN MALFORMED BLOCK----- // junk that may look like header lines // or data lines, but no END line // // -----BEGIN ACTUAL BLOCK----- // realdata // -----END ACTUAL BLOCK----- // // we've failed to parse using the first BEGIN line // and now will try again, using the second BEGIN line. p, rest = Decode(rest); if p == nil { rest = data; } return; }
src/pkg/encoding/pem/pem.go
0
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.0016163960099220276, 0.0002992016088683158, 0.00015800008259247988, 0.00017313490388914943, 0.0003430286596994847 ]
{ "id": 1, "code_window": [ "\tif special && trim_white {\n", "\t\t// consume trailing white space\n", "\t\tfor ; i < len(t.buf) && white(t.buf[i]); i++ {\n", "\t\t\tif t.buf[i] == '\\n' {\n", "\t\t\t\ti++;\n", "\t\t\t\tbreak\t// stop after newline\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tt.linenum++;\n" ], "file_path": "src/pkg/template/template.go", "type": "add", "edit_start_line_idx": 277 }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Data-driven templates for generating textual output such as HTML. See http://code.google.com/p/json-template/wiki/Reference for full documentation of the template language. A summary: Templates are executed by applying them to a data structure. Annotations in the template refer to elements of the data structure (typically a field of a struct) to control execution and derive values to be displayed. The template walks the structure as it executes and the "cursor" @ represents the value at the current location in the structure. Data items may be values or pointers; the interface hides the indirection. Major constructs ({} are metacharacters; [] marks optional elements): {# comment } A one-line comment. {.section field} XXX [ {.or} YYY ] {.end} Set @ to the value of the field. It may be an explicit @ to stay at the same point in the data. If the field is nil or empty, execute YYY; otherwise execute XXX. {.repeated section field} XXX [ {.alternates with} ZZZ ] [ {.or} YYY ] {.end} Like .section, but field must be an array or slice. XXX is executed for each element. If the array is nil or empty, YYY is executed instead. If the {.alternates with} marker is present, ZZZ is executed between iterations of XXX. {field} {field|formatter} Insert the value of the field into the output. Field is first looked for in the cursor, as in .section and .repeated. If it is not found, the search continues in outer sections until the top level is reached. If a formatter is specified, it must be named in the formatter map passed to the template set up routines or in the default set ("html","str","") and is used to process the data for output. The formatter function has signature func(wr io.Write, data interface{}, formatter string) where wr is the destination for output, data is the field value, and formatter is its name at the invocation site. */ package template import ( "container/vector"; "fmt"; "io"; "os"; "reflect"; "runtime"; "strings"; ) // Errors returned during parsing and execution. Users may extract the information and reformat // if they desire. type Error struct { Line int; Msg string; } func (e *Error) String() string { return fmt.Sprintf("line %d: %s", e.Line, e.Msg) } // Most of the literals are aces. var lbrace = []byte{ '{' } var rbrace = []byte{ '}' } var space = []byte{ ' ' } var tab = []byte{ '\t' } // The various types of "tokens", which are plain text or (usually) brace-delimited descriptors const ( tokAlternates = iota; tokComment; tokEnd; tokLiteral; tokOr; tokRepeated; tokSection; tokText; tokVariable; ) // FormatterMap is the type describing the mapping from formatter // names to the functions that implement them. type FormatterMap map[string] func(io.Writer, interface{}, string) // Built-in formatters. var builtins = FormatterMap { "html" : HtmlFormatter, "str" : StringFormatter, "" : StringFormatter, } // The parsed state of a template is a vector of xxxElement structs. // Sections have line numbers so errors can be reported better during execution. // Plain text. type textElement struct { text []byte; } // A literal such as .meta-left or .meta-right type literalElement struct { text []byte; } // A variable to be evaluated type variableElement struct { linenum int; name string; formatter string; // TODO(r): implement pipelines } // A .section block, possibly with a .or type sectionElement struct { linenum int; // of .section itself field string; // cursor field for this block start int; // first element or int; // first element of .or block end int; // one beyond last element } // A .repeated block, possibly with a .or and a .alternates type repeatedElement struct { sectionElement; // It has the same structure... altstart int; // ... except for alternates altend int; } // Template is the type that represents a template definition. // It is unchanged after parsing. type Template struct { fmap FormatterMap; // formatters for variables // Used during parsing: ldelim, rdelim []byte; // delimiters; default {} buf []byte; // input text to process p int; // position in buf linenum int; // position in input error os.Error; // error during parsing (only) // Parsed results: elems *vector.Vector; } // Internal state for executing a Template. As we evaluate the struct, // the data item descends into the fields associated with sections, etc. // Parent is used to walk upwards to find variables higher in the tree. type state struct { parent *state; // parent in hierarchy data reflect.Value; // the driver data for this section etc. wr io.Writer; // where to send output errors chan os.Error; // for reporting errors during execute } func (parent *state) clone(data reflect.Value) *state { return &state{parent, data, parent.wr, parent.errors} } // New creates a new template with the specified formatter map (which // may be nil) to define auxiliary functions for formatting variables. func New(fmap FormatterMap) *Template { t := new(Template); t.fmap = fmap; t.ldelim = lbrace; t.rdelim = rbrace; t.elems = vector.New(0); return t; } // Report error and stop executing. The line number must be provided explicitly. func (t *Template) execError(st *state, line int, err string, args ...) { st.errors <- &Error{line, fmt.Sprintf(err, args)}; runtime.Goexit(); } // Report error, save in Template to terminate parsing. // The line number comes from the template state. func (t *Template) parseError(err string, args ...) { t.error = &Error{t.linenum, fmt.Sprintf(err, args)}; } // -- Lexical analysis // Is c a white space character? func white(c uint8) bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n' } // Safely, does s[n:n+len(t)] == t? func equal(s []byte, n int, t []byte) bool { b := s[n:len(s)]; if len(t) > len(b) { // not enough space left for a match. return false } for i , c := range t { if c != b[i] { return false } } return true } // nextItem returns the next item from the input buffer. If the returned // item is empty, we are at EOF. The item will be either a // delimited string or a non-empty string between delimited // strings. Tokens stop at (but include, if plain text) a newline. // Action tokens on a line by themselves drop the white space on // either side, up to and including the newline. func (t *Template) nextItem() []byte { sawLeft := false; // are we waiting for an opening delimiter? special := false; // is this a {.foo} directive, which means trim white space? // Delete surrounding white space if this {.foo} is the only thing on the line. trim_white := t.p == 0 || t.buf[t.p-1] == '\n'; only_white := true; // we have seen only white space so far var i int; start := t.p; Loop: for i = t.p; i < len(t.buf); i++ { switch { case t.buf[i] == '\n': t.linenum++; i++; break Loop; case white(t.buf[i]): // white space, do nothing case !sawLeft && equal(t.buf, i, t.ldelim): // sawLeft checked because delims may be equal // anything interesting already on the line? if !only_white { break Loop; } // is it a directive or comment? j := i + len(t.ldelim); // position after delimiter if j+1 < len(t.buf) && (t.buf[j] == '.' || t.buf[j] == '#') { special = true; if trim_white && only_white { start = i; } } else if i > t.p { // have some text accumulated so stop before delimiter break Loop; } sawLeft = true; i = j - 1; case equal(t.buf, i, t.rdelim): if !sawLeft { t.parseError("unmatched closing delimiter"); return nil; } sawLeft = false; i += len(t.rdelim); break Loop; default: only_white = false; } } if sawLeft { t.parseError("unmatched opening delimiter"); return nil; } item := t.buf[start:i]; if special && trim_white { // consume trailing white space for ; i < len(t.buf) && white(t.buf[i]); i++ { if t.buf[i] == '\n' { i++; break // stop after newline } } } t.p = i; return item } // Turn a byte array into a white-space-split array of strings. func words(buf []byte) []string { s := make([]string, 0, 5); p := 0; // position in buf // one word per loop for i := 0; ; i++ { // skip white space for ; p < len(buf) && white(buf[p]); p++ { } // grab word start := p; for ; p < len(buf) && !white(buf[p]); p++ { } if start == p { // no text left break } if i == cap(s) { ns := make([]string, 2*cap(s)); for j := range s { ns[j] = s[j] } s = ns; } s = s[0:i+1]; s[i] = string(buf[start:p]) } return s } // Analyze an item and return its token type and, if it's an action item, an array of // its constituent words. func (t *Template) analyze(item []byte) (tok int, w []string) { // item is known to be non-empty if !equal(item, 0, t.ldelim) { // doesn't start with left delimiter tok = tokText; return; } if !equal(item, len(item)-len(t.rdelim), t.rdelim) { // doesn't end with right delimiter t.parseError("internal error: unmatched opening delimiter"); // lexing should prevent this return; } if len(item) <= len(t.ldelim)+len(t.rdelim) { // no contents t.parseError("empty directive"); return; } // Comment if item[len(t.ldelim)] == '#' { tok = tokComment; return } // Split into words w = words(item[len(t.ldelim): len(item)-len(t.rdelim)]); // drop final delimiter if len(w) == 0 { t.parseError("empty directive"); return; } if len(w) == 1 && w[0][0] != '.' { tok = tokVariable; return; } switch w[0] { case ".meta-left", ".meta-right", ".space", ".tab": tok = tokLiteral; return; case ".or": tok = tokOr; return; case ".end": tok = tokEnd; return; case ".section": if len(w) != 2 { t.parseError("incorrect fields for .section: %s", item); return; } tok = tokSection; return; case ".repeated": if len(w) != 3 || w[1] != "section" { t.parseError("incorrect fields for .repeated: %s", item); return; } tok = tokRepeated; return; case ".alternates": if len(w) != 2 || w[1] != "with" { t.parseError("incorrect fields for .alternates: %s", item); return; } tok = tokAlternates; return; } t.parseError("bad directive: %s", item); return } // -- Parsing // Allocate a new variable-evaluation element. func (t *Template) newVariable(name_formatter string) (v *variableElement) { name := name_formatter; formatter := ""; bar := strings.Index(name_formatter, "|"); if bar >= 0 { name = name_formatter[0:bar]; formatter = name_formatter[bar+1:len(name_formatter)]; } // Probably ok, so let's build it. v = &variableElement{t.linenum, name, formatter}; // We could remember the function address here and avoid the lookup later, // but it's more dynamic to let the user change the map contents underfoot. // We do require the name to be present, though. // Is it in user-supplied map? if t.fmap != nil { if _, ok := t.fmap[formatter]; ok { return } } // Is it in builtin map? if _, ok := builtins[formatter]; ok { return } t.parseError("unknown formatter: %s", formatter); return } // Grab the next item. If it's simple, just append it to the template. // Otherwise return its details. func (t *Template) parseSimple(item []byte) (done bool, tok int, w []string) { tok, w = t.analyze(item); if t.error != nil { return } done = true; // assume for simplicity switch tok { case tokComment: return; case tokText: t.elems.Push(&textElement{item}); return; case tokLiteral: switch w[0] { case ".meta-left": t.elems.Push(&literalElement{t.ldelim}); case ".meta-right": t.elems.Push(&literalElement{t.rdelim}); case ".space": t.elems.Push(&literalElement{space}); case ".tab": t.elems.Push(&literalElement{tab}); default: t.parseError("internal error: unknown literal: %s", w[0]); return; } return; case tokVariable: t.elems.Push(t.newVariable(w[0])); return; } return false, tok, w } // parseRepeated and parseSection are mutually recursive func (t *Template) parseRepeated(words []string) *repeatedElement { r := new(repeatedElement); t.elems.Push(r); r.linenum = t.linenum; r.field = words[2]; // Scan section, collecting true and false (.or) blocks. r.start = t.elems.Len(); r.or = -1; r.altstart = -1; r.altend = -1; Loop: for t.error == nil { item := t.nextItem(); if t.error != nil { break; } if len(item) == 0 { t.parseError("missing .end for .repeated section"); break; } done, tok, w := t.parseSimple(item); if t.error != nil { break; } if done { continue } switch tok { case tokEnd: break Loop; case tokOr: if r.or >= 0 { t.parseError("extra .or in .repeated section"); break Loop; } r.altend = t.elems.Len(); r.or = t.elems.Len(); case tokSection: t.parseSection(w); case tokRepeated: t.parseRepeated(w); case tokAlternates: if r.altstart >= 0 { t.parseError("extra .alternates in .repeated section"); break Loop; } if r.or >= 0 { t.parseError(".alternates inside .or block in .repeated section"); break Loop; } r.altstart = t.elems.Len(); default: t.parseError("internal error: unknown repeated section item: %s", item); break Loop; } } if t.error != nil { return nil } if r.altend < 0 { r.altend = t.elems.Len() } r.end = t.elems.Len(); return r; } func (t *Template) parseSection(words []string) *sectionElement { s := new(sectionElement); t.elems.Push(s); s.linenum = t.linenum; s.field = words[1]; // Scan section, collecting true and false (.or) blocks. s.start = t.elems.Len(); s.or = -1; Loop: for t.error == nil { item := t.nextItem(); if t.error != nil { break; } if len(item) == 0 { t.parseError("missing .end for .section"); break; } done, tok, w := t.parseSimple(item); if t.error != nil { break; } if done { continue } switch tok { case tokEnd: break Loop; case tokOr: if s.or >= 0 { t.parseError("extra .or in .section"); break Loop; } s.or = t.elems.Len(); case tokSection: t.parseSection(w); case tokRepeated: t.parseRepeated(w); case tokAlternates: t.parseError(".alternates not in .repeated"); default: t.parseError("internal error: unknown section item: %s", item); } } if t.error != nil { return nil } s.end = t.elems.Len(); return s; } func (t *Template) parse() { for t.error == nil { item := t.nextItem(); if t.error != nil { break } if len(item) == 0 { break } done, tok, w := t.parseSimple(item); if done { continue } switch tok { case tokOr, tokEnd, tokAlternates: t.parseError("unexpected %s", w[0]); case tokSection: t.parseSection(w); case tokRepeated: t.parseRepeated(w); default: t.parseError("internal error: bad directive in parse: %s", item); } } } // -- Execution // If the data for this template is a struct, find the named variable. // Names of the form a.b.c are walked down the data tree. // The special name "@" (the "cursor") denotes the current data. // The value coming in (st.data) might need indirecting to reach // a struct while the return value is not indirected - that is, // it represents the actual named field. func (st *state) findVar(s string) reflect.Value { if s == "@" { return st.data } data := st.data; elems := strings.Split(s, ".", 0); for i := 0; i < len(elems); i++ { // Look up field; data must be a struct. data = reflect.Indirect(data); if data == nil { return nil } typ, ok := data.Type().(*reflect.StructType); if !ok { return nil } field, ok := typ.FieldByName(elems[i]); if !ok { return nil } data = data.(*reflect.StructValue).FieldByIndex(field.Index); } return data } // Is there no data to look at? func empty(v reflect.Value) bool { v = reflect.Indirect(v); if v == nil { return true } switch v := v.(type) { case *reflect.BoolValue: return v.Get() == false; case *reflect.StringValue: return v.Get() == ""; case *reflect.StructValue: return false; case *reflect.ArrayValue: return v.Len() == 0; case *reflect.SliceValue: return v.Len() == 0; } return true; } // Look up a variable, up through the parent if necessary. func (t *Template) varValue(name string, st *state) reflect.Value { field := st.findVar(name); if field == nil { if st.parent == nil { t.execError(st, t.linenum, "name not found: %s", name) } return t.varValue(name, st.parent); } return field; } // Evaluate a variable, looking up through the parent if necessary. // If it has a formatter attached ({var|formatter}) run that too. func (t *Template) writeVariable(v *variableElement, st *state) { formatter := v.formatter; val := t.varValue(v.name, st).Interface(); // is it in user-supplied map? if t.fmap != nil { if fn, ok := t.fmap[formatter]; ok { fn(st.wr, val, formatter); return; } } // is it in builtin map? if fn, ok := builtins[formatter]; ok { fn(st.wr, val, formatter); return; } t.execError(st, v.linenum, "missing formatter %s for variable %s", formatter, v.name) } // Execute element i. Return next index to execute. func (t *Template) executeElement(i int, st *state) int { switch elem := t.elems.At(i).(type) { case *textElement: st.wr.Write(elem.text); return i+1; case *literalElement: st.wr.Write(elem.text); return i+1; case *variableElement: t.writeVariable(elem, st); return i+1; case *sectionElement: t.executeSection(elem, st); return elem.end; case *repeatedElement: t.executeRepeated(elem, st); return elem.end; } e := t.elems.At(i); t.execError(st, 0, "internal error: bad directive in execute: %v %T\n", reflect.NewValue(e).Interface(), e); return 0 } // Execute the template. func (t *Template) execute(start, end int, st *state) { for i := start; i < end; { i = t.executeElement(i, st) } } // Execute a .section func (t *Template) executeSection(s *sectionElement, st *state) { // Find driver data for this section. It must be in the current struct. field := t.varValue(s.field, st); if field == nil { t.execError(st, s.linenum, ".section: cannot find field %s in %s", s.field, reflect.Indirect(st.data).Type()); } st = st.clone(field); start, end := s.start, s.or; if !empty(field) { // Execute the normal block. if end < 0 { end = s.end } } else { // Execute the .or block. If it's missing, do nothing. start, end = s.or, s.end; if start < 0 { return } } for i := start; i < end; { i = t.executeElement(i, st) } } // Return the result of calling the Iter method on v, or nil. func iter(v reflect.Value) *reflect.ChanValue { for j := 0; j < v.Type().NumMethod(); j++ { mth := v.Type().Method(j); fv := v.Method(j); ft := fv.Type().(*reflect.FuncType); // TODO(rsc): NumIn() should return 0 here, because ft is from a curried FuncValue. if mth.Name != "Iter" || ft.NumIn() != 1 || ft.NumOut() != 1 { continue } ct, ok := ft.Out(0).(*reflect.ChanType); if !ok || ct.Dir() & reflect.RecvDir == 0 { continue } return fv.Call(nil)[0].(*reflect.ChanValue) } return nil } // Execute a .repeated section func (t *Template) executeRepeated(r *repeatedElement, st *state) { // Find driver data for this section. It must be in the current struct. field := t.varValue(r.field, st); if field == nil { t.execError(st, r.linenum, ".repeated: cannot find field %s in %s", r.field, reflect.Indirect(st.data).Type()); } start, end := r.start, r.or; if end < 0 { end = r.end } if r.altstart >= 0 { end = r.altstart } first := true; if array, ok := field.(reflect.ArrayOrSliceValue); ok { for j := 0; j < array.Len(); j++ { newst := st.clone(array.Elem(j)); // .alternates between elements if !first && r.altstart >= 0 { for i := r.altstart; i < r.altend; { i = t.executeElement(i, newst) } } first = false; for i := start; i < end; { i = t.executeElement(i, newst) } } } else if ch := iter(field); ch != nil { for { e := ch.Recv(); if ch.Closed() { break } newst := st.clone(e); // .alternates between elements if !first && r.altstart >= 0 { for i := r.altstart; i < r.altend; { i = t.executeElement(i, newst) } } first = false; for i := start; i < end; { i = t.executeElement(i, newst) } } } else { t.execError(st, r.linenum, ".repeated: cannot repeat %s (type %s)", r.field, field.Type()); } if first { // Empty. Execute the .or block, once. If it's missing, do nothing. start, end := r.or, r.end; if start >= 0 { newst := st.clone(field); for i := start; i < end; { i = t.executeElement(i, newst) } } return } } // A valid delimiter must contain no white space and be non-empty. func validDelim(d []byte) bool { if len(d) == 0 { return false } for _, c := range d { if white(c) { return false } } return true; } // -- Public interface // Parse initializes a Template by parsing its definition. The string // s contains the template text. If any errors occur, Parse returns // the error. func (t *Template) Parse(s string) os.Error { if !validDelim(t.ldelim) || !validDelim(t.rdelim) { return &Error{1, fmt.Sprintf("bad delimiter strings %q %q", t.ldelim, t.rdelim)} } t.buf = strings.Bytes(s); t.p = 0; t.linenum = 0; t.parse(); return t.error; } // Execute applies a parsed template to the specified data object, // generating output to wr. func (t *Template) Execute(data interface{}, wr io.Writer) os.Error { // Extract the driver data. val := reflect.NewValue(data); errors := make(chan os.Error); go func() { t.p = 0; t.execute(0, t.elems.Len(), &state{nil, val, wr, errors}); errors <- nil; // clean return; }(); return <-errors; } // SetDelims sets the left and right delimiters for operations in the // template. They are validated during parsing. They could be // validated here but it's better to keep the routine simple. The // delimiters are very rarely invalid and Parse has the necessary // error-handling interface already. func (t *Template) SetDelims(left, right string) { t.ldelim = strings.Bytes(left); t.rdelim = strings.Bytes(right); } // Parse creates a Template with default parameters (such as {} for // metacharacters). The string s contains the template text while // the formatter map fmap, which may be nil, defines auxiliary functions // for formatting variables. The template is returned. If any errors // occur, err will be non-nil. func Parse(s string, fmap FormatterMap) (t *Template, err os.Error) { t = New(fmap); err = t.Parse(s); if err != nil { t = nil } return } // MustParse is like Parse but panics if the template cannot be parsed. func MustParse(s string, fmap FormatterMap) *Template { t , err := Parse(s, fmap); if err != nil { panic("template parse error: ", err); } return t }
src/pkg/template/template.go
1
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.9976557493209839, 0.06489713490009308, 0.00016239167598541826, 0.00018576484580989927, 0.23627910017967224 ]
{ "id": 1, "code_window": [ "\tif special && trim_white {\n", "\t\t// consume trailing white space\n", "\t\tfor ; i < len(t.buf) && white(t.buf[i]); i++ {\n", "\t\t\tif t.buf[i] == '\\n' {\n", "\t\t\t\ti++;\n", "\t\t\t\tbreak\t// stop after newline\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tt.linenum++;\n" ], "file_path": "src/pkg/template/template.go", "type": "add", "edit_start_line_idx": 277 }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // decimal to binary floating point conversion. // Algorithm: // 1) Store input in multiprecision decimal. // 2) Multiply/divide decimal by powers of two until in range [0.5, 1) // 3) Multiply by 2^precision and round to get mantissa. // The strconv package implements conversions to and from // string representations of basic data types. package strconv import ( "math"; "os"; ) var optimize = true // can change for testing // TODO(rsc): Better truncation handling. func stringToDecimal(s string) (neg bool, d *decimal, trunc bool, ok bool) { i := 0; // optional sign if i >= len(s) { return; } switch { case s[i] == '+': i++; case s[i] == '-': neg = true; i++; } // digits b := new(decimal); sawdot := false; sawdigits := false; for ; i < len(s); i++ { switch { case s[i] == '.': if sawdot { return; } sawdot = true; b.dp = b.nd; continue; case '0' <= s[i] && s[i] <= '9': sawdigits = true; if s[i] == '0' && b.nd == 0 { // ignore leading zeros b.dp--; continue; } b.d[b.nd] = s[i]; b.nd++; continue; } break; } if !sawdigits { return; } if !sawdot { b.dp = b.nd; } // optional exponent moves decimal point. // if we read a very large, very long number, // just be sure to move the decimal point by // a lot (say, 100000). it doesn't matter if it's // not the exact number. if i < len(s) && s[i] == 'e' { i++; if i >= len(s) { return; } esign := 1; if s[i] == '+' { i++; } else if s[i] == '-' { i++; esign = -1; } if i >= len(s) || s[i] < '0' || s[i] > '9' { return; } e := 0; for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ { if e < 10000 { e = e*10 + int(s[i]) - '0'; } } b.dp += e*esign; } if i != len(s) { return; } d = b; ok = true; return; } // decimal power of ten to binary power of two. var powtab = []int{1, 3, 6, 9, 13, 16, 19, 23, 26} func decimalToFloatBits(neg bool, d *decimal, trunc bool, flt *floatInfo) (b uint64, overflow bool) { var exp int; var mant uint64; // Zero is always a special case. if d.nd == 0 { mant = 0; exp = flt.bias; goto out; } // Obvious overflow/underflow. // These bounds are for 64-bit floats. // Will have to change if we want to support 80-bit floats in the future. if d.dp > 310 { goto overflow; } if d.dp < -330 { // zero mant = 0; exp = flt.bias; goto out; } // Scale by powers of two until in range [0.5, 1.0) exp = 0; for d.dp > 0 { var n int; if d.dp >= len(powtab) { n = 27; } else { n = powtab[d.dp]; } d.Shift(-n); exp += n; } for d.dp < 0 || d.dp == 0 && d.d[0] < '5' { var n int; if -d.dp >= len(powtab) { n = 27; } else { n = powtab[-d.dp]; } d.Shift(n); exp -= n; } // Our range is [0.5,1) but floating point range is [1,2). exp--; // Minimum representable exponent is flt.bias+1. // If the exponent is smaller, move it up and // adjust d accordingly. if exp < flt.bias + 1 { n := flt.bias + 1 - exp; d.Shift(-n); exp += n; } if exp - flt.bias >= 1 << flt.expbits - 1 { goto overflow; } // Extract 1+flt.mantbits bits. mant = d.Shift(int(1 + flt.mantbits)).RoundedInteger(); // Rounding might have added a bit; shift down. if mant == 2 << flt.mantbits { mant >>= 1; exp++; if exp - flt.bias >= 1 << flt.expbits - 1 { goto overflow; } } // Denormalized? if mant&(1 << flt.mantbits) == 0 { exp = flt.bias; } goto out; overflow: // ±Inf mant = 0; exp = 1 << flt.expbits - 1 + flt.bias; overflow = true; out: // Assemble bits. bits := mant&(uint64(1) << flt.mantbits - 1); bits |= uint64((exp - flt.bias)&(1 << flt.expbits - 1)) << flt.mantbits; if neg { bits |= 1 << flt.mantbits << flt.expbits; } return bits, overflow; } // Compute exact floating-point integer from d's digits. // Caller is responsible for avoiding overflow. func decimalAtof64Int(neg bool, d *decimal) float64 { f := float64(0); for i := 0; i < d.nd; i++ { f = f*10 + float64(d.d[i] - '0'); } if neg { f *= -1; // BUG work around 6g f = -f. } return f; } func decimalAtof32Int(neg bool, d *decimal) float32 { f := float32(0); for i := 0; i < d.nd; i++ { f = f*10 + float32(d.d[i] - '0'); } if neg { f *= -1; // BUG work around 6g f = -f. } return f; } // Exact powers of 10. var float64pow10 = []float64{ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22, } var float32pow10 = []float32{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10} // If possible to convert decimal d to 64-bit float f exactly, // entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits. // Three common cases: // value is exact integer // value is exact integer * exact power of ten // value is exact integer / exact power of ten // These all produce potentially inexact but correctly rounded answers. func decimalAtof64(neg bool, d *decimal, trunc bool) (f float64, ok bool) { // Exact integers are <= 10^15. // Exact powers of ten are <= 10^22. if d.nd > 15 { return; } switch { case d.dp == d.nd: // int f := decimalAtof64Int(neg, d); return f, true; case d.dp > d.nd && d.dp <= 15+22: // int * 10^k f := decimalAtof64Int(neg, d); k := d.dp - d.nd; // If exponent is big but number of digits is not, // can move a few zeros into the integer part. if k > 22 { f *= float64pow10[k-22]; k = 22; } return f * float64pow10[k], true; case d.dp < d.nd && d.nd - d.dp <= 22: // int / 10^k f := decimalAtof64Int(neg, d); return f / float64pow10[d.nd - d.dp], true; } return; } // If possible to convert decimal d to 32-bit float f exactly, // entirely in floating-point math, do so, avoiding the machinery above. func decimalAtof32(neg bool, d *decimal, trunc bool) (f float32, ok bool) { // Exact integers are <= 10^7. // Exact powers of ten are <= 10^10. if d.nd > 7 { return; } switch { case d.dp == d.nd: // int f := decimalAtof32Int(neg, d); return f, true; case d.dp > d.nd && d.dp <= 7+10: // int * 10^k f := decimalAtof32Int(neg, d); k := d.dp - d.nd; // If exponent is big but number of digits is not, // can move a few zeros into the integer part. if k > 10 { f *= float32pow10[k-10]; k = 10; } return f * float32pow10[k], true; case d.dp < d.nd && d.nd - d.dp <= 10: // int / 10^k f := decimalAtof32Int(neg, d); return f / float32pow10[d.nd - d.dp], true; } return; } // Atof32 converts the string s to a 32-bit floating-point number. // // If s is well-formed and near a valid floating point number, // Atof32 returns the nearest floating point number rounded // using IEEE754 unbiased rounding. // // The errors that Atof32 returns have concrete type *NumError // and include err.Num = s. // // If s is not syntactically well-formed, Atof32 returns err.Error = os.EINVAL. // // If s is syntactically well-formed but is more than 1/2 ULP // away from the largest floating point number of the given size, // Atof32 returns f = ±Inf, err.Error = os.ERANGE. func Atof32(s string) (f float32, err os.Error) { neg, d, trunc, ok := stringToDecimal(s); if !ok { return 0, &NumError{s, os.EINVAL}; } if optimize { if f, ok := decimalAtof32(neg, d, trunc); ok { return f, nil; } } b, ovf := decimalToFloatBits(neg, d, trunc, &float32info); f = math.Float32frombits(uint32(b)); if ovf { err = &NumError{s, os.ERANGE}; } return f, err; } // Atof64 converts the string s to a 64-bit floating-point number. // Except for the type of its result, its definition is the same as that // of Atof32. func Atof64(s string) (f float64, err os.Error) { neg, d, trunc, ok := stringToDecimal(s); if !ok { return 0, &NumError{s, os.EINVAL}; } if optimize { if f, ok := decimalAtof64(neg, d, trunc); ok { return f, nil; } } b, ovf := decimalToFloatBits(neg, d, trunc, &float64info); f = math.Float64frombits(b); if ovf { err = &NumError{s, os.ERANGE}; } return f, err; } // Atof is like Atof32 or Atof64, depending on the size of float. func Atof(s string) (f float, err os.Error) { if FloatSize == 32 { f1, err1 := Atof32(s); return float(f1), err1; } f1, err1 := Atof64(s); return float(f1), err1; }
src/pkg/strconv/atof.go
0
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.3087421655654907, 0.00898666214197874, 0.0001627145247766748, 0.0001754329859977588, 0.04998341202735901 ]
{ "id": 1, "code_window": [ "\tif special && trim_white {\n", "\t\t// consume trailing white space\n", "\t\tfor ; i < len(t.buf) && white(t.buf[i]); i++ {\n", "\t\t\tif t.buf[i] == '\\n' {\n", "\t\t\t\ti++;\n", "\t\t\t\tbreak\t// stop after newline\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tt.linenum++;\n" ], "file_path": "src/pkg/template/template.go", "type": "add", "edit_start_line_idx": 277 }
/* Plan 9 from User Space src/lib9/_p9dir.c http://code.swtch.com/plan9port/src/tip/src/lib9/_p9dir.c Copyright 2001-2007 Russ Cox. All Rights Reserved. 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. */ #include <u.h> #define NOPLAN9DEFINES #include <libc.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <pwd.h> #include <grp.h> #if defined(__FreeBSD__) #include <sys/disk.h> #include <sys/disklabel.h> #include <sys/ioctl.h> #endif #if defined(__OpenBSD__) #include <sys/disklabel.h> #include <sys/ioctl.h> #define _HAVEDISKLABEL static int diskdev[] = { 151, /* aacd */ 116, /* ad */ 157, /* ar */ 118, /* afd */ 133, /* amrd */ 13, /* da */ 102, /* fla */ 109, /* idad */ 95, /* md */ 131, /* mlxd */ 168, /* pst */ 147, /* twed */ 43, /* vn */ 3, /* wd */ 87, /* wfd */ 4, /* da on FreeBSD 5 */ }; static int isdisk(struct stat *st) { int i, dev; if(!S_ISCHR(st->st_mode)) return 0; dev = major(st->st_rdev); for(i=0; i<nelem(diskdev); i++) if(diskdev[i] == dev) return 1; return 0; } #endif #if defined(__FreeBSD__) /* maybe OpenBSD too? */ char *diskdev[] = { "aacd", "ad", "ar", "afd", "amrd", "da", "fla", "idad", "md", "mlxd", "pst", "twed", "vn", "wd", "wfd", "da", }; static int isdisk(struct stat *st) { char *name; int i, len; if(!S_ISCHR(st->st_mode)) return 0; name = devname(st->st_rdev, S_IFCHR); for(i=0; i<nelem(diskdev); i++){ len = strlen(diskdev[i]); if(strncmp(diskdev[i], name, len) == 0 && isdigit((uchar)name[len])) return 1; } return 0; } #endif #if defined(__linux__) #include <linux/hdreg.h> #include <linux/fs.h> #include <sys/ioctl.h> #undef major #define major(dev) ((int)(((dev) >> 8) & 0xff)) static vlong disksize(int fd, int dev) { u64int u64; long l; struct hd_geometry geo; memset(&geo, 0, sizeof geo); l = 0; u64 = 0; #ifdef BLKGETSIZE64 if(ioctl(fd, BLKGETSIZE64, &u64) >= 0) return u64; #endif if(ioctl(fd, BLKGETSIZE, &l) >= 0) return l*512; if(ioctl(fd, HDIO_GETGEO, &geo) >= 0) return (vlong)geo.heads*geo.sectors*geo.cylinders*512; return 0; } #define _HAVEDISKSIZE #endif #if !defined(__linux__) && !defined(__sun__) #define _HAVESTGEN #endif int _p9usepwlibrary = 1; /* * Caching the last group and passwd looked up is * a significant win (stupidly enough) on most systems. * It's not safe for threaded programs, but neither is using * getpwnam in the first place, so I'm not too worried. */ int _p9dir(struct stat *lst, struct stat *st, char *name, Dir *d, char **str, char *estr) { char *s; char tmp[20]; static struct group *g; static struct passwd *p; static int gid, uid; int sz, fd; fd = -1; USED(fd); sz = 0; if(d) memset(d, 0, sizeof *d); /* name */ s = strrchr(name, '/'); if(s) s++; if(!s || !*s) s = name; if(*s == '/') s++; if(*s == 0) s = "/"; if(d){ if(*str + strlen(s)+1 > estr) d->name = "oops"; else{ strcpy(*str, s); d->name = *str; *str += strlen(*str)+1; } } sz += strlen(s)+1; /* user */ if(p && st->st_uid == uid && p->pw_uid == uid) ; else if(_p9usepwlibrary){ p = getpwuid(st->st_uid); uid = st->st_uid; } if(p == nil || st->st_uid != uid || p->pw_uid != uid){ snprint(tmp, sizeof tmp, "%d", (int)st->st_uid); s = tmp; }else s = p->pw_name; sz += strlen(s)+1; if(d){ if(*str+strlen(s)+1 > estr) d->uid = "oops"; else{ strcpy(*str, s); d->uid = *str; *str += strlen(*str)+1; } } /* group */ if(g && st->st_gid == gid && g->gr_gid == gid) ; else if(_p9usepwlibrary){ g = getgrgid(st->st_gid); gid = st->st_gid; } if(g == nil || st->st_gid != gid || g->gr_gid != gid){ snprint(tmp, sizeof tmp, "%d", (int)st->st_gid); s = tmp; }else s = g->gr_name; sz += strlen(s)+1; if(d){ if(*str + strlen(s)+1 > estr) d->gid = "oops"; else{ strcpy(*str, s); d->gid = *str; *str += strlen(*str)+1; } } if(d){ d->type = 'M'; d->muid = ""; d->qid.path = ((uvlong)st->st_dev<<32) | st->st_ino; #ifdef _HAVESTGEN d->qid.vers = st->st_gen; #endif if(d->qid.vers == 0) d->qid.vers = st->st_mtime + st->st_ctime; d->mode = st->st_mode&0777; d->atime = st->st_atime; d->mtime = st->st_mtime; d->length = st->st_size; if(S_ISDIR(st->st_mode)){ d->length = 0; d->mode |= DMDIR; d->qid.type = QTDIR; } if(S_ISLNK(lst->st_mode)) /* yes, lst not st */ d->mode |= DMSYMLINK; if(S_ISFIFO(st->st_mode)) d->mode |= DMNAMEDPIPE; if(S_ISSOCK(st->st_mode)) d->mode |= DMSOCKET; if(S_ISBLK(st->st_mode)){ d->mode |= DMDEVICE; d->qid.path = ('b'<<16)|st->st_rdev; } if(S_ISCHR(st->st_mode)){ d->mode |= DMDEVICE; d->qid.path = ('c'<<16)|st->st_rdev; } /* fetch real size for disks */ #ifdef _HAVEDISKSIZE if(S_ISBLK(st->st_mode) && (fd = open(name, O_RDONLY)) >= 0){ d->length = disksize(fd, major(st->st_dev)); close(fd); } #endif #if defined(DIOCGMEDIASIZE) if(isdisk(st)){ int fd; off_t mediasize; if((fd = open(name, O_RDONLY)) >= 0){ if(ioctl(fd, DIOCGMEDIASIZE, &mediasize) >= 0) d->length = mediasize; close(fd); } } #elif defined(_HAVEDISKLABEL) if(isdisk(st)){ int fd, n; struct disklabel lab; if((fd = open(name, O_RDONLY)) < 0) goto nosize; if(ioctl(fd, DIOCGDINFO, &lab) < 0) goto nosize; n = minor(st->st_rdev)&7; if(n >= lab.d_npartitions) goto nosize; d->length = (vlong)(lab.d_partitions[n].p_size) * lab.d_secsize; nosize: if(fd >= 0) close(fd); } #endif } return sz; }
src/lib9/_p9dir.c
0
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.002400733530521393, 0.00035444850800558925, 0.00016101800429169089, 0.0001736590056680143, 0.0005688609089702368 ]
{ "id": 1, "code_window": [ "\tif special && trim_white {\n", "\t\t// consume trailing white space\n", "\t\tfor ; i < len(t.buf) && white(t.buf[i]); i++ {\n", "\t\t\tif t.buf[i] == '\\n' {\n", "\t\t\t\ti++;\n", "\t\t\t\tbreak\t// stop after newline\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tt.linenum++;\n" ], "file_path": "src/pkg/template/template.go", "type": "add", "edit_start_line_idx": 277 }
// $G $D/$F.go && $L $F.$A && ./$A.out || echo BUG wrong result // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main type A []int; func main() { var a [3]A; for i := 0; i < 3; i++ { a[i] = A{i}; } if a[0][0] != 0 { panic(); } if a[1][0] != 1 { panic(); } if a[2][0] != 2 { panic(); } } /* uetli:~/Source/go1/test/bugs gri$ 6g bug097.go && 6l bug097.6 && 6.out panic on line 342 PC=0x13c2 0x13c2?zi main·main(1, 0, 1606416416, ...) main·main(0x1, 0x7fff5fbff820, 0x0, ...) SIGTRAP: trace trap Faulting address: 0x4558 pc: 0x4558 0x4558?zi sys·Breakpoint(40960, 0, 45128, ...) sys·Breakpoint(0xa000, 0xb048, 0xa000, ...) 0x156a?zi sys·panicl(342, 0, 0, ...) sys·panicl(0x156, 0x300000000, 0xb024, ...) 0x13c2?zi main·main(1, 0, 1606416416, ...) main·main(0x1, 0x7fff5fbff820, 0x0, ...) */ /* An array composite literal needs to be created freshly every time. It is a "construction" of an array after all. If I pass the address of the array to some function, it may store it globally. Same applies to struct literals. */
test/fixedbugs/bug097.go
0
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.0002771882282104343, 0.00019008807430509478, 0.00016510998830199242, 0.000169271559570916, 0.00004358978185337037 ]
{ "id": 2, "code_window": [ "\t}\n", "\tt.buf = strings.Bytes(s);\n", "\tt.p = 0;\n", "\tt.linenum = 0;\n", "\tt.parse();\n", "\treturn t.error;\n", "}\n", "\n", "// Execute applies a parsed template to the specified data object,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tt.linenum = 1;\n" ], "file_path": "src/pkg/template/template.go", "type": "replace", "edit_start_line_idx": 852 }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Data-driven templates for generating textual output such as HTML. See http://code.google.com/p/json-template/wiki/Reference for full documentation of the template language. A summary: Templates are executed by applying them to a data structure. Annotations in the template refer to elements of the data structure (typically a field of a struct) to control execution and derive values to be displayed. The template walks the structure as it executes and the "cursor" @ represents the value at the current location in the structure. Data items may be values or pointers; the interface hides the indirection. Major constructs ({} are metacharacters; [] marks optional elements): {# comment } A one-line comment. {.section field} XXX [ {.or} YYY ] {.end} Set @ to the value of the field. It may be an explicit @ to stay at the same point in the data. If the field is nil or empty, execute YYY; otherwise execute XXX. {.repeated section field} XXX [ {.alternates with} ZZZ ] [ {.or} YYY ] {.end} Like .section, but field must be an array or slice. XXX is executed for each element. If the array is nil or empty, YYY is executed instead. If the {.alternates with} marker is present, ZZZ is executed between iterations of XXX. {field} {field|formatter} Insert the value of the field into the output. Field is first looked for in the cursor, as in .section and .repeated. If it is not found, the search continues in outer sections until the top level is reached. If a formatter is specified, it must be named in the formatter map passed to the template set up routines or in the default set ("html","str","") and is used to process the data for output. The formatter function has signature func(wr io.Write, data interface{}, formatter string) where wr is the destination for output, data is the field value, and formatter is its name at the invocation site. */ package template import ( "container/vector"; "fmt"; "io"; "os"; "reflect"; "runtime"; "strings"; ) // Errors returned during parsing and execution. Users may extract the information and reformat // if they desire. type Error struct { Line int; Msg string; } func (e *Error) String() string { return fmt.Sprintf("line %d: %s", e.Line, e.Msg) } // Most of the literals are aces. var lbrace = []byte{ '{' } var rbrace = []byte{ '}' } var space = []byte{ ' ' } var tab = []byte{ '\t' } // The various types of "tokens", which are plain text or (usually) brace-delimited descriptors const ( tokAlternates = iota; tokComment; tokEnd; tokLiteral; tokOr; tokRepeated; tokSection; tokText; tokVariable; ) // FormatterMap is the type describing the mapping from formatter // names to the functions that implement them. type FormatterMap map[string] func(io.Writer, interface{}, string) // Built-in formatters. var builtins = FormatterMap { "html" : HtmlFormatter, "str" : StringFormatter, "" : StringFormatter, } // The parsed state of a template is a vector of xxxElement structs. // Sections have line numbers so errors can be reported better during execution. // Plain text. type textElement struct { text []byte; } // A literal such as .meta-left or .meta-right type literalElement struct { text []byte; } // A variable to be evaluated type variableElement struct { linenum int; name string; formatter string; // TODO(r): implement pipelines } // A .section block, possibly with a .or type sectionElement struct { linenum int; // of .section itself field string; // cursor field for this block start int; // first element or int; // first element of .or block end int; // one beyond last element } // A .repeated block, possibly with a .or and a .alternates type repeatedElement struct { sectionElement; // It has the same structure... altstart int; // ... except for alternates altend int; } // Template is the type that represents a template definition. // It is unchanged after parsing. type Template struct { fmap FormatterMap; // formatters for variables // Used during parsing: ldelim, rdelim []byte; // delimiters; default {} buf []byte; // input text to process p int; // position in buf linenum int; // position in input error os.Error; // error during parsing (only) // Parsed results: elems *vector.Vector; } // Internal state for executing a Template. As we evaluate the struct, // the data item descends into the fields associated with sections, etc. // Parent is used to walk upwards to find variables higher in the tree. type state struct { parent *state; // parent in hierarchy data reflect.Value; // the driver data for this section etc. wr io.Writer; // where to send output errors chan os.Error; // for reporting errors during execute } func (parent *state) clone(data reflect.Value) *state { return &state{parent, data, parent.wr, parent.errors} } // New creates a new template with the specified formatter map (which // may be nil) to define auxiliary functions for formatting variables. func New(fmap FormatterMap) *Template { t := new(Template); t.fmap = fmap; t.ldelim = lbrace; t.rdelim = rbrace; t.elems = vector.New(0); return t; } // Report error and stop executing. The line number must be provided explicitly. func (t *Template) execError(st *state, line int, err string, args ...) { st.errors <- &Error{line, fmt.Sprintf(err, args)}; runtime.Goexit(); } // Report error, save in Template to terminate parsing. // The line number comes from the template state. func (t *Template) parseError(err string, args ...) { t.error = &Error{t.linenum, fmt.Sprintf(err, args)}; } // -- Lexical analysis // Is c a white space character? func white(c uint8) bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n' } // Safely, does s[n:n+len(t)] == t? func equal(s []byte, n int, t []byte) bool { b := s[n:len(s)]; if len(t) > len(b) { // not enough space left for a match. return false } for i , c := range t { if c != b[i] { return false } } return true } // nextItem returns the next item from the input buffer. If the returned // item is empty, we are at EOF. The item will be either a // delimited string or a non-empty string between delimited // strings. Tokens stop at (but include, if plain text) a newline. // Action tokens on a line by themselves drop the white space on // either side, up to and including the newline. func (t *Template) nextItem() []byte { sawLeft := false; // are we waiting for an opening delimiter? special := false; // is this a {.foo} directive, which means trim white space? // Delete surrounding white space if this {.foo} is the only thing on the line. trim_white := t.p == 0 || t.buf[t.p-1] == '\n'; only_white := true; // we have seen only white space so far var i int; start := t.p; Loop: for i = t.p; i < len(t.buf); i++ { switch { case t.buf[i] == '\n': t.linenum++; i++; break Loop; case white(t.buf[i]): // white space, do nothing case !sawLeft && equal(t.buf, i, t.ldelim): // sawLeft checked because delims may be equal // anything interesting already on the line? if !only_white { break Loop; } // is it a directive or comment? j := i + len(t.ldelim); // position after delimiter if j+1 < len(t.buf) && (t.buf[j] == '.' || t.buf[j] == '#') { special = true; if trim_white && only_white { start = i; } } else if i > t.p { // have some text accumulated so stop before delimiter break Loop; } sawLeft = true; i = j - 1; case equal(t.buf, i, t.rdelim): if !sawLeft { t.parseError("unmatched closing delimiter"); return nil; } sawLeft = false; i += len(t.rdelim); break Loop; default: only_white = false; } } if sawLeft { t.parseError("unmatched opening delimiter"); return nil; } item := t.buf[start:i]; if special && trim_white { // consume trailing white space for ; i < len(t.buf) && white(t.buf[i]); i++ { if t.buf[i] == '\n' { i++; break // stop after newline } } } t.p = i; return item } // Turn a byte array into a white-space-split array of strings. func words(buf []byte) []string { s := make([]string, 0, 5); p := 0; // position in buf // one word per loop for i := 0; ; i++ { // skip white space for ; p < len(buf) && white(buf[p]); p++ { } // grab word start := p; for ; p < len(buf) && !white(buf[p]); p++ { } if start == p { // no text left break } if i == cap(s) { ns := make([]string, 2*cap(s)); for j := range s { ns[j] = s[j] } s = ns; } s = s[0:i+1]; s[i] = string(buf[start:p]) } return s } // Analyze an item and return its token type and, if it's an action item, an array of // its constituent words. func (t *Template) analyze(item []byte) (tok int, w []string) { // item is known to be non-empty if !equal(item, 0, t.ldelim) { // doesn't start with left delimiter tok = tokText; return; } if !equal(item, len(item)-len(t.rdelim), t.rdelim) { // doesn't end with right delimiter t.parseError("internal error: unmatched opening delimiter"); // lexing should prevent this return; } if len(item) <= len(t.ldelim)+len(t.rdelim) { // no contents t.parseError("empty directive"); return; } // Comment if item[len(t.ldelim)] == '#' { tok = tokComment; return } // Split into words w = words(item[len(t.ldelim): len(item)-len(t.rdelim)]); // drop final delimiter if len(w) == 0 { t.parseError("empty directive"); return; } if len(w) == 1 && w[0][0] != '.' { tok = tokVariable; return; } switch w[0] { case ".meta-left", ".meta-right", ".space", ".tab": tok = tokLiteral; return; case ".or": tok = tokOr; return; case ".end": tok = tokEnd; return; case ".section": if len(w) != 2 { t.parseError("incorrect fields for .section: %s", item); return; } tok = tokSection; return; case ".repeated": if len(w) != 3 || w[1] != "section" { t.parseError("incorrect fields for .repeated: %s", item); return; } tok = tokRepeated; return; case ".alternates": if len(w) != 2 || w[1] != "with" { t.parseError("incorrect fields for .alternates: %s", item); return; } tok = tokAlternates; return; } t.parseError("bad directive: %s", item); return } // -- Parsing // Allocate a new variable-evaluation element. func (t *Template) newVariable(name_formatter string) (v *variableElement) { name := name_formatter; formatter := ""; bar := strings.Index(name_formatter, "|"); if bar >= 0 { name = name_formatter[0:bar]; formatter = name_formatter[bar+1:len(name_formatter)]; } // Probably ok, so let's build it. v = &variableElement{t.linenum, name, formatter}; // We could remember the function address here and avoid the lookup later, // but it's more dynamic to let the user change the map contents underfoot. // We do require the name to be present, though. // Is it in user-supplied map? if t.fmap != nil { if _, ok := t.fmap[formatter]; ok { return } } // Is it in builtin map? if _, ok := builtins[formatter]; ok { return } t.parseError("unknown formatter: %s", formatter); return } // Grab the next item. If it's simple, just append it to the template. // Otherwise return its details. func (t *Template) parseSimple(item []byte) (done bool, tok int, w []string) { tok, w = t.analyze(item); if t.error != nil { return } done = true; // assume for simplicity switch tok { case tokComment: return; case tokText: t.elems.Push(&textElement{item}); return; case tokLiteral: switch w[0] { case ".meta-left": t.elems.Push(&literalElement{t.ldelim}); case ".meta-right": t.elems.Push(&literalElement{t.rdelim}); case ".space": t.elems.Push(&literalElement{space}); case ".tab": t.elems.Push(&literalElement{tab}); default: t.parseError("internal error: unknown literal: %s", w[0]); return; } return; case tokVariable: t.elems.Push(t.newVariable(w[0])); return; } return false, tok, w } // parseRepeated and parseSection are mutually recursive func (t *Template) parseRepeated(words []string) *repeatedElement { r := new(repeatedElement); t.elems.Push(r); r.linenum = t.linenum; r.field = words[2]; // Scan section, collecting true and false (.or) blocks. r.start = t.elems.Len(); r.or = -1; r.altstart = -1; r.altend = -1; Loop: for t.error == nil { item := t.nextItem(); if t.error != nil { break; } if len(item) == 0 { t.parseError("missing .end for .repeated section"); break; } done, tok, w := t.parseSimple(item); if t.error != nil { break; } if done { continue } switch tok { case tokEnd: break Loop; case tokOr: if r.or >= 0 { t.parseError("extra .or in .repeated section"); break Loop; } r.altend = t.elems.Len(); r.or = t.elems.Len(); case tokSection: t.parseSection(w); case tokRepeated: t.parseRepeated(w); case tokAlternates: if r.altstart >= 0 { t.parseError("extra .alternates in .repeated section"); break Loop; } if r.or >= 0 { t.parseError(".alternates inside .or block in .repeated section"); break Loop; } r.altstart = t.elems.Len(); default: t.parseError("internal error: unknown repeated section item: %s", item); break Loop; } } if t.error != nil { return nil } if r.altend < 0 { r.altend = t.elems.Len() } r.end = t.elems.Len(); return r; } func (t *Template) parseSection(words []string) *sectionElement { s := new(sectionElement); t.elems.Push(s); s.linenum = t.linenum; s.field = words[1]; // Scan section, collecting true and false (.or) blocks. s.start = t.elems.Len(); s.or = -1; Loop: for t.error == nil { item := t.nextItem(); if t.error != nil { break; } if len(item) == 0 { t.parseError("missing .end for .section"); break; } done, tok, w := t.parseSimple(item); if t.error != nil { break; } if done { continue } switch tok { case tokEnd: break Loop; case tokOr: if s.or >= 0 { t.parseError("extra .or in .section"); break Loop; } s.or = t.elems.Len(); case tokSection: t.parseSection(w); case tokRepeated: t.parseRepeated(w); case tokAlternates: t.parseError(".alternates not in .repeated"); default: t.parseError("internal error: unknown section item: %s", item); } } if t.error != nil { return nil } s.end = t.elems.Len(); return s; } func (t *Template) parse() { for t.error == nil { item := t.nextItem(); if t.error != nil { break } if len(item) == 0 { break } done, tok, w := t.parseSimple(item); if done { continue } switch tok { case tokOr, tokEnd, tokAlternates: t.parseError("unexpected %s", w[0]); case tokSection: t.parseSection(w); case tokRepeated: t.parseRepeated(w); default: t.parseError("internal error: bad directive in parse: %s", item); } } } // -- Execution // If the data for this template is a struct, find the named variable. // Names of the form a.b.c are walked down the data tree. // The special name "@" (the "cursor") denotes the current data. // The value coming in (st.data) might need indirecting to reach // a struct while the return value is not indirected - that is, // it represents the actual named field. func (st *state) findVar(s string) reflect.Value { if s == "@" { return st.data } data := st.data; elems := strings.Split(s, ".", 0); for i := 0; i < len(elems); i++ { // Look up field; data must be a struct. data = reflect.Indirect(data); if data == nil { return nil } typ, ok := data.Type().(*reflect.StructType); if !ok { return nil } field, ok := typ.FieldByName(elems[i]); if !ok { return nil } data = data.(*reflect.StructValue).FieldByIndex(field.Index); } return data } // Is there no data to look at? func empty(v reflect.Value) bool { v = reflect.Indirect(v); if v == nil { return true } switch v := v.(type) { case *reflect.BoolValue: return v.Get() == false; case *reflect.StringValue: return v.Get() == ""; case *reflect.StructValue: return false; case *reflect.ArrayValue: return v.Len() == 0; case *reflect.SliceValue: return v.Len() == 0; } return true; } // Look up a variable, up through the parent if necessary. func (t *Template) varValue(name string, st *state) reflect.Value { field := st.findVar(name); if field == nil { if st.parent == nil { t.execError(st, t.linenum, "name not found: %s", name) } return t.varValue(name, st.parent); } return field; } // Evaluate a variable, looking up through the parent if necessary. // If it has a formatter attached ({var|formatter}) run that too. func (t *Template) writeVariable(v *variableElement, st *state) { formatter := v.formatter; val := t.varValue(v.name, st).Interface(); // is it in user-supplied map? if t.fmap != nil { if fn, ok := t.fmap[formatter]; ok { fn(st.wr, val, formatter); return; } } // is it in builtin map? if fn, ok := builtins[formatter]; ok { fn(st.wr, val, formatter); return; } t.execError(st, v.linenum, "missing formatter %s for variable %s", formatter, v.name) } // Execute element i. Return next index to execute. func (t *Template) executeElement(i int, st *state) int { switch elem := t.elems.At(i).(type) { case *textElement: st.wr.Write(elem.text); return i+1; case *literalElement: st.wr.Write(elem.text); return i+1; case *variableElement: t.writeVariable(elem, st); return i+1; case *sectionElement: t.executeSection(elem, st); return elem.end; case *repeatedElement: t.executeRepeated(elem, st); return elem.end; } e := t.elems.At(i); t.execError(st, 0, "internal error: bad directive in execute: %v %T\n", reflect.NewValue(e).Interface(), e); return 0 } // Execute the template. func (t *Template) execute(start, end int, st *state) { for i := start; i < end; { i = t.executeElement(i, st) } } // Execute a .section func (t *Template) executeSection(s *sectionElement, st *state) { // Find driver data for this section. It must be in the current struct. field := t.varValue(s.field, st); if field == nil { t.execError(st, s.linenum, ".section: cannot find field %s in %s", s.field, reflect.Indirect(st.data).Type()); } st = st.clone(field); start, end := s.start, s.or; if !empty(field) { // Execute the normal block. if end < 0 { end = s.end } } else { // Execute the .or block. If it's missing, do nothing. start, end = s.or, s.end; if start < 0 { return } } for i := start; i < end; { i = t.executeElement(i, st) } } // Return the result of calling the Iter method on v, or nil. func iter(v reflect.Value) *reflect.ChanValue { for j := 0; j < v.Type().NumMethod(); j++ { mth := v.Type().Method(j); fv := v.Method(j); ft := fv.Type().(*reflect.FuncType); // TODO(rsc): NumIn() should return 0 here, because ft is from a curried FuncValue. if mth.Name != "Iter" || ft.NumIn() != 1 || ft.NumOut() != 1 { continue } ct, ok := ft.Out(0).(*reflect.ChanType); if !ok || ct.Dir() & reflect.RecvDir == 0 { continue } return fv.Call(nil)[0].(*reflect.ChanValue) } return nil } // Execute a .repeated section func (t *Template) executeRepeated(r *repeatedElement, st *state) { // Find driver data for this section. It must be in the current struct. field := t.varValue(r.field, st); if field == nil { t.execError(st, r.linenum, ".repeated: cannot find field %s in %s", r.field, reflect.Indirect(st.data).Type()); } start, end := r.start, r.or; if end < 0 { end = r.end } if r.altstart >= 0 { end = r.altstart } first := true; if array, ok := field.(reflect.ArrayOrSliceValue); ok { for j := 0; j < array.Len(); j++ { newst := st.clone(array.Elem(j)); // .alternates between elements if !first && r.altstart >= 0 { for i := r.altstart; i < r.altend; { i = t.executeElement(i, newst) } } first = false; for i := start; i < end; { i = t.executeElement(i, newst) } } } else if ch := iter(field); ch != nil { for { e := ch.Recv(); if ch.Closed() { break } newst := st.clone(e); // .alternates between elements if !first && r.altstart >= 0 { for i := r.altstart; i < r.altend; { i = t.executeElement(i, newst) } } first = false; for i := start; i < end; { i = t.executeElement(i, newst) } } } else { t.execError(st, r.linenum, ".repeated: cannot repeat %s (type %s)", r.field, field.Type()); } if first { // Empty. Execute the .or block, once. If it's missing, do nothing. start, end := r.or, r.end; if start >= 0 { newst := st.clone(field); for i := start; i < end; { i = t.executeElement(i, newst) } } return } } // A valid delimiter must contain no white space and be non-empty. func validDelim(d []byte) bool { if len(d) == 0 { return false } for _, c := range d { if white(c) { return false } } return true; } // -- Public interface // Parse initializes a Template by parsing its definition. The string // s contains the template text. If any errors occur, Parse returns // the error. func (t *Template) Parse(s string) os.Error { if !validDelim(t.ldelim) || !validDelim(t.rdelim) { return &Error{1, fmt.Sprintf("bad delimiter strings %q %q", t.ldelim, t.rdelim)} } t.buf = strings.Bytes(s); t.p = 0; t.linenum = 0; t.parse(); return t.error; } // Execute applies a parsed template to the specified data object, // generating output to wr. func (t *Template) Execute(data interface{}, wr io.Writer) os.Error { // Extract the driver data. val := reflect.NewValue(data); errors := make(chan os.Error); go func() { t.p = 0; t.execute(0, t.elems.Len(), &state{nil, val, wr, errors}); errors <- nil; // clean return; }(); return <-errors; } // SetDelims sets the left and right delimiters for operations in the // template. They are validated during parsing. They could be // validated here but it's better to keep the routine simple. The // delimiters are very rarely invalid and Parse has the necessary // error-handling interface already. func (t *Template) SetDelims(left, right string) { t.ldelim = strings.Bytes(left); t.rdelim = strings.Bytes(right); } // Parse creates a Template with default parameters (such as {} for // metacharacters). The string s contains the template text while // the formatter map fmap, which may be nil, defines auxiliary functions // for formatting variables. The template is returned. If any errors // occur, err will be non-nil. func Parse(s string, fmap FormatterMap) (t *Template, err os.Error) { t = New(fmap); err = t.Parse(s); if err != nil { t = nil } return } // MustParse is like Parse but panics if the template cannot be parsed. func MustParse(s string, fmap FormatterMap) *Template { t , err := Parse(s, fmap); if err != nil { panic("template parse error: ", err); } return t }
src/pkg/template/template.go
1
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.9962511658668518, 0.011819783598184586, 0.00016380639863200486, 0.00027497613336890936, 0.10377427190542221 ]
{ "id": 2, "code_window": [ "\t}\n", "\tt.buf = strings.Bytes(s);\n", "\tt.p = 0;\n", "\tt.linenum = 0;\n", "\tt.parse();\n", "\treturn t.error;\n", "}\n", "\n", "// Execute applies a parsed template to the specified data object,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tt.linenum = 1;\n" ], "file_path": "src/pkg/template/template.go", "type": "replace", "edit_start_line_idx": 852 }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package os import "syscall" // Time returns the current time, in whole seconds and // fractional nanoseconds, plus an Error if any. The current // time is thus 1e9*sec+nsec, in nanoseconds. The zero of // time is the Unix epoch. func Time() (sec int64, nsec int64, err Error) { var tv syscall.Timeval; if errno := syscall.Gettimeofday(&tv); errno != 0 { return 0, 0, NewSyscallError("gettimeofday", errno); } return int64(tv.Sec), int64(tv.Usec)*1000, err; }
src/pkg/os/time.go
0
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.00018101824389304966, 0.00017552297504153103, 0.00016814196715131402, 0.00017740868497639894, 0.000005423195943876635 ]
{ "id": 2, "code_window": [ "\t}\n", "\tt.buf = strings.Bytes(s);\n", "\tt.p = 0;\n", "\tt.linenum = 0;\n", "\tt.parse();\n", "\treturn t.error;\n", "}\n", "\n", "// Execute applies a parsed template to the specified data object,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tt.linenum = 1;\n" ], "file_path": "src/pkg/template/template.go", "type": "replace", "edit_start_line_idx": 852 }
#SNG: from basn4a16.png IHDR { width: 32; height: 32; bitdepth: 16; using grayscale alpha; } gAMA {1.0000} IMAGE { pixels hex 00000000 10840000 21080000 318c0000 42100000 52940000 63180000 739c0000 84200000 94a40000 a5280000 b5ac0000 c6300000 d6b40000 e7380000 f7bc0000 f7bc0000 e7380000 d6b40000 c6300000 b5ac0000 a5280000 94a40000 84200000 739c0000 63180000 52940000 42100000 318c0000 21080000 10840000 00000000 10840000 00001085 11a71085 234f1085 34f61085 469e1085 58461085 69ed1085 7b951085 8d3d1085 9ee41085 b08c1085 c2341085 d3db1085 e5831085 f72b1085 f72b1085 e5831085 d3db1085 c2341085 b08c1085 9ee41085 8d3d1085 7b951085 69ed1085 58461085 469e1085 34f61085 234f1085 11a71085 00001085 10840000 21080000 11a71085 00002109 12f62109 25ec2109 38e32109 4bd92109 5ed02109 71c62109 84bd2109 97b32109 aaa92109 bda02109 d0962109 e38d2109 f6832109 f6832109 e38d2109 d0962109 bda02109 aaa92109 97b32109 84bd2109 71c62109 5ed02109 4bd92109 38e32109 25ec2109 12f62109 00002109 11a71085 21080000 318c0000 234f1085 12f62109 0000318d 147a318d 28f5318d 3d70318d 51eb318d 6665318d 7ae0318d 8f5b318d a3d6318d b851318d cccb318d e146318d f5c1318d f5c1318d e146318d cccb318d b851318d a3d6318d 8f5b318d 7ae0318d 6665318d 51eb318d 3d70318d 28f5318d 147a318d 0000318d 12f62109 234f1085 318c0000 42100000 34f61085 25ec2109 147a318d 00004211 16424211 2c854211 42c84211 590a4211 6f4d4211 85904211 9bd24211 b2154211 c8584211 de9a4211 f4dd4211 f4dd4211 de9a4211 c8584211 b2154211 9bd24211 85904211 6f4d4211 590a4211 42c84211 2c854211 16424211 00004211 147a318d 25ec2109 34f61085 42100000 52940000 469e1085 38e32109 28f5318d 16424211 00005295 18615295 30c25295 49245295 61855295 79e75295 92485295 aaa95295 c30b5295 db6c5295 f3ce5295 f3ce5295 db6c5295 c30b5295 aaa95295 92485295 79e75295 61855295 49245295 30c25295 18615295 00005295 16424211 28f5318d 38e32109 469e1085 52940000 63180000 58461085 4bd92109 3d70318d 2c854211 18615295 00006319 1af26319 35e46319 50d76319 6bc96319 86bc6319 a1ae6319 bca06319 d7936319 f2856319 f2856319 d7936319 bca06319 a1ae6319 86bc6319 6bc96319 50d76319 35e46319 1af26319 00006319 18615295 2c854211 3d70318d 4bd92109 58461085 63180000 739c0000 69ed1085 5ed02109 51eb318d 42c84211 30c25295 1af26319 0000739d 1e1d739d 3c3b739d 5a59739d 7877739d 9695739d b4b3739d d2d1739d f0ef739d f0ef739d d2d1739d b4b3739d 9695739d 7877739d 5a59739d 3c3b739d 1e1d739d 0000739d 1af26319 30c25295 42c84211 51eb318d 5ed02109 69ed1085 739c0000 84200000 7b951085 71c62109 6665318d 590a4211 49245295 35e46319 1e1d739d 00008421 22218421 44438421 66658421 88878421 aaa98421 cccb8421 eeed8421 eeed8421 cccb8421 aaa98421 88878421 66658421 44438421 22218421 00008421 1e1d739d 35e46319 49245295 590a4211 6665318d 71c62109 7b951085 84200000 94a40000 8d3d1085 84bd2109 7ae0318d 6f4d4211 61855295 50d76319 3c3b739d 22218421 000094a5 276294a5 4ec494a5 762694a5 9d8994a5 c4eb94a5 ec4d94a5 ec4d94a5 c4eb94a5 9d8994a5 762694a5 4ec494a5 276294a5 000094a5 22218421 3c3b739d 50d76319 61855295 6f4d4211 7ae0318d 84bd2109 8d3d1085 94a40000 a5280000 9ee41085 97b32109 8f5b318d 85904211 79e75295 6bc96319 5a59739d 44438421 276294a5 0000a529 2e8ba529 5d16a529 8ba2a529 ba2da529 e8b9a529 e8b9a529 ba2da529 8ba2a529 5d16a529 2e8ba529 0000a529 276294a5 44438421 5a59739d 6bc96319 79e75295 85904211 8f5b318d 97b32109 9ee41085 a5280000 b5ac0000 b08c1085 aaa92109 a3d6318d 9bd24211 92485295 86bc6319 7877739d 66658421 4ec494a5 2e8ba529 0000b5ad 38e3b5ad 71c6b5ad aaa9b5ad e38db5ad e38db5ad aaa9b5ad 71c6b5ad 38e3b5ad 0000b5ad 2e8ba529 4ec494a5 66658421 7877739d 86bc6319 92485295 9bd24211 a3d6318d aaa92109 b08c1085 b5ac0000 c6300000 c2341085 bda02109 b851318d b2154211 aaa95295 a1ae6319 9695739d 88878421 762694a5 5d16a529 38e3b5ad 0000c631 4924c631 9248c631 db6cc631 db6cc631 9248c631 4924c631 0000c631 38e3b5ad 5d16a529 762694a5 88878421 9695739d a1ae6319 aaa95295 b2154211 b851318d bda02109 c2341085 c6300000 d6b40000 d3db1085 d0962109 cccb318d c8584211 c30b5295 bca06319 b4b3739d aaa98421 9d8994a5 8ba2a529 71c6b5ad 4924c631 0000d6b5 6665d6b5 cccbd6b5 cccbd6b5 6665d6b5 0000d6b5 4924c631 71c6b5ad 8ba2a529 9d8994a5 aaa98421 b4b3739d bca06319 c30b5295 c8584211 cccb318d d0962109 d3db1085 d6b40000 e7380000 e5831085 e38d2109 e146318d de9a4211 db6c5295 d7936319 d2d1739d cccb8421 c4eb94a5 ba2da529 aaa9b5ad 9248c631 6665d6b5 0000e739 aaa9e739 aaa9e739 0000e739 6665d6b5 9248c631 aaa9b5ad ba2da529 c4eb94a5 cccb8421 d2d1739d d7936319 db6c5295 de9a4211 e146318d e38d2109 e5831085 e7380000 f7bc0000 f72b1085 f6832109 f5c1318d f4dd4211 f3ce5295 f2856319 f0ef739d eeed8421 ec4d94a5 e8b9a529 e38db5ad db6cc631 cccbd6b5 aaa9e739 0000f7bd 0000f7bd aaa9e739 cccbd6b5 db6cc631 e38db5ad e8b9a529 ec4d94a5 eeed8421 f0ef739d f2856319 f3ce5295 f4dd4211 f5c1318d f6832109 f72b1085 f7bc0000 f7bc0000 f72b1085 f6832109 f5c1318d f4dd4211 f3ce5295 f2856319 f0ef739d eeed8421 ec4d94a5 e8b9a529 e38db5ad db6cc631 cccbd6b5 aaa9e739 0000f7bd 0000f7bd aaa9e739 cccbd6b5 db6cc631 e38db5ad e8b9a529 ec4d94a5 eeed8421 f0ef739d f2856319 f3ce5295 f4dd4211 f5c1318d f6832109 f72b1085 f7bc0000 e7380000 e5831085 e38d2109 e146318d de9a4211 db6c5295 d7936319 d2d1739d cccb8421 c4eb94a5 ba2da529 aaa9b5ad 9248c631 6665d6b5 0000e739 aaa9e739 aaa9e739 0000e739 6665d6b5 9248c631 aaa9b5ad ba2da529 c4eb94a5 cccb8421 d2d1739d d7936319 db6c5295 de9a4211 e146318d e38d2109 e5831085 e7380000 d6b40000 d3db1085 d0962109 cccb318d c8584211 c30b5295 bca06319 b4b3739d aaa98421 9d8994a5 8ba2a529 71c6b5ad 4924c631 0000d6b5 6665d6b5 cccbd6b5 cccbd6b5 6665d6b5 0000d6b5 4924c631 71c6b5ad 8ba2a529 9d8994a5 aaa98421 b4b3739d bca06319 c30b5295 c8584211 cccb318d d0962109 d3db1085 d6b40000 c6300000 c2341085 bda02109 b851318d b2154211 aaa95295 a1ae6319 9695739d 88878421 762694a5 5d16a529 38e3b5ad 0000c631 4924c631 9248c631 db6cc631 db6cc631 9248c631 4924c631 0000c631 38e3b5ad 5d16a529 762694a5 88878421 9695739d a1ae6319 aaa95295 b2154211 b851318d bda02109 c2341085 c6300000 b5ac0000 b08c1085 aaa92109 a3d6318d 9bd24211 92485295 86bc6319 7877739d 66658421 4ec494a5 2e8ba529 0000b5ad 38e3b5ad 71c6b5ad aaa9b5ad e38db5ad e38db5ad aaa9b5ad 71c6b5ad 38e3b5ad 0000b5ad 2e8ba529 4ec494a5 66658421 7877739d 86bc6319 92485295 9bd24211 a3d6318d aaa92109 b08c1085 b5ac0000 a5280000 9ee41085 97b32109 8f5b318d 85904211 79e75295 6bc96319 5a59739d 44438421 276294a5 0000a529 2e8ba529 5d16a529 8ba2a529 ba2da529 e8b9a529 e8b9a529 ba2da529 8ba2a529 5d16a529 2e8ba529 0000a529 276294a5 44438421 5a59739d 6bc96319 79e75295 85904211 8f5b318d 97b32109 9ee41085 a5280000 94a40000 8d3d1085 84bd2109 7ae0318d 6f4d4211 61855295 50d76319 3c3b739d 22218421 000094a5 276294a5 4ec494a5 762694a5 9d8994a5 c4eb94a5 ec4d94a5 ec4d94a5 c4eb94a5 9d8994a5 762694a5 4ec494a5 276294a5 000094a5 22218421 3c3b739d 50d76319 61855295 6f4d4211 7ae0318d 84bd2109 8d3d1085 94a40000 84200000 7b951085 71c62109 6665318d 590a4211 49245295 35e46319 1e1d739d 00008421 22218421 44438421 66658421 88878421 aaa98421 cccb8421 eeed8421 eeed8421 cccb8421 aaa98421 88878421 66658421 44438421 22218421 00008421 1e1d739d 35e46319 49245295 590a4211 6665318d 71c62109 7b951085 84200000 739c0000 69ed1085 5ed02109 51eb318d 42c84211 30c25295 1af26319 0000739d 1e1d739d 3c3b739d 5a59739d 7877739d 9695739d b4b3739d d2d1739d f0ef739d f0ef739d d2d1739d b4b3739d 9695739d 7877739d 5a59739d 3c3b739d 1e1d739d 0000739d 1af26319 30c25295 42c84211 51eb318d 5ed02109 69ed1085 739c0000 63180000 58461085 4bd92109 3d70318d 2c854211 18615295 00006319 1af26319 35e46319 50d76319 6bc96319 86bc6319 a1ae6319 bca06319 d7936319 f2856319 f2856319 d7936319 bca06319 a1ae6319 86bc6319 6bc96319 50d76319 35e46319 1af26319 00006319 18615295 2c854211 3d70318d 4bd92109 58461085 63180000 52940000 469e1085 38e32109 28f5318d 16424211 00005295 18615295 30c25295 49245295 61855295 79e75295 92485295 aaa95295 c30b5295 db6c5295 f3ce5295 f3ce5295 db6c5295 c30b5295 aaa95295 92485295 79e75295 61855295 49245295 30c25295 18615295 00005295 16424211 28f5318d 38e32109 469e1085 52940000 42100000 34f61085 25ec2109 147a318d 00004211 16424211 2c854211 42c84211 590a4211 6f4d4211 85904211 9bd24211 b2154211 c8584211 de9a4211 f4dd4211 f4dd4211 de9a4211 c8584211 b2154211 9bd24211 85904211 6f4d4211 590a4211 42c84211 2c854211 16424211 00004211 147a318d 25ec2109 34f61085 42100000 318c0000 234f1085 12f62109 0000318d 147a318d 28f5318d 3d70318d 51eb318d 6665318d 7ae0318d 8f5b318d a3d6318d b851318d cccb318d e146318d f5c1318d f5c1318d e146318d cccb318d b851318d a3d6318d 8f5b318d 7ae0318d 6665318d 51eb318d 3d70318d 28f5318d 147a318d 0000318d 12f62109 234f1085 318c0000 21080000 11a71085 00002109 12f62109 25ec2109 38e32109 4bd92109 5ed02109 71c62109 84bd2109 97b32109 aaa92109 bda02109 d0962109 e38d2109 f6832109 f6832109 e38d2109 d0962109 bda02109 aaa92109 97b32109 84bd2109 71c62109 5ed02109 4bd92109 38e32109 25ec2109 12f62109 00002109 11a71085 21080000 10840000 00001085 11a71085 234f1085 34f61085 469e1085 58461085 69ed1085 7b951085 8d3d1085 9ee41085 b08c1085 c2341085 d3db1085 e5831085 f72b1085 f72b1085 e5831085 d3db1085 c2341085 b08c1085 9ee41085 8d3d1085 7b951085 69ed1085 58461085 469e1085 34f61085 234f1085 11a71085 00001085 10840000 00000000 10840000 21080000 318c0000 42100000 52940000 63180000 739c0000 84200000 94a40000 a5280000 b5ac0000 c6300000 d6b40000 e7380000 f7bc0000 f7bc0000 e7380000 d6b40000 c6300000 b5ac0000 a5280000 94a40000 84200000 739c0000 63180000 52940000 42100000 318c0000 21080000 10840000 00000000 }
src/pkg/image/png/testdata/pngsuite/basn4a16.sng
0
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.004420826677232981, 0.0022491742856800556, 0.00016300710558425635, 0.003049326129257679, 0.0017547097522765398 ]
{ "id": 2, "code_window": [ "\t}\n", "\tt.buf = strings.Bytes(s);\n", "\tt.p = 0;\n", "\tt.linenum = 0;\n", "\tt.parse();\n", "\treturn t.error;\n", "}\n", "\n", "// Execute applies a parsed template to the specified data object,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tt.linenum = 1;\n" ], "file_path": "src/pkg/template/template.go", "type": "replace", "edit_start_line_idx": 852 }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package math // Pow returns x**y, the base-x exponential of y. func Pow(x, y float64) float64 { // TODO: x or y NaN, ±Inf, maybe ±0. switch { case y == 0: return 1; case y == 1: return x; case x == 0 && y > 0: return 0; case x == 0 && y < 0: return Inf(1); case y == 0.5: return Sqrt(x); case y == -0.5: return 1/Sqrt(x); } absy := y; flip := false; if absy < 0 { absy = -absy; flip = true; } yi, yf := Modf(absy); if yf != 0 && x < 0 { return NaN(); } if yi >= 1<<63 { return Exp(y*Log(x)); } // ans = a1 * 2^ae (= 1 for now). a1 := float64(1); ae := 0; // ans *= x^yf if yf != 0 { if yf > 0.5 { yf--; yi++; } a1 = Exp(yf*Log(x)); } // ans *= x^yi // by multiplying in successive squarings // of x according to bits of yi. // accumulate powers of two into exp. x1, xe := Frexp(x); for i := int64(yi); i != 0; i >>= 1 { if i&1 == 1 { a1 *= x1; ae += xe; } x1 *= x1; xe <<= 1; if x1 < .5 { x1 += x1; xe--; } } // ans = a1*2^ae // if flip { ans = 1 / ans } // but in the opposite order if flip { a1 = 1/a1; ae = -ae; } return Ldexp(a1, ae); }
src/pkg/math/pow.go
0
https://github.com/golang/go/commit/120d0b50c647d13e35f00fbb01de49d1dd0af2fe
[ 0.00018037267727777362, 0.0001779913727659732, 0.00017451870371587574, 0.00017784588271752, 0.0000017941958958545001 ]
{ "id": 0, "code_window": [ " \"@com_github_cockroachdb_redact//:redact\",\n", " \"@com_github_gogo_protobuf//types\",\n", " \"@com_github_jackc_pgx_v4//:pgx\",\n", " \"@com_github_stretchr_testify//require\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"@com_github_jackc_pgx_v5//:pgx\",\n" ], "file_path": "pkg/ccl/testccl/sqlccl/BUILD.bazel", "type": "add", "edit_start_line_idx": 65 }
// Copyright 2022 The Cockroach Authors. // // Licensed as a CockroachDB Enterprise file under the Cockroach Community // License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt package sqlccl import ( "context" gosql "database/sql" "net/url" "testing" "github.com/cockroachdb/cockroach-go/v2/crdb" "github.com/cockroachdb/cockroach/pkg/base" "github.com/cockroachdb/cockroach/pkg/security/username" "github.com/cockroachdb/cockroach/pkg/testutils/serverutils" "github.com/cockroachdb/cockroach/pkg/testutils/sqlutils" "github.com/cockroachdb/cockroach/pkg/util/leaktest" "github.com/stretchr/testify/require" ) func TestShowTransferState(t *testing.T) { defer leaktest.AfterTest(t)() ctx := context.Background() s, mainDB, _ := serverutils.StartServer(t, base.TestServerArgs{ DefaultTestTenant: base.TestControlsTenantsExplicitly, }) defer s.Stopper().Stop(ctx) tenant, tenantDB := serverutils.StartTenant(t, s, base.TestTenantArgs{ TenantID: serverutils.TestTenantID(), }) defer tenant.Stopper().Stop(ctx) _, err := tenantDB.Exec("CREATE USER testuser WITH PASSWORD 'hunter2'") require.NoError(t, err) _, err = mainDB.Exec("ALTER TENANT ALL SET CLUSTER SETTING server.user_login.session_revival_token.enabled = true") require.NoError(t, err) testUserConn := tenant.SQLConnForUser(t, username.TestUser, "") t.Run("without_transfer_key", func(t *testing.T) { conn := testUserConn rows, err := conn.Query("SHOW TRANSFER STATE") require.NoError(t, err, "show transfer state failed") defer rows.Close() resultColumns, err := rows.Columns() require.NoError(t, err) require.Equal(t, []string{ "error", "session_state_base64", "session_revival_token_base64", }, resultColumns) var errVal, sessionState, sessionRevivalToken gosql.NullString rows.Next() err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken) require.NoError(t, err, "unexpected error while reading transfer state") require.Falsef(t, errVal.Valid, "expected null error, got %s", errVal.String) require.True(t, sessionState.Valid) require.True(t, sessionRevivalToken.Valid) }) var state, token string t.Run("with_transfer_key", func(t *testing.T) { pgURL, cleanup := sqlutils.PGUrl( t, tenant.SQLAddr(), "TestShowTransferState-with_transfer_key", url.UserPassword(username.TestUser, "hunter2"), ) defer cleanup() q := pgURL.Query() q.Add("application_name", "carl") pgURL.RawQuery = q.Encode() conn, err := gosql.Open("postgres", pgURL.String()) require.NoError(t, err) defer conn.Close() // Add a prepared statement to make sure SHOW TRANSFER STATE handles it. // Since lib/pq doesn't tell us the name of the prepared statement, we won't // be able to test that we can use it after deserializing the session, but // there are other tests for that. stmt, err := conn.Prepare("SELECT 1 WHERE 1 = 1") require.NoError(t, err) defer stmt.Close() rows, err := conn.Query(`SHOW TRANSFER STATE WITH 'foobar'`) require.NoError(t, err, "show transfer state failed") defer rows.Close() resultColumns, err := rows.Columns() require.NoError(t, err) require.Equal(t, []string{ "error", "session_state_base64", "session_revival_token_base64", "transfer_key", }, resultColumns) var key string var errVal, sessionState, sessionRevivalToken gosql.NullString rows.Next() err = rows.Scan(&errVal, &sessionState, &sessionRevivalToken, &key) require.NoError(t, err, "unexpected error while reading transfer state") require.Equal(t, "foobar", key) require.False(t, errVal.Valid) require.True(t, sessionState.Valid) require.True(t, sessionRevivalToken.Valid) state = sessionState.String token = sessionRevivalToken.String }) t.Run("successful_transfer", func(t *testing.T) { pgURL, cleanup := sqlutils.PGUrl( t, tenant.SQLAddr(), "TestShowTransferState-successful_transfer", url.User(username.TestUser), // Do not use a password here. ) defer cleanup() q := pgURL.Query() q.Add("application_name", "someotherapp") q.Add("crdb:session_revival_token_base64", token) pgURL.RawQuery = q.Encode() conn, err := gosql.Open("postgres", pgURL.String()) require.NoError(t, err) defer conn.Close() var appName string err = conn.QueryRow("SHOW application_name").Scan(&appName) require.NoError(t, err) require.Equal(t, "someotherapp", appName) var b bool err = conn.QueryRow( "SELECT crdb_internal.deserialize_session(decode($1, 'base64'))", state, ).Scan(&b) require.NoError(t, err) require.True(t, b) err = conn.QueryRow("SHOW application_name").Scan(&appName) require.NoError(t, err) require.Equal(t, "carl", appName) }) // Errors should be displayed as a SQL value. t.Run("errors", func(t *testing.T) { t.Run("root_user", func(t *testing.T) { var key string var errVal, sessionState, sessionRevivalToken gosql.NullString err := tenantDB.QueryRow(`SHOW TRANSFER STATE WITH 'bar'`).Scan(&errVal, &sessionState, &sessionRevivalToken, &key) require.NoError(t, err) require.True(t, errVal.Valid) require.Equal(t, "cannot create token for root user", errVal.String) require.False(t, sessionState.Valid) require.False(t, sessionRevivalToken.Valid) }) t.Run("transaction", func(t *testing.T) { conn := testUserConn var errVal, sessionState, sessionRevivalToken gosql.NullString err = crdb.ExecuteTx(ctx, conn, nil /* txopts */, func(tx *gosql.Tx) error { return tx.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken) }) require.NoError(t, err) require.True(t, errVal.Valid) require.Equal(t, "cannot serialize a session which is inside a transaction", errVal.String) require.False(t, sessionState.Valid) require.False(t, sessionRevivalToken.Valid) }) t.Run("temp_tables", func(t *testing.T) { pgURL, cleanup := sqlutils.PGUrl( t, tenant.SQLAddr(), "TestShowTransferState-errors-temp_tables", url.UserPassword(username.TestUser, "hunter2"), ) defer cleanup() q := pgURL.Query() q.Add("experimental_enable_temp_tables", "true") pgURL.RawQuery = q.Encode() conn, err := gosql.Open("postgres", pgURL.String()) require.NoError(t, err) defer conn.Close() _, err = conn.Exec("CREATE TEMP TABLE temp_tbl()") require.NoError(t, err) var errVal, sessionState, sessionRevivalToken gosql.NullString err = conn.QueryRow("SHOW TRANSFER STATE").Scan(&errVal, &sessionState, &sessionRevivalToken) require.NoError(t, err) require.True(t, errVal.Valid) require.Equal(t, "cannot serialize session with temporary schemas", errVal.String) require.False(t, sessionState.Valid) require.False(t, sessionRevivalToken.Valid) }) }) }
pkg/ccl/testccl/sqlccl/show_transfer_state_test.go
1
https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e
[ 0.0004574848571792245, 0.00018901821749750525, 0.00016418201266787946, 0.0001709584321361035, 0.00006519176531583071 ]
{ "id": 0, "code_window": [ " \"@com_github_cockroachdb_redact//:redact\",\n", " \"@com_github_gogo_protobuf//types\",\n", " \"@com_github_jackc_pgx_v4//:pgx\",\n", " \"@com_github_stretchr_testify//require\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"@com_github_jackc_pgx_v5//:pgx\",\n" ], "file_path": "pkg/ccl/testccl/sqlccl/BUILD.bazel", "type": "add", "edit_start_line_idx": 65 }
// Copyright 2022 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package load import "math" // Load represents a named collection of load dimensions. It is used for // performing arithmetic and comparison between comparable objects which have // load. type Load interface { // Dim returns the value of the Dimension given. Dim(dim Dimension) float64 // String returns a string representation of Load. String() string } // Greater returns true if for every dim given in a is greater than the dim in // b element-wise, false otherwise. Unspecified dimensions are ignored. func Greater(a, b Load, dims ...Dimension) bool { for _, dim := range dims { if a.Dim(dim) <= b.Dim(dim) { return false } } return true } // Less returns true if for every dim given in a is less than the dim in b // element-wise, false otherwise. Unspecified dimensions are ignored. func Less(a, b Load, dims ...Dimension) bool { for _, dim := range dims { if a.Dim(dim) >= b.Dim(dim) { return false } } return true } // Sub takes the element-wise subtraction of the calling load with the // other element-wise and returns the result. func Sub(a, b Load) Load { return bimap(a, b, func(ai, bi float64) float64 { return ai - bi }) } // Add takes the element-wise addition of each dimension and returns the // result. func Add(a, b Load) Load { return bimap(a, b, func(ai, bi float64) float64 { return ai + bi }) } // Max takes the element-wise maximum of each dimension and returns the result. func Max(a, b Load) Load { return bimap(a, b, func(ai, bi float64) float64 { return math.Max(ai, bi) }) } // Min takes the element-wise minimum of each dimension and returns the result. func Min(a, b Load) Load { return bimap(a, b, func(ai, bi float64) float64 { return math.Min(ai, bi) }) } // ElementWiseProduct multiplies the calling Load with other and returns // the result. The multiplication is done element-wise: // ElementWiseProduct([a1,a2,a3], [b1,b2,b3]) = [a1*b1,a2*b2,a3*b3] func ElementWiseProduct(a, b Load) Load { return bimap(a, b, func(ai, bi float64) float64 { return ai * bi }) } // Scale applies the factor given against every dimension. func Scale(l Load, factor float64) Load { return nmap(l, func(_ Dimension, li float64) float64 { return li * factor }) } // Set returns a new Load with every dimension equal to the value given. func Set(val float64) Load { l := Vector{} return nmap(l, func(_ Dimension, li float64) float64 { return val }) } func bimap(a, b Load, op func(ai, bi float64) float64) Load { mapped := Vector{} for dim := Dimension(0); dim < Dimension(nDimensions); dim++ { mapped[dim] = op(a.Dim(dim), b.Dim(dim)) } return mapped } func nmap(l Load, op func(d Dimension, li float64) float64) Load { mapped := Vector{} for dim := Dimension(0); dim < Dimension(nDimensions); dim++ { mapped[dim] = op(dim, l.Dim(dim)) } return mapped }
pkg/kv/kvserver/allocator/load/load.go
0
https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e
[ 0.00027412307099439204, 0.00017901243700180203, 0.00016325457545462996, 0.00017019599908962846, 0.000030324579711304978 ]
{ "id": 0, "code_window": [ " \"@com_github_cockroachdb_redact//:redact\",\n", " \"@com_github_gogo_protobuf//types\",\n", " \"@com_github_jackc_pgx_v4//:pgx\",\n", " \"@com_github_stretchr_testify//require\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"@com_github_jackc_pgx_v5//:pgx\",\n" ], "file_path": "pkg/ccl/testccl/sqlccl/BUILD.bazel", "type": "add", "edit_start_line_idx": 65 }
load("@rules_proto//proto:defs.bzl", "proto_library") load("@io_bazel_rules_go//go:def.bzl", "go_library") load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") proto_library( name = "rangelogtestpb_proto", srcs = ["rangelogtest.proto"], strip_import_prefix = "/pkg", visibility = ["//pkg/kv/kvserver/rangelog:__subpackages__"], deps = ["//pkg/kv/kvserver/kvserverpb:kvserverpb_proto"], ) go_proto_library( name = "rangelogtestpb_go_proto", compilers = ["//pkg/cmd/protoc-gen-gogoroach:protoc-gen-gogoroach_compiler"], importpath = "github.com/cockroachdb/cockroach/pkg/kv/kvserver/rangelog/internal/rangelogtestpb", proto = ":rangelogtestpb_proto", visibility = [ "//pkg/gen:__subpackages__", # keep "//pkg/kv/kvserver/rangelog:__subpackages__", ], deps = ["//pkg/kv/kvserver/kvserverpb"], ) go_library( name = "rangelogtestpb", srcs = ["parse.go"], embed = [":rangelogtestpb_go_proto"], importpath = "github.com/cockroachdb/cockroach/pkg/kv/kvserver/rangelog/internal/rangelogtestpb", visibility = ["//pkg/kv/kvserver/rangelog:__subpackages__"], deps = [ "//pkg/kv/kvserver/kvserverpb", "//pkg/roachpb", "//pkg/util/encoding/csv", "@com_github_cockroachdb_errors//:errors", ], )
pkg/kv/kvserver/rangelog/internal/rangelogtestpb/BUILD.bazel
0
https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e
[ 0.007006315980106592, 0.0020820442587137222, 0.00017289470997639, 0.0005744829541072249, 0.0028563153464347124 ]
{ "id": 0, "code_window": [ " \"@com_github_cockroachdb_redact//:redact\",\n", " \"@com_github_gogo_protobuf//types\",\n", " \"@com_github_jackc_pgx_v4//:pgx\",\n", " \"@com_github_stretchr_testify//require\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " \"@com_github_jackc_pgx_v5//:pgx\",\n" ], "file_path": "pkg/ccl/testccl/sqlccl/BUILD.bazel", "type": "add", "edit_start_line_idx": 65 }
Copyright (c) 2015, Gengo, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Gengo, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
licenses/BSD3-grpc-ecosystem.grpc-gateway.txt
0
https://github.com/cockroachdb/cockroach/commit/70adada9f498e7c7a1969765d4504d2ff943bd7e
[ 0.00016942544607445598, 0.00016621935355942696, 0.00016202556435018778, 0.00016720700659789145, 0.0000031006641165731708 ]