filename
stringlengths 4
198
| content
stringlengths 25
939k
| environment
list | variablearg
list | constarg
list | variableargjson
stringclasses 1
value | constargjson
stringlengths 2
3.9k
| lang
stringclasses 3
values | constargcount
float64 0
129
⌀ | variableargcount
float64 0
0
⌀ | sentence
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|
java/src/main/java/orthae/com/github/windowsspeech4j/LibraryLoader.java | package orthae.com.github.windowsspeech4j;
import orthae.com.github.windowsspeech4j.exception.SpeechDriverException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
class LibraryLoader {
public void validateSystemVersion() {
final String systemName = getSystemName();
if (!systemName.contains("Windows 10") && !systemName.contains("Windows 8.1") &&
!systemName.contains("Windows 8") && !systemName.contains("Windows 7") &&
!systemName.contains("Windows Vista")) {
throw new SpeechDriverException(0, "System is not supported");
}
}
public void loadLibrary() throws IOException {
final String libraryName = "WindowsSpeech4J.dll";
final Path libraryPath = getLibraryPath(libraryName);
InputStream stream = getResourceAsStream(libraryName);
deleteExisting(libraryPath);
extractLibrary(libraryPath, stream);
loadLibrary(libraryPath);
}
public Path getLibraryPath(String libraryName) {
return Paths.get(System.getenv("TEMP"), libraryName);
}
public void loadLibrary(Path libraryPath) {
System.load(libraryPath.toAbsolutePath().toString());
}
public void extractLibrary(Path libraryPath, InputStream stream) throws IOException {
Files.copy(stream, libraryPath);
}
public void deleteExisting(Path libraryPath) throws IOException {
Files.deleteIfExists(libraryPath);
}
public String getSystemName() {
return System.getProperty("os.name");
}
public InputStream getResourceAsStream(String libraryName) {
return SpeechClient.class.getResourceAsStream(libraryName);
}
}
| [
"\"TEMP\""
]
| []
| [
"TEMP"
]
| [] | ["TEMP"] | java | 1 | 0 | |
internal/util/paramtable/basetable.go | // Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// 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 paramtable
import (
"fmt"
"os"
"path"
"runtime"
"strconv"
"strings"
"syscall"
"go.uber.org/zap"
memkv "github.com/milvus-io/milvus/internal/kv/mem"
"github.com/milvus-io/milvus/internal/log"
"github.com/milvus-io/milvus/internal/proto/commonpb"
"github.com/milvus-io/milvus/internal/util/typeutil"
"github.com/spf13/cast"
"github.com/spf13/viper"
)
// UniqueID is type alias of typeutil.UniqueID
type UniqueID = typeutil.UniqueID
const envPrefix string = "milvus"
type Base interface {
Load(key string) (string, error)
LoadRange(key, endKey string, limit int) ([]string, []string, error)
LoadYaml(fileName string) error
Remove(key string) error
Save(key, value string) error
Init()
}
type BaseTable struct {
params *memkv.MemoryKV
configDir string
RoleName string
Log log.Config
LogConfigFunction func(log.Config)
}
func (gp *BaseTable) Init() {
gp.params = memkv.NewMemoryKV()
gp.configDir = gp.initConfPath()
log.Debug("config directory", zap.String("configDir", gp.configDir))
gp.loadFromCommonYaml()
gp.loadFromComponentYaml()
gp.loadFromMilvusYaml()
gp.tryloadFromEnv()
gp.InitLogCfg()
}
func (gp *BaseTable) GetConfigDir() string {
return gp.configDir
}
func (gp *BaseTable) LoadFromKVPair(kvPairs []*commonpb.KeyValuePair) error {
for _, pair := range kvPairs {
err := gp.Save(pair.Key, pair.Value)
if err != nil {
return err
}
}
return nil
}
func (gp *BaseTable) initConfPath() string {
// check if user set conf dir through env
configDir, find := syscall.Getenv("MILVUSCONF")
if !find {
runPath, err := os.Getwd()
if err != nil {
panic(err)
}
configDir = runPath + "/configs/"
if _, err := os.Stat(configDir); err != nil {
_, fpath, _, _ := runtime.Caller(0)
// TODO, this is a hack, need to find better solution for relative path
configDir = path.Dir(fpath) + "/../../../configs/"
}
}
return configDir
}
func (gp *BaseTable) loadFromMilvusYaml() {
if err := gp.LoadYaml("milvus.yaml"); err != nil {
panic(err)
}
}
func (gp *BaseTable) loadFromComponentYaml() bool {
configFile := gp.configDir + "advanced/component.yaml"
if _, err := os.Stat(configFile); err == nil {
if err := gp.LoadYaml("advanced/component.yaml"); err != nil {
panic(err)
}
return true
}
return false
}
func (gp *BaseTable) loadFromCommonYaml() bool {
configFile := gp.configDir + "advanced/common.yaml"
if _, err := os.Stat(configFile); err == nil {
if err := gp.LoadYaml("advanced/common.yaml"); err != nil {
panic(err)
}
return true
}
return false
}
func (gp *BaseTable) tryloadFromEnv() {
var err error
minioAddress := os.Getenv("MINIO_ADDRESS")
if minioAddress == "" {
minioHost, err := gp.Load("minio.address")
if err != nil {
panic(err)
}
port, err := gp.Load("minio.port")
if err != nil {
panic(err)
}
minioAddress = minioHost + ":" + port
}
gp.Save("_MinioAddress", minioAddress)
etcdEndpoints := os.Getenv("ETCD_ENDPOINTS")
if etcdEndpoints == "" {
etcdEndpoints, err = gp.Load("etcd.endpoints")
if err != nil {
panic(err)
}
}
gp.Save("_EtcdEndpoints", etcdEndpoints)
pulsarAddress := os.Getenv("PULSAR_ADDRESS")
if pulsarAddress == "" {
pulsarHost, err := gp.Load("pulsar.address")
if err != nil {
panic(err)
}
port, err := gp.Load("pulsar.port")
if err != nil {
panic(err)
}
pulsarAddress = "pulsar://" + pulsarHost + ":" + port
}
gp.Save("_PulsarAddress", pulsarAddress)
rocksmqPath := os.Getenv("ROCKSMQ_PATH")
if rocksmqPath == "" {
path, err := gp.Load("rocksmq.path")
if err != nil {
panic(err)
}
rocksmqPath = path
}
gp.Save("_RocksmqPath", rocksmqPath)
insertBufferFlushSize := os.Getenv("DATA_NODE_IBUFSIZE")
if insertBufferFlushSize == "" {
insertBufferFlushSize = gp.LoadWithDefault("datanode.flush.insertBufSize", "16777216")
}
gp.Save("_DATANODE_INSERTBUFSIZE", insertBufferFlushSize)
minioAccessKey := os.Getenv("MINIO_ACCESS_KEY")
if minioAccessKey == "" {
minioAccessKey, err = gp.Load("minio.accessKeyID")
if err != nil {
panic(err)
}
}
gp.Save("_MinioAccessKeyID", minioAccessKey)
minioSecretKey := os.Getenv("MINIO_SECRET_KEY")
if minioSecretKey == "" {
minioSecretKey, err = gp.Load("minio.secretAccessKey")
if err != nil {
panic(err)
}
}
gp.Save("_MinioSecretAccessKey", minioSecretKey)
minioUseSSL := os.Getenv("MINIO_USE_SSL")
if minioUseSSL == "" {
minioUseSSL, err = gp.Load("minio.useSSL")
if err != nil {
panic(err)
}
}
gp.Save("_MinioUseSSL", minioUseSSL)
minioBucketName := os.Getenv("MINIO_BUCKET_NAME")
if minioBucketName == "" {
minioBucketName, err = gp.Load("minio.bucketName")
if err != nil {
panic(err)
}
}
gp.Save("_MinioBucketName", minioBucketName)
// try to load environment start with ENV_PREFIX
for _, e := range os.Environ() {
parts := strings.SplitN(e, "=", 2)
if strings.Contains(parts[0], envPrefix) {
parts := strings.SplitN(e, "=", 2)
// remove the ENV PREFIX and use the rest as key
keyParts := strings.SplitAfterN(parts[0], ".", 2)
// mem kv throw no errors
gp.Save(keyParts[1], parts[1])
}
}
}
func (gp *BaseTable) Load(key string) (string, error) {
return gp.params.Load(strings.ToLower(key))
}
func (gp *BaseTable) LoadWithDefault(key, defaultValue string) string {
return gp.params.LoadWithDefault(strings.ToLower(key), defaultValue)
}
func (gp *BaseTable) LoadRange(key, endKey string, limit int) ([]string, []string, error) {
return gp.params.LoadRange(strings.ToLower(key), strings.ToLower(endKey), limit)
}
func (gp *BaseTable) LoadYaml(fileName string) error {
config := viper.New()
configFile := gp.configDir + fileName
if _, err := os.Stat(configFile); err != nil {
panic("cannot access config file: " + configFile)
}
config.SetConfigFile(configFile)
if err := config.ReadInConfig(); err != nil {
panic(err)
}
for _, key := range config.AllKeys() {
val := config.Get(key)
str, err := cast.ToStringE(val)
if err != nil {
switch val := val.(type) {
case []interface{}:
str = str[:0]
for _, v := range val {
ss, err := cast.ToStringE(v)
if err != nil {
panic(err)
}
if str == "" {
str = ss
} else {
str = str + "," + ss
}
}
default:
panic("undefined config type, key=" + key)
}
}
err = gp.params.Save(strings.ToLower(key), str)
if err != nil {
panic(err)
}
}
return nil
}
func (gp *BaseTable) Remove(key string) error {
return gp.params.Remove(strings.ToLower(key))
}
func (gp *BaseTable) Save(key, value string) error {
return gp.params.Save(strings.ToLower(key), value)
}
func (gp *BaseTable) ParseBool(key string, defaultValue bool) bool {
valueStr := gp.LoadWithDefault(key, strconv.FormatBool(defaultValue))
value, err := strconv.ParseBool(valueStr)
if err != nil {
panic(err)
}
return value
}
func (gp *BaseTable) ParseFloat(key string) float64 {
valueStr, err := gp.Load(key)
if err != nil {
panic(err)
}
value, err := strconv.ParseFloat(valueStr, 64)
if err != nil {
panic(err)
}
return value
}
func (gp *BaseTable) ParseFloatWithDefault(key string, defaultValue float64) float64 {
valueStr := gp.LoadWithDefault(key, fmt.Sprintf("%f", defaultValue))
value, err := strconv.ParseFloat(valueStr, 64)
if err != nil {
panic(err)
}
return value
}
func (gp *BaseTable) ParseInt64(key string) int64 {
valueStr, err := gp.Load(key)
if err != nil {
panic(err)
}
value, err := strconv.ParseInt(valueStr, 10, 64)
if err != nil {
panic(err)
}
return value
}
func (gp *BaseTable) ParseInt64WithDefault(key string, defaultValue int64) int64 {
valueStr := gp.LoadWithDefault(key, strconv.FormatInt(defaultValue, 10))
value, err := strconv.ParseInt(valueStr, 10, 64)
if err != nil {
panic(err)
}
return value
}
func (gp *BaseTable) ParseInt32(key string) int32 {
valueStr, err := gp.Load(key)
if err != nil {
panic(err)
}
value, err := strconv.ParseInt(valueStr, 10, 32)
if err != nil {
panic(err)
}
return int32(value)
}
func (gp *BaseTable) ParseInt32WithDefault(key string, defaultValue int32) int32 {
valueStr := gp.LoadWithDefault(key, strconv.FormatInt(int64(defaultValue), 10))
value, err := strconv.ParseInt(valueStr, 10, 32)
if err != nil {
panic(err)
}
return int32(value)
}
func (gp *BaseTable) ParseInt(key string) int {
valueStr, err := gp.Load(key)
if err != nil {
panic(err)
}
value, err := strconv.Atoi(valueStr)
if err != nil {
panic(err)
}
return value
}
func (gp *BaseTable) ParseIntWithDefault(key string, defaultValue int) int {
valueStr := gp.LoadWithDefault(key, strconv.FormatInt(int64(defaultValue), 10))
value, err := strconv.Atoi(valueStr)
if err != nil {
panic(err)
}
return value
}
// package methods
func ConvertRangeToIntRange(rangeStr, sep string) []int {
items := strings.Split(rangeStr, sep)
if len(items) != 2 {
panic("Illegal range ")
}
startStr := items[0]
endStr := items[1]
start, err := strconv.Atoi(startStr)
if err != nil {
panic(err)
}
end, err := strconv.Atoi(endStr)
if err != nil {
panic(err)
}
if start < 0 || end < 0 {
panic("Illegal range value")
}
if start > end {
panic("Illegal range value, start > end")
}
return []int{start, end}
}
func ConvertRangeToIntSlice(rangeStr, sep string) []int {
rangeSlice := ConvertRangeToIntRange(rangeStr, sep)
start, end := rangeSlice[0], rangeSlice[1]
var ret []int
for i := start; i < end; i++ {
ret = append(ret, i)
}
return ret
}
func (gp *BaseTable) InitLogCfg() {
gp.Log = log.Config{}
format, err := gp.Load("log.format")
if err != nil {
panic(err)
}
gp.Log.Format = format
level, err := gp.Load("log.level")
if err != nil {
panic(err)
}
gp.Log.Level = level
gp.Log.File.MaxSize = gp.ParseInt("log.file.maxSize")
gp.Log.File.MaxBackups = gp.ParseInt("log.file.maxBackups")
gp.Log.File.MaxDays = gp.ParseInt("log.file.maxAge")
}
func (gp *BaseTable) SetLogConfig(f func(log.Config)) {
gp.LogConfigFunction = f
}
func (gp *BaseTable) SetLogger(id UniqueID) {
rootPath, err := gp.Load("log.file.rootPath")
if err != nil {
panic(err)
}
if rootPath != "" {
log.Debug("Set logger ", zap.Int64("id", id), zap.String("role", gp.RoleName))
if id < 0 {
gp.Log.File.Filename = path.Join(rootPath, gp.RoleName+".log")
} else {
gp.Log.File.Filename = path.Join(rootPath, gp.RoleName+"-"+strconv.FormatInt(id, 10)+".log")
}
} else {
gp.Log.File.Filename = ""
}
if gp.LogConfigFunction != nil {
gp.LogConfigFunction(gp.Log)
}
}
| [
"\"MINIO_ADDRESS\"",
"\"ETCD_ENDPOINTS\"",
"\"PULSAR_ADDRESS\"",
"\"ROCKSMQ_PATH\"",
"\"DATA_NODE_IBUFSIZE\"",
"\"MINIO_ACCESS_KEY\"",
"\"MINIO_SECRET_KEY\"",
"\"MINIO_USE_SSL\"",
"\"MINIO_BUCKET_NAME\""
]
| []
| [
"ROCKSMQ_PATH",
"PULSAR_ADDRESS",
"MINIO_ADDRESS",
"MINIO_USE_SSL",
"MINIO_SECRET_KEY",
"DATA_NODE_IBUFSIZE",
"ETCD_ENDPOINTS",
"MINIO_BUCKET_NAME",
"MINIO_ACCESS_KEY"
]
| [] | ["ROCKSMQ_PATH", "PULSAR_ADDRESS", "MINIO_ADDRESS", "MINIO_USE_SSL", "MINIO_SECRET_KEY", "DATA_NODE_IBUFSIZE", "ETCD_ENDPOINTS", "MINIO_BUCKET_NAME", "MINIO_ACCESS_KEY"] | go | 9 | 0 | |
sc-elasticbeanstalk/application_deployment/create_application_version/app.py | #!/bin/python
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import json
import logging
import os
import re
import boto3 # pylint: disable=import-error
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
eb = None
def lambda_handler(event, context):
global eb
if not eb:
eb = boto3.client('elasticbeanstalk')
logger.info(json.dumps(event))
response = eb.describe_applications(
# ApplicationNames=[event["ApplicationName"]]
ApplicationNames=[os.environ["ApplicationName"]]
)
try:
logger.info(response["Applications"][0]["Versions"])
# Find last version number
version_pattern = re.compile(r'V[0-9]*$')
highest_version_number = -1
for version in response["Applications"][0]["Versions"]:
if version_pattern.match(version):
version_number = int(version_pattern.findall(version)[0][1::])
highest_version_number = max(highest_version_number, version_number)
new_version_label = "V" + str(highest_version_number + 1)
except KeyError:
# No ApplicationVersion present
new_version_label = "V0"
response = eb.create_application_version(
# ApplicationName=event["ApplicationName"],
ApplicationName=os.environ["ApplicationName"],
VersionLabel=new_version_label,
# Description=event["Description"],
# SourceBuildInformation={
# 'SourceType': 'Zip',
# 'SourceRepository': 'S3',
# 'SourceLocation': event["SourceLocation"]
# },
SourceBundle={
'S3Bucket': event["S3Bucket"],
'S3Key': event["S3Key"]
},
# BuildConfiguration={
# 'ArtifactName': 'string',
# 'CodeBuildServiceRole': 'string',
# 'ComputeType': 'BUILD_GENERAL1_SMALL'|'BUILD_GENERAL1_MEDIUM'|'BUILD_GENERAL1_LARGE',
# 'Image': 'string',
# 'TimeoutInMinutes': 123
# },
AutoCreateApplication=True,
Process=True
# Tags=[
# {
# 'Key': 'string',
# 'Value': 'string'
# },
# ]
)
logger.info(response)
# Delete old Application versions - Keep the neweset application versions. The amount of application versions kept is taken from the environment variable RemainingApplicationVersions
describe_response = eb.describe_application_versions(
ApplicationName=os.environ["ApplicationName"]
)
app_versions_list = describe_response["ApplicationVersions"]
for app_version in app_versions_list[int(os.environ["RemainingApplicationVersions"])::]:
if app_version["VersionLabel"] != new_version_label:
delete_response = eb.delete_application_version(
ApplicationName=os.environ["ApplicationName"],
VersionLabel=app_version["VersionLabel"]
)
logger.info(delete_response)
# except Exception as e:
# # Handle exception
# logger.exception("## EXCEPTION")
# logger.exception(e)
# traceback.print_exc()
# print("Unexpected error: %s" % e)
# return {
# "statusCode": 500,
# "body": json.dumps({
# "message": print(e),
# }),
# }
return {
'statusCode': 200,
'VersionLabel': new_version_label,
'body': json.dumps('Lambda done!')
}
| []
| []
| [
"RemainingApplicationVersions",
"ApplicationName"
]
| [] | ["RemainingApplicationVersions", "ApplicationName"] | python | 2 | 0 | |
pkg/hosts/tunnel.go | package hosts
import (
"bytes"
"io"
"os"
"sync"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
)
type Tunnel struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
Writer io.Writer
Modes ssh.TerminalModes
Term string
Height int
Weight int
err error
conn *ssh.Client
cmd *bytes.Buffer
}
func (t *Tunnel) Close() error {
return t.conn.Close()
}
func (t *Tunnel) Cmd(cmd string) *Tunnel {
if t.cmd == nil {
t.cmd = bytes.NewBufferString(cmd + "\n")
return t
}
_, err := t.cmd.WriteString(cmd + "\n")
if err != nil {
t.err = err
}
return t
}
func (t *Tunnel) Terminal() error {
session, err := t.conn.NewSession()
defer func() {
_ = session.Close()
}()
if err != nil {
return err
}
term := os.Getenv("TERM")
if term == "" {
t.Term = "xterm-256color"
}
t.Modes = ssh.TerminalModes{
ssh.ECHO: 1,
ssh.VSTATUS: 1,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
fd := int(os.Stdin.Fd())
oldState, err := terminal.MakeRaw(fd)
defer func() {
_ = terminal.Restore(fd, oldState)
}()
if err != nil {
return err
}
t.Weight, t.Height, err = terminal.GetSize(fd)
if err != nil {
return err
}
session.Stdin = os.Stdin
session.Stdout = os.Stdout
session.Stderr = os.Stderr
if err := session.RequestPty(t.Term, t.Height, t.Weight, t.Modes); err != nil {
return err
}
if err := session.Shell(); err != nil {
return err
}
if err := session.Wait(); err != nil {
return err
}
return nil
}
func (t *Tunnel) Run() error {
if t.err != nil {
return t.err
}
return t.executeCommands()
}
func (t *Tunnel) SetStdio(stdout, stderr io.Writer) *Tunnel {
t.Stdout = stdout
t.Stderr = stderr
return t
}
func (t *Tunnel) executeCommands() error {
for {
cmd, err := t.cmd.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
return err
}
if err := t.executeCommand(cmd); err != nil {
return err
}
}
return nil
}
func (t *Tunnel) executeCommand(cmd string) error {
session, err := t.conn.NewSession()
if err != nil {
return err
}
defer func() {
_ = session.Close()
}()
stdoutPipe, err := session.StdoutPipe()
if err != nil {
return err
}
stderrPipe, err := session.StderrPipe()
if err != nil {
return err
}
var outWriter, errWriter io.Writer
if t.Writer != nil {
outWriter = io.MultiWriter(t.Stdout, t.Writer)
errWriter = io.MultiWriter(t.Stderr, t.Writer)
} else {
outWriter = io.MultiWriter(os.Stdout, t.Stdout)
errWriter = io.MultiWriter(os.Stderr, t.Stderr)
}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
io.Copy(outWriter, stdoutPipe)
wg.Done()
}()
wg.Add(1)
go func() {
io.Copy(errWriter, stderrPipe)
wg.Done()
}()
err = session.Run(cmd)
wg.Wait()
return err
}
func (t *Tunnel) Session() (*ssh.Session, error) {
return t.conn.NewSession()
}
| [
"\"TERM\""
]
| []
| [
"TERM"
]
| [] | ["TERM"] | go | 1 | 0 | |
pkg/cortex/serve/cortex_internal/lib/model/tree.py | # Copyright 2021 Cortex Labs, Inc.
#
# 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.
import os
import itertools
import time
import datetime
import shutil
import threading as td
from typing import List, Dict, Any, Tuple, Callable, AbstractSet
from cortex_internal.lib import util
from cortex_internal.lib.type import PredictorType
from cortex_internal.lib.concurrency import ReadWriteLock
from cortex_internal.lib.exceptions import CortexException, WithBreak
from cortex_internal.lib.storage import S3, GCS
from cortex_internal.lib.model.validation import (
validate_models_dir_paths,
validate_model_paths,
ModelVersion,
)
from cortex_internal.lib.log import configure_logger
logger = configure_logger("cortex", os.environ["CORTEX_LOG_CONFIG_FILE"])
class ModelsTree:
"""
Model tree for cloud-provided models.
"""
def __init__(self):
self.models = {}
self._locks = {}
self._create_lock = td.RLock()
self._removable = set()
def acquire(self, mode: str, model_name: str, model_version: str) -> None:
"""
Acquire shared/exclusive (R/W) access for a specific model. Use this when multiple threads are used.
Args:
mode: "r" for read lock, "w" for write lock.
model_name: The name of the model.
model_version: The version of the model.
"""
model_id = f"{model_name}-{model_version}"
if not model_id in self._locks:
lock = ReadWriteLock()
self._create_lock.acquire()
if model_id not in self._locks:
self._locks[model_id] = lock
self._create_lock.release()
self._locks[model_id].acquire(mode)
def release(self, mode: str, model_name: str, model_version: str) -> None:
"""
Release shared/exclusive (R/W) access for a specific model. Use this when multiple threads are used.
Args:
mode: "r" for read lock, "w" for write lock.
model_name: The name of the model.
model_version: The version of the model.
"""
model_id = f"{model_name}-{model_version}"
self._locks[model_id].release(mode)
def update_models(
self,
model_names: List[str],
model_versions: Dict[str, List[str]],
model_paths: List[str],
sub_paths: List[List[str]],
timestamps: List[List[datetime.datetime]],
bucket_providers: List[str],
bucket_names: List[str],
) -> Tuple[AbstractSet[str], AbstractSet[str]]:
"""
Updates the model tree with the latest from the upstream and removes stale models.
Locking is not required. Locking is already done within the method.
Args:
model_names: The unique names of the models as discovered in models:dir or specified in models:paths.
model_versions: The detected versions of each model. If the list is empty, then version "1" should be assumed. The dictionary keys represent the models' names.
model_paths: Cloud model paths to each model.
sub_paths: A list of filepaths lists for each file of each model.
timestamps: When was each versioned model updated the last time on the upstream. When no versions are passed, a timestamp is still expected.
bucket_providers: A list with the bucket providers for each model ("s3" or "gs"). Empty elements if none are used.
bucket_names: A list with the bucket_names required for each model. Empty elements if no bucket is used.
Returns:
The loaded model IDs ("<model-name>-<model-version") that haven't been found in the passed parameters.
Which model IDs have been updated. If these model IDs are in memory or on disk already, then they should get updated as well.
Also sets an info attribute which might look like this:
{
"<model-name>": ,
}
And where "versions" represents the available versions of a model <model-name> and each "timestamps" element is the corresponding
last-edit time of each versioned model.
"""
current_model_ids = set()
updated_model_ids = set()
for idx in range(len(model_names)):
model_name = model_names[idx]
if len(model_versions[model_name]) == 0:
model_id = f"{model_name}-1"
with LockedModelsTree(self, "w", model_name, "1"):
updated = self.update_model(
bucket_providers[idx],
bucket_names[idx],
model_name,
"1",
model_paths[idx],
sub_paths[idx],
timestamps[idx][0],
True,
)
current_model_ids.add(model_id)
if updated:
updated_model_ids.add(model_id)
for v_idx, model_version in enumerate(model_versions[model_name]):
model_id = f"{model_name}-{model_version}"
with LockedModelsTree(self, "w", model_name, model_version):
updated = self.update_model(
bucket_providers[idx],
bucket_names[idx],
model_name,
model_version,
os.path.join(model_paths[idx], model_version) + "/",
sub_paths[idx],
timestamps[idx][v_idx],
True,
)
current_model_ids.add(model_id)
if updated:
updated_model_ids.add(model_id)
old_model_ids = set(self.models.keys()) - current_model_ids
for old_model_id in old_model_ids:
model_name, model_version = old_model_id.rsplit("-", maxsplit=1)
if old_model_id not in self._removable:
continue
with LockedModelsTree(self, "w", model_name, model_version):
del self.models[old_model_id]
self._removable = self._removable - set([old_model_id])
return old_model_ids, updated_model_ids
def update_model(
self,
provider: str,
bucket: str,
model_name: str,
model_version: str,
model_path: str,
sub_paths: List[str],
timestamp: datetime.datetime,
removable: bool,
) -> None:
"""
Updates the model tree with the given model.
Locking is required.
Args:
provider: The bucket provider for the model ("s3" or "gs"). Empty if no bucket was used.
bucket: The cloud bucket on which the model is stored. Empty if there's no bucket.
model_name: The unique name of the model as discovered in models:dir or specified in models:paths.
model_version: A detected version of the model.
model_path: The model path to the versioned model.
sub_paths: A list of filepaths for each file of the model.
timestamp: When was the model path updated the last time.
removable: If update_models method is allowed to remove the model.
Returns:
True if the model wasn't in the tree or if the timestamp is newer. False otherwise.
"""
model_id = f"{model_name}-{model_version}"
has_changed = False
if model_id not in self.models:
has_changed = True
elif self.models[model_id]["timestamp"] < timestamp:
has_changed = True
if has_changed or model_id in self.models:
self.models[model_id] = {
"provider": provider,
"bucket": bucket,
"path": model_path,
"sub_paths": sub_paths,
"timestamp": timestamp,
}
if removable:
self._removable.add(model_id)
else:
self._removable = self._removable - set([model_id])
return has_changed
def model_info(self, model_name: str) -> dict:
"""
Gets model info about the available versions and model timestamps.
Locking is not required.
Returns:
A dict with keys "bucket", "model_paths, "versions" and "timestamps".
"model_paths" contains the cloud prefixes of each versioned model, "versions" represents the available versions of the model,
and each "timestamps" element is the corresponding last-edit time of each versioned model.
Empty lists are returned if the model is not found.
Example of returned dictionary for model_name.
```json
{
"provider": "s3",
"bucket": "bucket-0",
"model_paths": ["modelA/1", "modelA/4", "modelA/7", ...],
"versions": [1,4,7, ...],
"timestamps": [12884999, 12874449, 12344931, ...]
}
```
"""
info = {
"model_paths": [],
"versions": [],
"timestamps": [],
}
# to ensure atomicity
models = self.models.copy()
for model_id in models:
_model_name, model_version = model_id.rsplit("-", maxsplit=1)
if _model_name == model_name:
if "provider" not in info:
info["provider"] = models[model_id]["provider"]
if "bucket" not in info:
info["bucket"] = models[model_id]["bucket"]
info["model_paths"] += [os.path.join(models[model_id]["path"], model_version)]
info["versions"] += [model_version]
info["timestamps"] += [models[model_id]["timestamp"]]
return info
def get_model_names(self) -> List[str]:
"""
Gets the available model names.
Locking is not required.
Returns:
List of all model names.
"""
model_names = set()
# to ensure atomicity
models = self.models.copy()
for model_id in models:
model_name = model_id.rsplit("-", maxsplit=1)[0]
model_names.add(model_name)
return list(model_names)
def get_all_models_info(self) -> dict:
"""
Gets model info about the available versions and model timestamps.
Locking is not required.
It's like model_info method, but for all model names.
Example of returned dictionary.
```json
{
...
"modelA": {
"provider": "s3",
"bucket": "bucket-0",
"model_paths": ["modelA/1", "modelA/4", "modelA/7", ...],
"versions": ["1","4","7", ...],
"timestamps": [12884999, 12874449, 12344931, ...]
}
...
}
```
"""
models_info = {}
# to ensure atomicity
models = self.models.copy()
# extract model names
model_names = set()
for model_id in models:
model_name = model_id.rsplit("-", maxsplit=1)[0]
model_names.add(model_name)
model_names = list(model_names)
# build models info dictionary
for model_name in model_names:
model_info = {
"model_paths": [],
"versions": [],
"timestamps": [],
}
for model_id in models:
_model_name, model_version = model_id.rsplit("-", maxsplit=1)
if _model_name == model_name:
if "provider" not in model_info:
model_info["provider"] = models[model_id]["provider"]
if "bucket" not in model_info:
model_info["bucket"] = models[model_id]["bucket"]
model_info["model_paths"] += [
os.path.join(models[model_id]["path"], model_version)
]
model_info["versions"] += [model_version]
model_info["timestamps"] += [int(models[model_id]["timestamp"].timestamp())]
models_info[model_name] = model_info
return models_info
def __getitem__(self, model_id: str) -> dict:
"""
Each value of a key (model ID) is a dictionary with the following format:
{
"provider": <provider-of-the-bucket>,
"bucket": <bucket-of-the-model>,
"path": <path-of-the-model>,
"sub_paths": <sub-path-of-each-file-of-the-model>,
"timestamp": <when-was-the-model-last-modified>
}
Locking is required.
"""
return self.models[model_id].copy()
def __contains__(self, model_id: str) -> bool:
"""
Each value of a key (model ID) is a dictionary with the following format:
{
"provider": <provider-of-the-bucket>,
"bucket": <bucket-of-the-model>,
"path": <path-of-the-model>,
"sub_paths": <sub-path-of-each-file-of-the-model>,
"timestamp": <when-was-the-model-last-modified>
}
Locking is required.
"""
return model_id in self.models
class LockedModelsTree:
"""
When acquiring shared/exclusive (R/W) access to a model resource (model name + version).
Locks just for a specific model. Apply read lock when granting shared access or write lock when it's exclusive access (for adding/removing operations).
The context manager can be exited by raising cortex_internal.lib.exceptions.WithBreak.
"""
def __init__(self, tree: ModelsTree, mode: str, model_name: str, model_version: str):
"""
mode can be "r" for read or "w" for write.
"""
self._tree = tree
self._mode = mode
self._model_name = model_name
self._model_version = model_version
def __enter__(self):
self._tree.acquire(self._mode, self._model_name, self._model_version)
return self
def __exit__(self, exc_type, exc_value, traceback) -> bool:
self._tree.release(self._mode, self._model_name, self._model_version)
if exc_value is not None and exc_type is not WithBreak:
return False
return True
def find_all_cloud_models(
is_dir_used: bool,
models_dir: str,
predictor_type: PredictorType,
cloud_paths: List[str],
cloud_model_names: List[str],
) -> Tuple[
List[str],
Dict[str, List[str]],
List[str],
List[List[str]],
List[List[datetime.datetime]],
List[str],
List[str],
]:
"""
Get updated information on all models that are currently present on the cloud upstreams.
Information on the available models, versions, last edit times, the subpaths of each model, and so on.
Args:
is_dir_used: Whether predictor:models:dir is used or not.
models_dir: The value of predictor:models:dir in case it's present. Ignored when not required.
predictor_type: The predictor type.
cloud_paths: The cloud model paths as they are specified in predictor:models:path/predictor:models:paths/predictor:models:dir is used. Ignored when not required.
cloud_model_names: The cloud model names as they are specified in predictor:models:paths:name when predictor:models:paths is used or the default name of the model when predictor:models:path is used. Ignored when not required.
Returns: The tuple with the following elements:
model_names - a list with the names of the models (i.e. bert, gpt-2, etc) and they are unique
versions - a dictionary with the keys representing the model names and the values being lists of versions that each model has.
For non-versioned model paths ModelVersion.NOT_PROVIDED, the list will be empty.
model_paths - a list with the prefix of each model.
sub_paths - a list of filepaths lists for each file of each model.
timestamps - a list of timestamps lists representing the last edit time of each versioned model.
bucket_providers - a list of the bucket providers for each model. Can be "s3" or "gs".
bucket_names - a list of the bucket names of each model.
"""
# validate models stored in cloud (S3 or GS) that were specified with predictor:models:dir field
if is_dir_used:
if S3.is_valid_s3_path(models_dir):
bucket_name, models_path = S3.deconstruct_s3_path(models_dir)
client = S3(bucket_name)
if GCS.is_valid_gcs_path(models_dir):
bucket_name, models_path = GCS.deconstruct_gcs_path(models_dir)
client = GCS(bucket_name)
sub_paths, timestamps = client.search(models_path)
model_paths, ooa_ids = validate_models_dir_paths(sub_paths, predictor_type, models_path)
model_names = [os.path.basename(model_path) for model_path in model_paths]
model_paths = [
model_path for model_path in model_paths if os.path.basename(model_path) in model_names
]
model_paths = [
model_path + "/" * (not model_path.endswith("/")) for model_path in model_paths
]
if S3.is_valid_s3_path(models_dir):
bucket_providers = len(model_paths) * ["s3"]
if GCS.is_valid_gcs_path(models_dir):
bucket_providers = len(model_paths) * ["gs"]
bucket_names = len(model_paths) * [bucket_name]
sub_paths = len(model_paths) * [sub_paths]
timestamps = len(model_paths) * [timestamps]
# validate models stored in cloud (S3 or GS) that were specified with predictor:models:paths field
if not is_dir_used:
sub_paths = []
ooa_ids = []
model_paths = []
model_names = []
timestamps = []
bucket_providers = []
bucket_names = []
for idx, path in enumerate(cloud_paths):
if S3.is_valid_s3_path(path):
bucket_name, model_path = S3.deconstruct_s3_path(path)
client = S3(bucket_name)
elif GCS.is_valid_gcs_path(path):
bucket_name, model_path = GCS.deconstruct_gcs_path(path)
client = GCS(bucket_name)
else:
continue
sb, model_path_ts = client.search(model_path)
try:
ooa_ids.append(validate_model_paths(sb, predictor_type, model_path))
except CortexException:
continue
model_paths.append(model_path)
model_names.append(cloud_model_names[idx])
bucket_names.append(bucket_name)
sub_paths += [sb]
timestamps += [model_path_ts]
if S3.is_valid_s3_path(path):
bucket_providers.append("s3")
if GCS.is_valid_gcs_path(path):
bucket_providers.append("gs")
# determine the detected versions for each cloud model
# if the model was not versioned, then leave the version list empty
versions = {}
for model_path, model_name, model_ooa_ids, bucket_sub_paths in zip(
model_paths, model_names, ooa_ids, sub_paths
):
if ModelVersion.PROVIDED not in model_ooa_ids:
versions[model_name] = []
continue
model_sub_paths = [os.path.relpath(sub_path, model_path) for sub_path in bucket_sub_paths]
model_versions_paths = [path for path in model_sub_paths if not path.startswith("../")]
model_versions = [
util.get_leftmost_part_of_path(model_version_path)
for model_version_path in model_versions_paths
]
model_versions = list(set(model_versions))
versions[model_name] = model_versions
# pick up the max timestamp for each versioned model
aux_timestamps = []
for model_path, model_name, bucket_sub_paths, sub_path_timestamps in zip(
model_paths, model_names, sub_paths, timestamps
):
model_ts = []
if len(versions[model_name]) == 0:
masks = list(
map(
lambda x: x.startswith(model_path + "/" * (model_path[-1] != "/")),
bucket_sub_paths,
)
)
model_ts = [max(itertools.compress(sub_path_timestamps, masks))]
for version in versions[model_name]:
masks = list(
map(
lambda x: x.startswith(os.path.join(model_path, version) + "/"),
bucket_sub_paths,
)
)
model_ts.append(max(itertools.compress(sub_path_timestamps, masks)))
aux_timestamps.append(model_ts)
timestamps = aux_timestamps # type: List[List[datetime.datetime]]
# model_names - a list with the names of the models (i.e. bert, gpt-2, etc) and they are unique
# versions - a dictionary with the keys representing the model names and the values being lists of versions that each model has.
# For non-versioned model paths ModelVersion.NOT_PROVIDED, the list will be empty
# model_paths - a list with the prefix of each model
# sub_paths - a list of filepaths lists for each file of each model
# timestamps - a list of timestamps lists representing the last edit time of each versioned model
# bucket_providers - bucket providers
# bucket_names - names of the buckets
return model_names, versions, model_paths, sub_paths, timestamps, bucket_providers, bucket_names
| []
| []
| [
"CORTEX_LOG_CONFIG_FILE"
]
| [] | ["CORTEX_LOG_CONFIG_FILE"] | python | 1 | 0 | |
provisioning-service/info/info.go | package info
import (
"fmt"
"net"
"os"
"path"
"runtime"
"strconv"
"strings"
"time"
log "github.com/cihub/seelog"
sigar "github.com/cloudfoundry/gosigar"
"github.com/hailo-platform/H2O/platform/client"
"github.com/hailo-platform/H2O/platform/server"
"github.com/hailo-platform/H2O/platform/util"
"github.com/hailo-platform/H2O/protobuf/proto"
"github.com/hailo-platform/H2O/provisioning-service/dao"
iproto "github.com/hailo-platform/H2O/provisioning-service/proto"
)
const (
updateInterval = time.Second * 20
)
var (
hostname string
azName string
machineClass string
version string
ipAddress string
started uint64
numCpu uint64
cpuSample *sigar.Cpu
procSample map[string]*proc
)
func init() {
hostname, _ = os.Hostname()
azName, _ = util.GetAwsAZName()
machineClass = os.Getenv("H2O_MACHINE_CLASS")
if len(machineClass) == 0 {
machineClass = "default"
}
iface := "eth0"
switch runtime.GOOS {
case "darwin":
iface = "en1"
}
ipAddress = GetIpAddress(iface)
started = uint64(time.Now().Unix())
numCpu = uint64(runtime.NumCPU())
cpuSample, _ = getCpu()
procSample, _ = getProcUsage()
}
func GetIpAddress(iface string) string {
var ipAddress string
i, _ := net.InterfaceByName(iface)
addrs, _ := i.Addrs()
for _, addr := range addrs {
if strings.Contains(addr.String(), ":") {
continue
}
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
ipAddress = ip.String()
break
}
return ipAddress
}
func getMachineInfo(cpu sigar.Cpu) (*iproto.Machine, error) {
cpuUsed := getCpuUsage(cpu)
memory, _ := getMemory()
disk, _ := getDisk()
return &iproto.Machine{
Cores: proto.Uint64(numCpu),
Memory: proto.Uint64(memory.Total),
Disk: proto.Uint64(disk.Total),
Usage: &iproto.Resource{
Cpu: proto.Float64(cpuUsed),
Memory: proto.Uint64(memory.ActualUsed),
Disk: proto.Uint64(disk.Used),
},
}, nil
}
func getNameVersion(process string) (string, string) {
_, p := path.Split(process)
last := strings.LastIndex(p, "-")
if last == -1 {
return p, ""
}
return p[:last], p[last+1:]
}
func getServices(cpu sigar.Cpu) (map[string][]*iproto.Service, error) {
procs, err := getProcUsage()
if err != nil {
return nil, err
}
types := make(map[string]dao.ServiceType)
processes := make(map[string][]*iproto.Service)
services, _ := dao.CachedServices(machineClass)
for _, service := range services {
key := fmt.Sprintf("%s-%d", service.ServiceName, service.ServiceVersion)
types[key] = service.ServiceType
}
for proc, u := range procs {
usage := &iproto.Resource{}
if ou, ok := procSample[proc]; ok {
usage.Cpu = proto.Float64(getProcCpuUsage(*u.cpu, *ou.cpu, cpu.Total()))
}
usage.Memory = proto.Uint64(u.mem.Resident)
name, version := getNameVersion(proc)
process := &iproto.Service{
Name: proto.String(name),
Version: proto.String(version),
Usage: usage,
}
var typ string
key := fmt.Sprintf("%s-%s", name, version)
switch types[key] {
case dao.ServiceTypeContainer:
typ = "container"
default:
typ = "process"
}
processes[typ] = append(processes[typ], process)
}
procSample = procs
return processes, nil
}
func pubInfo() error {
cpu, _ := getCpu()
delta := (*cpu).Delta(*cpuSample)
cpuSample = cpu
services, _ := getServices(delta)
machineInfo, _ := getMachineInfo(delta)
return client.Pub("com.hailocab.kernel.provisioning.info", &iproto.Info{
Id: proto.String(server.InstanceID),
Version: proto.String(version),
Hostname: proto.String(hostname),
IpAddress: proto.String(ipAddress),
AzName: proto.String(azName),
MachineClass: proto.String(machineClass),
Started: proto.Uint64(started),
Timestamp: proto.Uint64(uint64(time.Now().Unix())),
Machine: machineInfo,
Processes: services["process"],
Containers: services["container"],
})
}
func run() {
version = strconv.FormatUint(server.Version, 10)
ticker := time.NewTicker(updateInterval)
for {
select {
case <-ticker.C:
if err := pubInfo(); err != nil {
log.Errorf("Error publishing info: %v", err)
}
}
}
}
func Run() {
go run()
}
| [
"\"H2O_MACHINE_CLASS\""
]
| []
| [
"H2O_MACHINE_CLASS"
]
| [] | ["H2O_MACHINE_CLASS"] | go | 1 | 0 | |
resource/template/template_funcs.go | package template
import (
"encoding/json"
"os"
"path"
"strings"
"time"
)
func newFuncMap() map[string]interface{} {
m := make(map[string]interface{})
m["base"] = path.Base
m["split"] = strings.Split
m["json"] = UnmarshalJsonObject
m["jsonArray"] = UnmarshalJsonArray
m["dir"] = path.Dir
m["getenv"] = os.Getenv
m["join"] = strings.Join
m["datetime"] = time.Now
m["toUpper"] = strings.ToUpper
m["toLower"] = strings.ToLower
return m
}
func addFuncs(out, in map[string]interface{}) {
for name, fn := range in {
out[name] = fn
}
}
func UnmarshalJsonObject(data string) (map[string]interface{}, error) {
var ret map[string]interface{}
err := json.Unmarshal([]byte(data), &ret)
return ret, err
}
func UnmarshalJsonArray(data string) ([]interface{}, error) {
var ret []interface{}
err := json.Unmarshal([]byte(data), &ret)
return ret, err
}
| []
| []
| []
| [] | [] | go | 0 | 0 | |
plugins/debug/main.py | #!/usr/bin/env python3
import os
from acquisition import AcquisitionArchiveStep
class DebugMainStep(AcquisitionArchiveStep):
plugin_name = "debug"
_shadow = True
def init(self):
module_runtime_home = os.environ.get('MODULE_RUNTIME_HOME', '/tmp')
self.args.dest_dir = os.path.join(module_runtime_home, 'var',
'debug')
self.args.strftime_template = \
"{ORIGINAL_DIRNAME}/{ORIGINAL_BASENAME}" \
"/{ORIGINAL_UID}_{STEP_COUNTER}_%H%M%S_{RANDOM_ID}"
AcquisitionArchiveStep.init(self)
if __name__ == "__main__":
x = DebugMainStep()
x.run()
| []
| []
| [
"MODULE_RUNTIME_HOME"
]
| [] | ["MODULE_RUNTIME_HOME"] | python | 1 | 0 | |
compute/compute_test.go | // Copyright (c) Microsoft and contributors. All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package compute
import (
"context"
"flag"
"fmt"
"log"
"os"
"strings"
"testing"
"github.com/marstr/randname"
"github.com/Azure-Samples/azure-sdk-for-go-samples/internal/config"
"github.com/Azure-Samples/azure-sdk-for-go-samples/resources"
)
var (
// names used in tests
username = "gosdkuser"
password = "gosdkuserpass!1"
vmName = generateName("gosdk-vm1")
vmssName = generateName("gosdk-vmss1")
diskName = generateName("gosdk-disk1")
nicName = generateName("gosdk-nic1")
virtualNetworkName = generateName("gosdk-vnet1")
subnet1Name = generateName("gosdk-subnet1")
subnet2Name = generateName("gosdk-subnet2")
nsgName = generateName("gosdk-nsg1")
ipName = generateName("gosdk-ip1")
lbName = generateName("gosdk-lb1")
sshPublicKeyPath = os.Getenv("HOME") + "/.ssh/id_rsa.pub"
containerGroupName string = randname.GenerateWithPrefix("gosdk-aci-", 10)
aksClusterName string = randname.GenerateWithPrefix("gosdk-aks-", 10)
aksUsername string = "azureuser"
aksSSHPublicKeyPath string = os.Getenv("HOME") + "/.ssh/id_rsa.pub"
aksAgentPoolCount int32 = 4
)
func addLocalEnvAndParse() error {
// parse env at top-level (also controls dotenv load)
err := config.ParseEnvironment()
if err != nil {
return fmt.Errorf("failed to add top-level env: %v\n", err.Error())
}
// add local env
vnetNameFromEnv := os.Getenv("AZURE_VNET_NAME")
if len(vnetNameFromEnv) > 0 {
virtualNetworkName = vnetNameFromEnv
}
return nil
}
func addLocalFlagsAndParse() error {
// add top-level flags
err := config.AddFlags()
if err != nil {
return fmt.Errorf("failed to add top-level flags: %v\n", err.Error())
}
// add local flags
// flag.StringVar(
// &testVnetName, "testVnetName", testVnetName,
// "Name for test Vnet.")
// parse all flags
flag.Parse()
return nil
}
func setup() error {
var err error
err = addLocalEnvAndParse()
if err != nil {
return err
}
err = addLocalFlagsAndParse()
if err != nil {
return err
}
return nil
}
func teardown() error {
if config.KeepResources() == false {
// does not wait
_, err := resources.DeleteGroup(context.Background(), config.GroupName())
if err != nil {
return err
}
}
return nil
}
// test helpers
func generateName(prefix string) string {
return strings.ToLower(randname.GenerateWithPrefix(prefix, 5))
}
// TestMain sets up the environment and initiates tests.
func TestMain(m *testing.M) {
var err error
var code int
err = setup()
if err != nil {
log.Fatalf("could not set up environment: %v\n", err)
}
code = m.Run()
err = teardown()
if err != nil {
log.Fatalf(
"could not tear down environment: %v\n; original exit code: %v\n",
err, code)
}
os.Exit(code)
}
| [
"\"HOME\"",
"\"HOME\"",
"\"AZURE_VNET_NAME\""
]
| []
| [
"AZURE_VNET_NAME",
"HOME"
]
| [] | ["AZURE_VNET_NAME", "HOME"] | go | 2 | 0 | |
examples/titanic_multi_files/script/random_forest.py | import os
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from titanic_multi_files import io, util
from pathlib import Path
train, test = io.load_dataset()
data = util.merge_dataset(train, test)
data["Sex"].replace(["male", "female"], [0, 1], inplace=True)
data["Embarked"].replace(["C", "Q", "S", None], [0, 1, 2, 3], inplace=True)
data["Fare"].fillna(np.mean(data["Fare"]), inplace=True)
data["Age"].fillna(np.mean(data["Age"]), inplace=True)
train, test = util.split_dataset(data)
feature_columns = [
"Pclass",
"Embarked",
"Fare",
"Parch",
"SibSp",
"Age",
"Sex",
]
x_train = train[feature_columns].values
y_train = train["Survived"].values
x_test = test[feature_columns].values
max_depth = int(os.environ.get("RF_MAX_DEPTH", 2))
crf = RandomForestClassifier(max_depth=max_depth, random_state=0)
crf.fit(x_train, y_train)
y_pred = crf.predict(x_test)
sub = io.load_submission()
sub["Survived"] = y_pred.astype(np.int32)
io.save_submission(sub)
| []
| []
| [
"RF_MAX_DEPTH"
]
| [] | ["RF_MAX_DEPTH"] | python | 1 | 0 | |
examples/service/conversations/role/delete/role_delete_example.go | package main
import (
"log"
"os"
"github.com/RJPearson94/twilio-sdk-go"
v1 "github.com/RJPearson94/twilio-sdk-go/service/conversations/v1"
"github.com/RJPearson94/twilio-sdk-go/session/credentials"
)
var conversationClient *v1.Conversations
func init() {
creds, err := credentials.New(credentials.Account{
Sid: os.Getenv("TWILIO_ACCOUNT_SID"),
AuthToken: os.Getenv("TWILIO_AUTH_TOKEN"),
})
if err != nil {
log.Panicf("%s", err.Error())
}
conversationClient = twilio.NewWithCredentials(creds).Conversations.V1
}
func main() {
err := conversationClient.
Role("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").
Delete()
if err != nil {
log.Panicf("%s", err.Error())
}
log.Printf("Role successfully deleted")
}
| [
"\"TWILIO_ACCOUNT_SID\"",
"\"TWILIO_AUTH_TOKEN\""
]
| []
| [
"TWILIO_AUTH_TOKEN",
"TWILIO_ACCOUNT_SID"
]
| [] | ["TWILIO_AUTH_TOKEN", "TWILIO_ACCOUNT_SID"] | go | 2 | 0 | |
src/coreclr/scripts/superpmi_asmdiffs_setup.py | #!/usr/bin/env python3
#
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the MIT license.
#
# Title : superpmi_asmdiffs_setup.py
#
# Notes:
#
# Script to setup the directory structure required to perform SuperPMI asmdiffs in CI.
# It creates `correlation_payload_directory` with `base` and `diff` directories
# that contain clrjit*.dll. It figures out the baseline commit hash to use for
# a particular GitHub pull request, and downloads the JIT rolling build for that
# commit hash. It downloads the jitutils repo and builds the jit-analyze tool. It
# downloads a version of `git` to be used by jit-analyze.
#
################################################################################
################################################################################
import argparse
import logging
import os
from coreclr_arguments import *
from jitutil import copy_directory, set_pipeline_variable, run_command, TempDir, download_files
parser = argparse.ArgumentParser(description="description")
parser.add_argument("-arch", help="Architecture")
parser.add_argument("-source_directory", help="Path to the root directory of the dotnet/runtime source tree")
parser.add_argument("-product_directory", help="Path to the directory containing built binaries (e.g., <source_directory>/artifacts/bin/coreclr/windows.x64.Checked)")
is_windows = platform.system() == "Windows"
def setup_args(args):
""" Setup the args for SuperPMI to use.
Args:
args (ArgParse): args parsed by arg parser
Returns:
args (CoreclrArguments)
"""
coreclr_args = CoreclrArguments(args, require_built_core_root=False, require_built_product_dir=False,
require_built_test_dir=False, default_build_type="Checked")
coreclr_args.verify(args,
"arch",
lambda unused: True,
"Unable to set arch")
coreclr_args.verify(args,
"source_directory",
lambda source_directory: os.path.isdir(source_directory),
"source_directory doesn't exist")
coreclr_args.verify(args,
"product_directory",
lambda product_directory: os.path.isdir(product_directory),
"product_directory doesn't exist")
return coreclr_args
def match_jit_files(full_path):
""" Match all the JIT files that we want to copy and use.
Note that we currently only match Windows files, and not osx cross-compile files.
We also don't copy the "default" clrjit.dll, since we always use the fully specified
JITs, e.g., clrjit_win_x86_x86.dll.
"""
file_name = os.path.basename(full_path)
if file_name.startswith("clrjit_") and file_name.endswith(".dll") and file_name.find("osx") == -1:
return True
return False
def match_superpmi_tool_files(full_path):
""" Match all the SuperPMI tool files that we want to copy and use.
Note that we currently only match Windows files.
"""
file_name = os.path.basename(full_path)
if file_name == "superpmi.exe" or file_name == "mcs.exe":
return True
return False
def main(main_args):
""" Prepare the Helix data for SuperPMI asmdiffs Azure DevOps pipeline.
The Helix correlation payload directory is created and populated as follows:
<source_directory>\payload -- the correlation payload directory
-- contains the *.py scripts from <source_directory>\src\coreclr\scripts
-- contains superpmi.exe, mcs.exe from the target-specific build
<source_directory>\payload\base
-- contains the baseline JITs
<source_directory>\payload\diff
-- contains the diff JITs
<source_directory>\payload\jit-analyze
-- contains the self-contained jit-analyze build (from dotnet/jitutils)
<source_directory>\payload\git
-- contains a Portable ("xcopy installable") `git` tool, downloaded from:
https://netcorenativeassets.blob.core.windows.net/resource-packages/external/windows/git/Git-2.32.0-64-bit.zip
This is needed by jit-analyze to do `git diff` on the generated asm. The `<source_directory>\payload\git\cmd`
directory is added to the PATH.
NOTE: this only runs on Windows.
Then, AzDO pipeline variables are set.
Args:
main_args ([type]): Arguments to the script
Returns:
0 on success, otherwise a failure code
"""
# Set up logging.
logger = logging.getLogger()
logger.setLevel(logging.INFO)
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.INFO)
logger.addHandler(stream_handler)
coreclr_args = setup_args(main_args)
arch = coreclr_args.arch
source_directory = coreclr_args.source_directory
product_directory = coreclr_args.product_directory
python_path = sys.executable
# CorrelationPayload directories
correlation_payload_directory = os.path.join(source_directory, "payload")
superpmi_scripts_directory = os.path.join(source_directory, 'src', 'coreclr', 'scripts')
base_jit_directory = os.path.join(correlation_payload_directory, "base")
diff_jit_directory = os.path.join(correlation_payload_directory, "diff")
jit_analyze_build_directory = os.path.join(correlation_payload_directory, "jit-analyze")
git_directory = os.path.join(correlation_payload_directory, "git")
######## Get the portable `git` package
git_url = "https://netcorenativeassets.blob.core.windows.net/resource-packages/external/windows/git/Git-2.32.0-64-bit.zip"
print('Downloading {} -> {}'.format(git_url, git_directory))
urls = [ git_url ]
# There are too many files to be verbose in the download and copy.
download_files(urls, git_directory, verbose=False, display_progress=False)
git_exe_tool = os.path.join(git_directory, "cmd", "git.exe")
if not os.path.isfile(git_exe_tool):
print('Error: `git` not found at {}'.format(git_exe_tool))
return 1
######## Get SuperPMI python scripts
# Copy *.py to CorrelationPayload
print('Copying {} -> {}'.format(superpmi_scripts_directory, correlation_payload_directory))
copy_directory(superpmi_scripts_directory, correlation_payload_directory, verbose_copy=True,
match_func=lambda path: any(path.endswith(extension) for extension in [".py"]))
######## Get baseline JIT
# Figure out which baseline JIT to use, and download it.
if not os.path.exists(base_jit_directory):
os.makedirs(base_jit_directory)
print("Fetching history of `main` branch so we can find the baseline JIT")
run_command(["git", "fetch", "--depth=500", "origin", "main"], source_directory, _exit_on_fail=True)
# Note: we only support downloading Windows versions of the JIT currently. To support downloading
# non-Windows JITs on a Windows machine, pass `-host_os <os>` to jitrollingbuild.py.
print("Running jitrollingbuild.py download to get baseline JIT")
jit_rolling_build_script = os.path.join(superpmi_scripts_directory, "jitrollingbuild.py")
_, _, return_code = run_command([
python_path,
jit_rolling_build_script,
"download",
"-arch", arch,
"-target_dir", base_jit_directory],
source_directory)
if return_code != 0:
print('{} failed with {}'.format(jit_rolling_build_script, return_code))
return return_code
######## Get diff JIT
print('Copying diff binaries {} -> {}'.format(product_directory, diff_jit_directory))
copy_directory(product_directory, diff_jit_directory, verbose_copy=True, match_func=match_jit_files)
######## Get SuperPMI tools
# Put the SuperPMI tools directly in the root of the correlation payload directory.
print('Copying SuperPMI tools {} -> {}'.format(product_directory, correlation_payload_directory))
copy_directory(product_directory, correlation_payload_directory, verbose_copy=True, match_func=match_superpmi_tool_files)
######## Clone and build jitutils: we only need jit-analyze
try:
with TempDir() as jitutils_directory:
run_command(
["git", "clone", "--quiet", "--depth", "1", "https://github.com/dotnet/jitutils", jitutils_directory])
# Make sure ".dotnet" directory exists, by running the script at least once
dotnet_script_name = "dotnet.cmd" if is_windows else "dotnet.sh"
dotnet_script_path = os.path.join(source_directory, dotnet_script_name)
run_command([dotnet_script_path, "--info"], jitutils_directory)
# Build jit-analyze only, and build it as a self-contained app (not framework-dependent).
# What target RID are we building? It depends on where we're going to run this code.
# The RID catalog is here: https://docs.microsoft.com/en-us/dotnet/core/rid-catalog.
# Windows x64 => win-x64
# Windows x86 => win-x86
# Windows arm32 => win-arm
# Windows arm64 => win-arm64
# Linux x64 => linux-x64
# Linux arm32 => linux-arm
# Linux arm64 => linux-arm64
# macOS x64 => osx-x64
# NOTE: we currently only support running on Windows x86/x64 (we don't pass the target OS)
RID = None
if arch == "x86":
RID = "win-x86"
if arch == "x64":
RID = "win-x64"
# Set dotnet path to run build
os.environ["PATH"] = os.path.join(source_directory, ".dotnet") + os.pathsep + os.environ["PATH"]
run_command([
"dotnet",
"publish",
"-c", "Release",
"--runtime", RID,
"--self-contained",
"--output", jit_analyze_build_directory,
os.path.join(jitutils_directory, "src", "jit-analyze", "jit-analyze.csproj")],
jitutils_directory)
except PermissionError as pe_error:
# Details: https://bugs.python.org/issue26660
print('Ignoring PermissionError: {0}'.format(pe_error))
jit_analyze_tool = os.path.join(jit_analyze_build_directory, "jit-analyze.exe")
if not os.path.isfile(jit_analyze_tool):
print('Error: {} not found'.format(jit_analyze_tool))
return 1
######## Set pipeline variables
helix_source_prefix = "official"
creator = ""
print('Setting pipeline variables:')
set_pipeline_variable("CorrelationPayloadDirectory", correlation_payload_directory)
set_pipeline_variable("Architecture", arch)
set_pipeline_variable("Creator", creator)
set_pipeline_variable("HelixSourcePrefix", helix_source_prefix)
return 0
if __name__ == "__main__":
args = parser.parse_args()
sys.exit(main(args))
| []
| []
| [
"PATH"
]
| [] | ["PATH"] | python | 1 | 0 | |
shared/generate/lex/parse.go | package lex
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
)
// Parse runs the Go parser against the given package name.
func Parse(name string) (*ast.Package, error) {
base := os.Getenv("GOPATH")
if base == "" {
base = "~/go"
}
dir := filepath.Join(base, "src", name)
fset := token.NewFileSet()
paths, err := filepath.Glob(filepath.Join(dir, "*.go"))
if err != nil {
return nil, errors.Wrap(err, "Search source file")
}
files := map[string]*ast.File{}
for _, path := range paths {
// Skip test files.
if strings.Contains(path, "_test.go") {
continue
}
file, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("Parse Go source file %q", path)
}
files[path] = file
}
// Ignore errors because they are typically about unresolved symbols.
pkg, _ := ast.NewPackage(fset, files, nil, nil)
return pkg, nil
}
| [
"\"GOPATH\""
]
| []
| [
"GOPATH"
]
| [] | ["GOPATH"] | go | 1 | 0 | |
experiments/inception_score/conopt_conv4.py | import os
from subprocess import call
from os import path
import sys
# Executables
executable = 'python'
# Paths
rootdir = '../..'
scriptname = 'run.py'
cwd = os.path.dirname(os.path.abspath(__file__))
outdir = os.path.join(cwd, 'out/conopt_conv4')
args = [
# Architecture
'--image-size', '375',
'--output-size', '32',
'--c-dim', '3',
'--z-dim', '256',
'--gf-dim', '64',
'--df-dim', '64',
'--g-architecture', 'dcgan4_nobn',
'--d-architecture', 'dcgan4_nobn',
'--gan-type','standard',
# Training
'--optimizer', 'conopt',
'--nsteps', '150000',
'--ntest', '1000',
'--learning-rate', '1e-4',
'--reg-param', '10.',
'--batch-size', '64',
'--log-dir', os.path.join(outdir, 'tf_logs'),
'--sample-dir', os.path.join(outdir, 'samples'),
'--is-inception-scores',
'--inception-dir', './inception',
# Data set
'--dataset', 'cifar-10',
'--data-dir', './data',
'--split', 'train'
]
# Run
my_env = os.environ.copy()
call([executable, scriptname] + args, env=my_env, cwd=rootdir)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
split_reach/fuzzymatcher/fuzzymatcher_task.py | #!/usr/bin/env python3
"""
Operator for matching references to publications in database
"""
import tempfile
import logging
import gzip
import json
import os
import argparse
import elastic.common
from hooks import s3hook
from hooks.sentry import report_exception
logger = logging.getLogger(__name__)
def yield_structured_references(s3, structured_references_path):
with tempfile.TemporaryFile(mode='rb+') as tf:
key = s3.get_s3_object(structured_references_path)
key.download_fileobj(tf)
tf.seek(0)
with gzip.GzipFile(mode='rb', fileobj=tf) as f:
for line in f:
yield json.loads(line)
def map_author(author):
return "%s %s" % (
author.get(
"LastName",
"Unknown"
), author.get("Initials", "?"),)
class ElasticsearchFuzzyMatcher:
MAX_TITLE_LENGTH = 512
def __init__(self, es, score_threshold, should_match_threshold,
es_index, organisation, min_title_length=0):
self.es = es
self.es_index = es_index
self.score_threshold = score_threshold
self.min_title_length = min_title_length
self.should_match_threshold = should_match_threshold
self.organisation = organisation
def match(self, reference):
if not reference.get('Title'):
return
title = reference['Title']
title_len = len(title)
if title_len < self.min_title_length:
return
if title_len > self.MAX_TITLE_LENGTH:
# ExtractRefs does not always yield journal titles;
# sometimes it just yields back a wholesale paragraph
# of text from somewhere in the document. Truncate this
# because sending it up to ES results in an error.
# (We may want to just skip long titles instead...and
# certainly should monitor them.)
title = ' '.join(
title[:self.MAX_TITLE_LENGTH].split()[:-1]
)
logger.info(
'ElasticsearchFuzzyMatcher.match: '
'orig-length=%d doc-id=%s truncated-title=%r',
title_len, reference.get('document_id', "Unkown ID"), title
)
body = {
"query": {
"match": {
"doc.title": {
"query": title,
"minimum_should_match": f"{self.should_match_threshold}%"
}
}
}
}
res = self.es.search(
index=self.es_index,
body=body,
size=1
)
matches_count = res['hits']['total']['value']
if matches_count == 0:
return
best_match = res['hits']['hits'][0]
best_score = best_match['_score']
if best_score > self.score_threshold:
matched_reference = best_match['_source']
# logger.info(
# 'ElasticsearchFuzzyMatcher.match: '
# 'doc-id=%s similarity=%.1f',
# reference['Document id'], best_score
# )
ref_metadata = reference.get('metadata', {})
return {
'reference_id': reference.get('reference_id', None),
'extracted_title': reference.get('Title', None),
'similarity': best_score,
# Matched reference information
'match_title': matched_reference.get('doc', {}).get('title', 'Unknown'),
'match_algo': 'Fuzzy match',
'match_pub_year': matched_reference.get('doc', {}).get('pubYear', None),
'match_authors': ", ".join(list(map(map_author, matched_reference.get('doc', {}).get('authors', [])))),
'match_publication': matched_reference.get('doc', {}).get('journalTitle', 'Unknown'),
'match_pmcid': matched_reference.get('doc', {}).get('pmcid', None),
'match_pmid': matched_reference.get('doc', {}).get('pmid', None),
'match_doi': matched_reference.get('doc', {}).get('doi', None),
'match_issn': matched_reference.get('doc', {}).get('journalISSN', None),
'match_source': 'EPMC',
'associated_policies_count': 1,
# Policy information
'policies': [{
'doc_id': ref_metadata.get("file_hash", None),
'source_url': ref_metadata.get('url', None),
'title': ref_metadata.get('title', None),
'source_page': ref_metadata.get('source_page', None),
'source_page_title': ref_metadata.get('source_page_title', None),
'pdf_creator': ref_metadata.get('creator', None),
'organisation': self.organisation,
}]
}
class FuzzyMatchRefsOperator(object):
"""
Matches references to known publications in the database
Args:
references: The references to match against the database
"""
template_fields = (
'src_s3_key',
'dst_s3_key'
)
def __init__(self, es_hosts, src_s3_key, dst_s3_key, es_index,
score_threshold=50,
organisation=None,
should_match_threshold=80):
self.src_s3_key = src_s3_key
self.dst_s3_key = dst_s3_key
self.score_threshold = score_threshold
self.should_match_threshold = should_match_threshold
self.es_index = es_index
self.organisation = organisation
self.es = elastic.common.connect(es_hosts)
@report_exception
def execute(self):
s3 = s3hook.S3Hook()
fuzzy_matcher = ElasticsearchFuzzyMatcher(
self.es,
self.score_threshold,
self.should_match_threshold,
self.es_index,
self.organisation,
)
refs = yield_structured_references(s3, self.src_s3_key)
match_count = 0
count = 0
references = {}
for count, structured_reference in enumerate(refs, 1):
if count % 500 == 0:
logger.info(
'FuzzyMatchRefsOperator: references=%d', count
)
fuzzy_matched_reference = fuzzy_matcher.match(
structured_reference
)
if fuzzy_matched_reference:
ref_id = fuzzy_matched_reference['reference_id']
if ref_id in references.keys():
references[ref_id]['policies'][
'associated_policies_count'] += 1
references[ref_id]['policies'].append(
fuzzy_matched_reference['policies'][0]
)
else:
references[ref_id] = fuzzy_matched_reference
match_count += 1
if match_count % 100 == 0:
logger.info(
'FuzzyMatchRefsOperator: matches=%d',
match_count
)
with tempfile.NamedTemporaryFile(mode='wb') as output_raw_f:
with gzip.GzipFile(mode='wb', fileobj=output_raw_f) as output_f:
for reference in references.values():
output_f.write(json.dumps(reference).encode('utf-8'))
output_f.write(b'\n')
output_raw_f.flush()
s3.load_file(
output_raw_f.name,
self.dst_s3_key,
)
logger.info(
'FuzzyMatchRefsOperator: references=%d matches=%d',
count, match_count
)
logger.info(
'FuzzyMatchRefsOperator: Matches saved to %s',
s3.get_s3_object(self.dst_s3_key)
)
if __name__ == '__main__':
es_host = os.environ['ES_HOST']
es_port = os.environ.get('ES_PORT', 9200)
es_hosts = [(es_host, es_port)]
arg_parser = argparse.ArgumentParser(
description='Run a web scraper for a given organisation and writes the'
' results to the given S3 path.'
)
arg_parser.add_argument(
'src_s3_key',
help='The source path to s3.'
)
arg_parser.add_argument(
'dst_s3_key',
help='The destination path to s3.'
)
arg_parser.add_argument(
'organisation',
choices=s3hook.ORGS,
default=None,
help='The organisation to match citations with.'
)
arg_parser.add_argument(
'epmc_es_index',
help='The index where EPMC data is stored.'
)
arg_parser.add_argument(
'--score_threshold',
default=None,
help="The maximum number of items to index."
)
arg_parser.add_argument(
'--should_match_threshold',
default=None,
help="The maximum number of items to index."
)
args = arg_parser.parse_args()
fuzzy_matcher = FuzzyMatchRefsOperator(
es_hosts,
args.src_s3_key,
args.dst_s3_key,
args.epmc_es_index,
score_threshold=args.score_threshold,
organisation=args.organisation,
should_match_threshold=args.should_match_threshold
)
fuzzy_matcher.execute()
| []
| []
| [
"ES_PORT",
"ES_HOST"
]
| [] | ["ES_PORT", "ES_HOST"] | python | 2 | 0 | |
extra_tests/test_datetime.py | """Additional tests for datetime."""
import pytest
import datetime
import sys
class date_safe(datetime.date):
pass
class datetime_safe(datetime.datetime):
pass
class time_safe(datetime.time):
pass
class timedelta_safe(datetime.timedelta):
pass
@pytest.mark.parametrize("obj, expected", [
(datetime.date(2015, 6, 8), "datetime.date(2015, 6, 8)"),
(datetime.datetime(2015, 6, 8, 12, 34, 56),
"datetime.datetime(2015, 6, 8, 12, 34, 56)"),
(datetime.time(12, 34, 56), "datetime.time(12, 34, 56)"),
(datetime.timedelta(1), "datetime.timedelta(days=1)"),
(datetime.timedelta(1, 2), "datetime.timedelta(days=1, seconds=2)"),
(datetime.timedelta(1, 2, 3), "datetime.timedelta(days=1, seconds=2, microseconds=3)"),
(date_safe(2015, 6, 8), "date_safe(2015, 6, 8)"),
(datetime_safe(2015, 6, 8, 12, 34, 56),
"datetime_safe(2015, 6, 8, 12, 34, 56)"),
(time_safe(12, 34, 56), "time_safe(12, 34, 56)"),
(timedelta_safe(1), "timedelta_safe(days=1)"),
(timedelta_safe(1, 2), "timedelta_safe(days=1, seconds=2)"),
(timedelta_safe(1, 2, 3), "timedelta_safe(days=1, seconds=2, microseconds=3)"),
])
def test_repr(obj, expected):
assert repr(obj).endswith(expected)
@pytest.mark.parametrize("obj", [
datetime.date.today(),
datetime.time(),
datetime.datetime.utcnow(),
datetime.timedelta(),
datetime.tzinfo(),
])
def test_attributes(obj):
with pytest.raises(AttributeError):
obj.abc = 1
def test_timedelta_init_long():
td = datetime.timedelta(microseconds=20000000000000000000)
assert td.days == 231481481
assert td.seconds == 41600
td = datetime.timedelta(microseconds=20000000000000000000.)
assert td.days == 231481481
assert td.seconds == 41600
def test_unpickle():
with pytest.raises(TypeError) as e:
datetime.date('123')
assert e.value.args[0].startswith('an integer is required')
with pytest.raises(TypeError) as e:
datetime.time('123')
assert e.value.args[0].startswith('an integer is required')
with pytest.raises(TypeError) as e:
datetime.datetime('123')
assert e.value.args[0].startswith('an integer is required')
datetime.time(b'\x01' * 6, None)
with pytest.raises(TypeError) as exc:
datetime.time(b'\x01' * 6, 123)
assert str(exc.value) == "bad tzinfo state arg"
datetime.datetime(b'\x01' * 10, None)
with pytest.raises(TypeError) as exc:
datetime.datetime(b'\x01' * 10, 123)
assert str(exc.value) == "bad tzinfo state arg"
def test_strptime():
import time, sys
string = '2004-12-01 13:02:47'
format = '%Y-%m-%d %H:%M:%S'
expected = datetime.datetime(*(time.strptime(string, format)[0:6]))
got = datetime.datetime.strptime(string, format)
assert expected == got
def test_datetime_rounding():
b = 0.0000001
a = 0.9999994
assert datetime.datetime.utcfromtimestamp(a).microsecond == 999999
assert datetime.datetime.utcfromtimestamp(a).second == 0
a += b
assert datetime.datetime.utcfromtimestamp(a).microsecond == 999999
assert datetime.datetime.utcfromtimestamp(a).second == 0
a += b
assert datetime.datetime.utcfromtimestamp(a).microsecond == 0
assert datetime.datetime.utcfromtimestamp(a).second == 1
def test_more_datetime_rounding():
expected_results = {
-1000.0: 'datetime.datetime(1969, 12, 31, 23, 43, 20)',
-999.9999996: 'datetime.datetime(1969, 12, 31, 23, 43, 20)',
-999.4: 'datetime.datetime(1969, 12, 31, 23, 43, 20, 600000)',
-999.0000004: 'datetime.datetime(1969, 12, 31, 23, 43, 21)',
-1.0: 'datetime.datetime(1969, 12, 31, 23, 59, 59)',
-0.9999996: 'datetime.datetime(1969, 12, 31, 23, 59, 59)',
-0.4: 'datetime.datetime(1969, 12, 31, 23, 59, 59, 600000)',
-0.0000004: 'datetime.datetime(1970, 1, 1, 0, 0)',
0.0: 'datetime.datetime(1970, 1, 1, 0, 0)',
0.0000004: 'datetime.datetime(1970, 1, 1, 0, 0)',
0.4: 'datetime.datetime(1970, 1, 1, 0, 0, 0, 400000)',
0.9999996: 'datetime.datetime(1970, 1, 1, 0, 0, 1)',
1000.0: 'datetime.datetime(1970, 1, 1, 0, 16, 40)',
1000.0000004: 'datetime.datetime(1970, 1, 1, 0, 16, 40)',
1000.4: 'datetime.datetime(1970, 1, 1, 0, 16, 40, 400000)',
1000.9999996: 'datetime.datetime(1970, 1, 1, 0, 16, 41)',
1293843661.191: 'datetime.datetime(2011, 1, 1, 1, 1, 1, 191000)',
}
for t in sorted(expected_results):
dt = datetime.datetime.utcfromtimestamp(t)
assert repr(dt) == expected_results[t]
def test_utcfromtimestamp():
"""Confirm that utcfromtimestamp and fromtimestamp give consistent results.
Based on danchr's test script in https://bugs.pypy.org/issue986
"""
import os
import time
if os.name == 'nt':
pytest.skip("setting os.environ['TZ'] ineffective on windows")
try:
prev_tz = os.environ.get("TZ")
os.environ["TZ"] = "GMT"
time.tzset()
for unused in range(100):
now = time.time()
delta = (datetime.datetime.utcfromtimestamp(now) -
datetime.datetime.fromtimestamp(now))
assert delta.days * 86400 + delta.seconds == 0
finally:
if prev_tz is None:
del os.environ["TZ"]
else:
os.environ["TZ"] = prev_tz
time.tzset()
def test_utcfromtimestamp_microsecond():
dt = datetime.datetime.utcfromtimestamp(0)
assert isinstance(dt.microsecond, int)
def test_default_args():
with pytest.raises(TypeError):
datetime.datetime()
with pytest.raises(TypeError):
datetime.datetime(10)
with pytest.raises(TypeError):
datetime.datetime(10, 10)
datetime.datetime(10, 10, 10)
def test_check_arg_types():
import decimal
class Number:
def __init__(self, value):
self.value = int(value)
def __int__(self):
return self.value
class SubInt(int):
pass
dt10 = datetime.datetime(10, 10, 10, 10, 10, 10, 10)
for xx in [
decimal.Decimal(10),
decimal.Decimal('10.9'),
Number(10),
SubInt(10),
Number(SubInt(10)),
]:
dtxx = datetime.datetime(xx, xx, xx, xx, xx, xx, xx)
assert dt10 == dtxx
assert type(dtxx.month) is int
assert type(dtxx.second) is int
with pytest.raises(TypeError) as exc:
datetime.datetime(0, 10, '10')
assert str(exc.value).startswith('an integer is required')
f10 = Number(10.9)
datetime.datetime(10, 10, f10)
class Float(float):
pass
s10 = Float(10.9)
with pytest.raises(TypeError) as exc:
datetime.datetime(10, 10, s10)
assert str(exc.value) == 'integer argument expected, got float'
with pytest.raises(TypeError):
datetime.datetime(10., 10, 10)
with pytest.raises(TypeError):
datetime.datetime(10, 10., 10)
with pytest.raises(TypeError):
datetime.datetime(10, 10, 10.)
with pytest.raises(TypeError):
datetime.datetime(10, 10, 10, 10.)
with pytest.raises(TypeError):
datetime.datetime(10, 10, 10, 10, 10.)
with pytest.raises(TypeError):
datetime.datetime(10, 10, 10, 10, 10, 10.)
with pytest.raises(TypeError):
datetime.datetime(10, 10, 10, 10, 10, 10, 10.)
def test_utcnow_microsecond():
import copy
dt = datetime.datetime.utcnow()
assert type(dt.microsecond) is int
copy.copy(dt)
def test_radd():
class X(object):
def __radd__(self, other):
return "radd"
assert datetime.date(10, 10, 10) + X() == "radd"
def test_raises_if_passed_naive_datetime_and_start_or_end_time_defined():
class Foo(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(0.1)
naive = datetime.datetime(2014, 9, 22)
aware = datetime.datetime(2014, 9, 22, tzinfo=Foo())
assert naive != aware
with pytest.raises(TypeError) as exc:
naive.__sub__(aware)
assert str(exc.value) == "can't subtract offset-naive and offset-aware datetimes"
naive = datetime.time(7, 32, 12)
aware = datetime.time(7, 32, 12, tzinfo=Foo())
assert naive != aware
def test_future_types_newint():
# Issue 2193
class newint(int):
def __int__(self):
return self
dt_from_ints = datetime.datetime(2015, 12, 31, 12, 34, 56)
dt_from_newints = datetime.datetime(newint(2015), newint(12), newint(31), newint(12), newint(34), newint(56))
dt_from_mixed = datetime.datetime(2015, newint(12), 31, newint(12), 34, newint(56))
assert dt_from_ints == dt_from_newints
assert dt_from_newints == dt_from_mixed
assert dt_from_mixed == dt_from_ints
d_from_int = datetime.date.fromtimestamp(1431216000)
d_from_newint = datetime.date.fromtimestamp(newint(1431216000))
assert d_from_int == d_from_newint
dt_from_int = datetime.datetime.fromtimestamp(1431216000)
dt_from_newint = datetime.datetime.fromtimestamp(newint(1431216000))
assert dt_from_int == dt_from_newint
dtu_from_int = datetime.datetime.utcfromtimestamp(1431216000)
dtu_from_newint = datetime.datetime.utcfromtimestamp(newint(1431216000))
assert dtu_from_int == dtu_from_newint
td_from_int = datetime.timedelta(16565)
tds_from_int = datetime.timedelta(seconds=1431216000)
td_from_newint = datetime.timedelta(newint(16565))
tds_from_newint = datetime.timedelta(seconds=newint(1431216000))
assert td_from_int == tds_from_int
assert td_from_int == td_from_newint
assert td_from_int == tds_from_newint
assert tds_from_int == td_from_newint
assert tds_from_int == tds_from_newint
assert td_from_newint == tds_from_newint
td_mul_int_int = td_from_int * 2
td_mul_int_newint = td_from_int * newint(2)
td_mul_newint_int = td_from_newint * 2
td_mul_newint_newint = td_from_newint * newint(2)
assert td_mul_int_int == td_mul_int_newint
assert td_mul_int_int == td_mul_newint_int
assert td_mul_int_int == td_mul_newint_newint
assert td_mul_int_newint == td_mul_newint_int
assert td_mul_int_newint == td_mul_newint_newint
assert td_mul_newint_int == td_mul_newint_newint
td_div_int_int = td_from_int / 3600
td_div_int_newint = td_from_int / newint(3600)
td_div_newint_int = td_from_newint / 3600
td_div_newint_newint = td_from_newint / newint(3600)
assert td_div_int_int == td_div_int_newint
assert td_div_int_int == td_div_newint_int
assert td_div_int_int == td_div_newint_newint
assert td_div_int_newint == td_div_newint_int
assert td_div_int_newint == td_div_newint_newint
assert td_div_newint_int == td_div_newint_newint
def test_return_types():
td = datetime.timedelta(5)
assert type(td.total_seconds()) is float
class sub(datetime.timedelta): pass
assert type(+sub()) is datetime.timedelta
def test_subclass_date():
# replace() should return a subclass but not call __new__ or __init__.
class MyDate(datetime.date):
forbidden = False
def __new__(cls):
if cls.forbidden: FAIL
return datetime.date.__new__(cls, 2016, 2, 3)
def __init__(self, *args):
if self.forbidden: FAIL
d = MyDate()
d.forbidden = True
d2 = d.replace(day=5)
assert type(d2) is MyDate
assert d2 == datetime.date(2016, 2, 5)
def test_subclass_time():
# replace() should return a subclass but not call __new__ or __init__.
class MyTime(datetime.time):
forbidden = False
def __new__(cls):
if cls.forbidden: FAIL
return datetime.time.__new__(cls, 1, 2, 3)
def __init__(self, *args):
if self.forbidden: FAIL
d = MyTime()
d.forbidden = True
d2 = d.replace(hour=5)
assert type(d2) is MyTime
assert d2 == datetime.time(5, 2, 3)
def test_subclass_datetime():
# replace() should return a subclass but not call __new__ or __init__.
class MyDatetime(datetime.datetime):
forbidden = False
def __new__(cls):
if cls.forbidden: FAIL
return datetime.datetime.__new__(cls, 2016, 4, 5, 1, 2, 3)
def __init__(self, *args):
if self.forbidden: FAIL
d = MyDatetime()
d.forbidden = True
d2 = d.replace(hour=7)
assert type(d2) is MyDatetime
assert d2 == datetime.datetime(2016, 4, 5, 7, 2, 3)
@pytest.mark.skipif('__pypy__' not in sys.builtin_module_names, reason='pypy only')
def test_normalize_pair():
normalize = datetime._normalize_pair
assert normalize(1, 59, 60) == (1, 59)
assert normalize(1, 60, 60) == (2, 0)
assert normalize(1, 95, 60) == (2, 35)
@pytest.mark.skipif('__pypy__' not in sys.builtin_module_names, reason='pypy only')
def test_normalize_date():
normalize = datetime._normalize_date
# Huge year is caught correctly
with pytest.raises(OverflowError):
normalize(1000 * 1000, 1, 1)
# Normal dates should be unchanged
assert normalize(3000, 1, 1) == (3000, 1, 1)
# Month overflows year boundary
assert normalize(2001, 24, 1) == (2002, 12, 1)
# Day overflows month boundary
assert normalize(2001, 14, 31) == (2002, 3, 3)
# Leap years? :S
assert normalize(2001, 1, 61) == (2001, 3, 2)
assert normalize(2000, 1, 61) == (2000, 3, 1)
@pytest.mark.skipif('__pypy__' not in sys.builtin_module_names, reason='pypy only')
def test_normalize_datetime():
normalize = datetime._normalize_datetime
abnormal = (2002, 13, 35, 30, 95, 75, 1000001)
assert normalize(*abnormal) == (2003, 2, 5, 7, 36, 16, 1)
| []
| []
| [
"TZ"
]
| [] | ["TZ"] | python | 1 | 0 | |
src/decisionengine/framework/modules/de_logger.py | # SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Logger to use in all modules
"""
import logging
import logging.config
import logging.handlers
import os
import structlog
import decisionengine.framework.modules.logging_configDict as logconf
import decisionengine.framework.modules.QueueLogger as QueueLogger
MB = 1000000
delogger = structlog.getLogger(logconf.LOGGERNAME)
delogger = delogger.bind(module=__name__.split(".")[-1], channel=logconf.DELOGGER_CHANNEL_NAME)
queue_logger = QueueLogger.QueueLogger()
def configure_logging(
log_level="DEBUG",
file_rotate_by="size",
rotation_time_unit="D",
rotation_interval=1,
max_backup_count=6,
max_file_size=200 * MB,
log_file_name="/tmp/decision_engine_logs/decisionengine.log",
start_q_logger="True",
):
"""
:type log_level: :obj:`str`
:arg log_level: log level
:type file_rotate_by: :obj: `str`
:arg file_rotate_by: files rotation by size or by time
:type rotation_time_unit: :obj:`str`
:arg rotation_time_unit: unit of time for file rotation
:type rotation_interval: :obj:`int`
:arg rotation_interval: time in rotation_time_units between file rotations
:type log_file_name: :obj:`str`
:arg log_file_name: log file name
:type max_file_size: :obj:`int`
:arg max_file_size: maximal size of log file. If reached save and start new log.
:type max_backup_count: :obj:`int`
:arg max_backup_count: start rotaion after this number is reached
:rtype: None
"""
dirname = os.path.dirname(log_file_name)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
delogger.setLevel(getattr(logging, log_level.upper()))
if delogger.handlers:
delogger.debug("Reusing existing logging handlers")
return None
# configure handlers
handlers_list = []
if file_rotate_by == "size":
for files in logconf.de_outfile_info:
handler = logging.handlers.RotatingFileHandler(
filename=f"{log_file_name}" + files[0], maxBytes=max_file_size, backupCount=max_backup_count
)
handler.setLevel(files[1])
handler.setFormatter(logging.Formatter(files[2]))
handlers_list.append(handler)
elif file_rotate_by == "time":
for files in logconf.de_outfile_info:
handler = logging.handlers.TimedRotatingFileHandler(
filename=f"{log_file_name}" + files[0],
when=rotation_time_unit,
interval=rotation_interval,
backupCount=max_backup_count,
)
handler.setLevel(files[1])
handler.setFormatter(logging.Formatter(files[2]))
handlers_list.append(handler)
else:
raise ValueError(f"Incorrect 'file_rotate_by':'{file_rotate_by}:'")
structlog_handlers_list = [handlers_list.pop(i) for i in logconf.structlog_file_index]
# setup standard file handlers
for h in handlers_list:
delogger.addHandler(h)
# setup the queue logger
if start_q_logger == "True":
queue_logger.setup_queue_logging(delogger, structlog_handlers_list)
queue_logger.start()
delogger.debug("de logging setup complete")
def get_logger():
"""
get default logger - "decisionengine"
:rtype: :class:`logging.Logger` - rotating file logger
"""
return delogger
def get_queue_logger():
"""
get QueueLogger which owns the logging queues and listeners
:rtype: :class:`decisionengine.framework.modules.QueueLogger``
"""
return queue_logger
def stop_queue_logger():
queue_logger.stop()
if __name__ == "__main__":
configure_logging(
"ERROR",
"size",
"D",
1,
max_backup_count=5,
max_file_size=100000,
log_file_name=f"{os.environ.get('HOME')}/de_log/decision_engine_log0",
)
delogger.error("THIS IS ERROR")
delogger.info("THIS IS INFO")
delogger.debug("THIS IS DEBUG")
| []
| []
| [
"HOME"
]
| [] | ["HOME"] | python | 1 | 0 | |
pkg/commands/git.go | package commands
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/mgutz/str"
"github.com/go-errors/errors"
gogit "github.com/go-git/go-git/v5"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/i18n"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/sirupsen/logrus"
gitconfig "github.com/tcnksm/go-gitconfig"
)
// this takes something like:
// * (HEAD detached at 264fc6f5)
// remotes
// and returns '264fc6f5' as the second match
const CurrentBranchNameRegex = `(?m)^\*.*?([^ ]*?)\)?$`
func verifyInGitRepo(runCmd func(string, ...interface{}) error) error {
return runCmd("git status")
}
func navigateToRepoRootDirectory(stat func(string) (os.FileInfo, error), chdir func(string) error) error {
for {
_, err := stat(".git")
if err == nil {
return nil
}
if !os.IsNotExist(err) {
return WrapError(err)
}
if err = chdir(".."); err != nil {
return WrapError(err)
}
}
}
func setupRepositoryAndWorktree(openGitRepository func(string) (*gogit.Repository, error), sLocalize func(string) string) (repository *gogit.Repository, worktree *gogit.Worktree, err error) {
repository, err = openGitRepository(".")
if err != nil {
if strings.Contains(err.Error(), `unquoted '\' must be followed by new line`) {
return nil, nil, errors.New(sLocalize("GitconfigParseErr"))
}
return
}
worktree, err = repository.Worktree()
if err != nil {
return
}
return
}
// GitCommand is our main git interface
type GitCommand struct {
Log *logrus.Entry
OSCommand *OSCommand
Worktree *gogit.Worktree
Repo *gogit.Repository
Tr *i18n.Localizer
Config config.AppConfigurer
getGlobalGitConfig func(string) (string, error)
getLocalGitConfig func(string) (string, error)
removeFile func(string) error
DotGitDir string
onSuccessfulContinue func() error
PatchManager *PatchManager
// Push to current determines whether the user has configured to push to the remote branch of the same name as the current or not
PushToCurrent bool
}
// NewGitCommand it runs git commands
func NewGitCommand(log *logrus.Entry, osCommand *OSCommand, tr *i18n.Localizer, config config.AppConfigurer) (*GitCommand, error) {
var worktree *gogit.Worktree
var repo *gogit.Repository
// see what our default push behaviour is
output, err := osCommand.RunCommandWithOutput("git config --get push.default")
pushToCurrent := false
if err != nil {
log.Errorf("error reading git config: %v", err)
} else {
pushToCurrent = strings.TrimSpace(output) == "current"
}
fs := []func() error{
func() error {
return verifyInGitRepo(osCommand.RunCommand)
},
func() error {
return navigateToRepoRootDirectory(os.Stat, os.Chdir)
},
func() error {
var err error
repo, worktree, err = setupRepositoryAndWorktree(gogit.PlainOpen, tr.SLocalize)
return err
},
}
for _, f := range fs {
if err := f(); err != nil {
return nil, err
}
}
dotGitDir, err := findDotGitDir(os.Stat, ioutil.ReadFile)
if err != nil {
return nil, err
}
gitCommand := &GitCommand{
Log: log,
OSCommand: osCommand,
Tr: tr,
Worktree: worktree,
Repo: repo,
Config: config,
getGlobalGitConfig: gitconfig.Global,
getLocalGitConfig: gitconfig.Local,
removeFile: os.RemoveAll,
DotGitDir: dotGitDir,
PushToCurrent: pushToCurrent,
}
gitCommand.PatchManager = NewPatchManager(log, gitCommand.ApplyPatch)
return gitCommand, nil
}
func findDotGitDir(stat func(string) (os.FileInfo, error), readFile func(filename string) ([]byte, error)) (string, error) {
f, err := stat(".git")
if err != nil {
return "", err
}
if f.IsDir() {
return ".git", nil
}
fileBytes, err := readFile(".git")
if err != nil {
return "", err
}
fileContent := string(fileBytes)
if !strings.HasPrefix(fileContent, "gitdir: ") {
return "", errors.New(".git is a file which suggests we are in a submodule but the file's contents do not contain a gitdir pointing to the actual .git directory")
}
return strings.TrimSpace(strings.TrimPrefix(fileContent, "gitdir: ")), nil
}
func (c *GitCommand) getUnfilteredStashEntries() []*StashEntry {
unescaped := "git stash list --pretty='%gs'"
rawString, _ := c.OSCommand.RunCommandWithOutput(unescaped)
stashEntries := []*StashEntry{}
for i, line := range utils.SplitLines(rawString) {
stashEntries = append(stashEntries, stashEntryFromLine(line, i))
}
return stashEntries
}
// GetStashEntries stash entries
func (c *GitCommand) GetStashEntries(filterPath string) []*StashEntry {
if filterPath == "" {
return c.getUnfilteredStashEntries()
}
unescaped := fmt.Sprintf("git stash list --name-only")
rawString, err := c.OSCommand.RunCommandWithOutput(unescaped)
if err != nil {
return c.getUnfilteredStashEntries()
}
stashEntries := []*StashEntry{}
var currentStashEntry *StashEntry
lines := utils.SplitLines(rawString)
isAStash := func(line string) bool { return strings.HasPrefix(line, "stash@{") }
re := regexp.MustCompile(`stash@\{(\d+)\}`)
outer:
for i := 0; i < len(lines); i++ {
if !isAStash(lines[i]) {
continue
}
match := re.FindStringSubmatch(lines[i])
idx, err := strconv.Atoi(match[1])
if err != nil {
return c.getUnfilteredStashEntries()
}
currentStashEntry = stashEntryFromLine(lines[i], idx)
for i+1 < len(lines) && !isAStash(lines[i+1]) {
i++
if lines[i] == filterPath {
stashEntries = append(stashEntries, currentStashEntry)
continue outer
}
}
}
return stashEntries
}
func stashEntryFromLine(line string, index int) *StashEntry {
return &StashEntry{
Name: line,
Index: index,
}
}
// GetStashEntryDiff stash diff
func (c *GitCommand) ShowStashEntryCmdStr(index int) string {
return fmt.Sprintf("git stash show -p --color=%s stash@{%d}", c.colorArg(), index)
}
// GetStatusFiles git status files
func (c *GitCommand) GetStatusFiles() []*File {
statusOutput, _ := c.GitStatus()
statusStrings := utils.SplitLines(statusOutput)
files := []*File{}
for _, statusString := range statusStrings {
change := statusString[0:2]
stagedChange := change[0:1]
unstagedChange := statusString[1:2]
filename := c.OSCommand.Unquote(statusString[3:])
untracked := utils.IncludesString([]string{"??", "A ", "AM"}, change)
hasNoStagedChanges := utils.IncludesString([]string{" ", "U", "?"}, stagedChange)
hasMergeConflicts := utils.IncludesString([]string{"DD", "AA", "UU", "AU", "UA", "UD", "DU"}, change)
hasInlineMergeConflicts := utils.IncludesString([]string{"UU", "AA"}, change)
file := &File{
Name: filename,
DisplayString: statusString,
HasStagedChanges: !hasNoStagedChanges,
HasUnstagedChanges: unstagedChange != " ",
Tracked: !untracked,
Deleted: unstagedChange == "D" || stagedChange == "D",
HasMergeConflicts: hasMergeConflicts,
HasInlineMergeConflicts: hasInlineMergeConflicts,
Type: c.OSCommand.FileType(filename),
ShortStatus: change,
}
files = append(files, file)
}
return files
}
// StashDo modify stash
func (c *GitCommand) StashDo(index int, method string) error {
return c.OSCommand.RunCommand("git stash %s stash@{%d}", method, index)
}
// StashSave save stash
// TODO: before calling this, check if there is anything to save
func (c *GitCommand) StashSave(message string) error {
return c.OSCommand.RunCommand("git stash save %s", c.OSCommand.Quote(message))
}
// MergeStatusFiles merge status files
func (c *GitCommand) MergeStatusFiles(oldFiles, newFiles []*File) []*File {
if len(oldFiles) == 0 {
return newFiles
}
appendedIndexes := []int{}
// retain position of files we already could see
result := []*File{}
for _, oldFile := range oldFiles {
for newIndex, newFile := range newFiles {
if oldFile.Name == newFile.Name {
result = append(result, newFile)
appendedIndexes = append(appendedIndexes, newIndex)
break
}
}
}
// append any new files to the end
for index, newFile := range newFiles {
if !includesInt(appendedIndexes, index) {
result = append(result, newFile)
}
}
return result
}
func includesInt(list []int, a int) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
// ResetAndClean removes all unstaged changes and removes all untracked files
func (c *GitCommand) ResetAndClean() error {
if err := c.ResetHard("HEAD"); err != nil {
return err
}
return c.RemoveUntrackedFiles()
}
func (c *GitCommand) GetCurrentBranchUpstreamDifferenceCount() (string, string) {
return c.GetCommitDifferences("HEAD", "HEAD@{u}")
}
func (c *GitCommand) GetBranchUpstreamDifferenceCount(branchName string) (string, string) {
return c.GetCommitDifferences(branchName, branchName+"@{u}")
}
// GetCommitDifferences checks how many pushables/pullables there are for the
// current branch
func (c *GitCommand) GetCommitDifferences(from, to string) (string, string) {
command := "git rev-list %s..%s --count"
pushableCount, err := c.OSCommand.RunCommandWithOutput(command, to, from)
if err != nil {
return "?", "?"
}
pullableCount, err := c.OSCommand.RunCommandWithOutput(command, from, to)
if err != nil {
return "?", "?"
}
return strings.TrimSpace(pushableCount), strings.TrimSpace(pullableCount)
}
// RenameCommit renames the topmost commit with the given name
func (c *GitCommand) RenameCommit(name string) error {
return c.OSCommand.RunCommand("git commit --allow-empty --amend -m %s", c.OSCommand.Quote(name))
}
// RebaseBranch interactive rebases onto a branch
func (c *GitCommand) RebaseBranch(branchName string) error {
cmd, err := c.PrepareInteractiveRebaseCommand(branchName, "", false)
if err != nil {
return err
}
return c.OSCommand.RunPreparedCommand(cmd)
}
// Fetch fetch git repo
func (c *GitCommand) Fetch(unamePassQuestion func(string) string, canAskForCredentials bool) error {
return c.OSCommand.DetectUnamePass("git fetch", func(question string) string {
if canAskForCredentials {
return unamePassQuestion(question)
}
return "\n"
})
}
// ResetToCommit reset to commit
func (c *GitCommand) ResetToCommit(sha string, strength string, options RunCommandOptions) error {
return c.OSCommand.RunCommandWithOptions(fmt.Sprintf("git reset --%s %s", strength, sha), options)
}
// NewBranch create new branch
func (c *GitCommand) NewBranch(name string, baseBranch string) error {
return c.OSCommand.RunCommand("git checkout -b %s %s", name, baseBranch)
}
// CurrentBranchName get the current branch name and displayname.
// the first returned string is the name and the second is the displayname
// e.g. name is 123asdf and displayname is '(HEAD detached at 123asdf)'
func (c *GitCommand) CurrentBranchName() (string, string, error) {
branchName, err := c.OSCommand.RunCommandWithOutput("git symbolic-ref --short HEAD")
if err == nil && branchName != "HEAD\n" {
trimmedBranchName := strings.TrimSpace(branchName)
return trimmedBranchName, trimmedBranchName, nil
}
output, err := c.OSCommand.RunCommandWithOutput("git branch --contains")
if err != nil {
return "", "", err
}
for _, line := range utils.SplitLines(output) {
re := regexp.MustCompile(CurrentBranchNameRegex)
match := re.FindStringSubmatch(line)
if len(match) > 0 {
branchName = match[1]
displayBranchName := match[0][2:]
return branchName, displayBranchName, nil
}
}
return "HEAD", "HEAD", nil
}
// DeleteBranch delete branch
func (c *GitCommand) DeleteBranch(branch string, force bool) error {
command := "git branch -d"
if force {
command = "git branch -D"
}
return c.OSCommand.RunCommand("%s %s", command, branch)
}
// ListStash list stash
func (c *GitCommand) ListStash() (string, error) {
return c.OSCommand.RunCommandWithOutput("git stash list")
}
// Merge merge
func (c *GitCommand) Merge(branchName string) error {
mergeArgs := c.Config.GetUserConfig().GetString("git.merging.args")
return c.OSCommand.RunCommand("git merge --no-edit %s %s", mergeArgs, branchName)
}
// AbortMerge abort merge
func (c *GitCommand) AbortMerge() error {
return c.OSCommand.RunCommand("git merge --abort")
}
// usingGpg tells us whether the user has gpg enabled so that we can know
// whether we need to run a subprocess to allow them to enter their password
func (c *GitCommand) usingGpg() bool {
gpgsign, _ := c.getLocalGitConfig("commit.gpgsign")
if gpgsign == "" {
gpgsign, _ = c.getGlobalGitConfig("commit.gpgsign")
}
value := strings.ToLower(gpgsign)
return value == "true" || value == "1" || value == "yes" || value == "on"
}
// Commit commits to git
func (c *GitCommand) Commit(message string, flags string) (*exec.Cmd, error) {
command := fmt.Sprintf("git commit %s -m %s", flags, c.OSCommand.Quote(message))
if c.usingGpg() {
return c.OSCommand.PrepareSubProcess(c.OSCommand.Platform.shell, c.OSCommand.Platform.shellArg, command), nil
}
return nil, c.OSCommand.RunCommand(command)
}
// Get the subject of the HEAD commit
func (c *GitCommand) GetHeadCommitMessage() (string, error) {
cmdStr := "git log -1 --pretty=%s"
message, err := c.OSCommand.RunCommandWithOutput(cmdStr)
return strings.TrimSpace(message), err
}
// AmendHead amends HEAD with whatever is staged in your working tree
func (c *GitCommand) AmendHead() (*exec.Cmd, error) {
command := "git commit --amend --no-edit --allow-empty"
if c.usingGpg() {
return c.OSCommand.PrepareSubProcess(c.OSCommand.Platform.shell, c.OSCommand.Platform.shellArg, command), nil
}
return nil, c.OSCommand.RunCommand(command)
}
// Pull pulls from repo
func (c *GitCommand) Pull(args string, ask func(string) string) error {
return c.OSCommand.DetectUnamePass("git pull --no-edit "+args, ask)
}
// PullWithoutPasswordCheck assumes that the pull will not prompt the user for a password
func (c *GitCommand) PullWithoutPasswordCheck(args string) error {
return c.OSCommand.RunCommand("git pull --no-edit " + args)
}
// Push pushes to a branch
func (c *GitCommand) Push(branchName string, force bool, upstream string, args string, ask func(string) string) error {
forceFlag := ""
if force {
forceFlag = "--force-with-lease"
}
setUpstreamArg := ""
if upstream != "" {
setUpstreamArg = "--set-upstream " + upstream
}
cmd := fmt.Sprintf("git push --follow-tags %s %s %s", forceFlag, setUpstreamArg, args)
return c.OSCommand.DetectUnamePass(cmd, ask)
}
// CatFile obtains the content of a file
func (c *GitCommand) CatFile(fileName string) (string, error) {
return c.OSCommand.RunCommandWithOutput("%s %s", c.OSCommand.Platform.catCmd, c.OSCommand.Quote(fileName))
}
// StageFile stages a file
func (c *GitCommand) StageFile(fileName string) error {
return c.OSCommand.RunCommand("git add %s", c.OSCommand.Quote(fileName))
}
// StageAll stages all files
func (c *GitCommand) StageAll() error {
return c.OSCommand.RunCommand("git add -A")
}
// UnstageAll stages all files
func (c *GitCommand) UnstageAll() error {
return c.OSCommand.RunCommand("git reset")
}
// UnStageFile unstages a file
func (c *GitCommand) UnStageFile(fileName string, tracked bool) error {
command := "git rm --cached %s"
if tracked {
command = "git reset HEAD %s"
}
// renamed files look like "file1 -> file2"
fileNames := strings.Split(fileName, " -> ")
for _, name := range fileNames {
if err := c.OSCommand.RunCommand(command, c.OSCommand.Quote(name)); err != nil {
return err
}
}
return nil
}
// GitStatus returns the plaintext short status of the repo
func (c *GitCommand) GitStatus() (string, error) {
return c.OSCommand.RunCommandWithOutput("git status --untracked-files=all --porcelain")
}
// IsInMergeState states whether we are still mid-merge
func (c *GitCommand) IsInMergeState() (bool, error) {
return c.OSCommand.FileExists(fmt.Sprintf("%s/MERGE_HEAD", c.DotGitDir))
}
// RebaseMode returns "" for non-rebase mode, "normal" for normal rebase
// and "interactive" for interactive rebase
func (c *GitCommand) RebaseMode() (string, error) {
exists, err := c.OSCommand.FileExists(fmt.Sprintf("%s/rebase-apply", c.DotGitDir))
if err != nil {
return "", err
}
if exists {
return "normal", nil
}
exists, err = c.OSCommand.FileExists(fmt.Sprintf("%s/rebase-merge", c.DotGitDir))
if exists {
return "interactive", err
} else {
return "", err
}
}
// DiscardAllFileChanges directly
func (c *GitCommand) DiscardAllFileChanges(file *File) error {
// if the file isn't tracked, we assume you want to delete it
quotedFileName := c.OSCommand.Quote(file.Name)
if file.HasStagedChanges || file.HasMergeConflicts {
if err := c.OSCommand.RunCommand("git reset -- %s", quotedFileName); err != nil {
return err
}
}
if !file.Tracked {
return c.removeFile(file.Name)
}
return c.DiscardUnstagedFileChanges(file)
}
// DiscardUnstagedFileChanges directly
func (c *GitCommand) DiscardUnstagedFileChanges(file *File) error {
quotedFileName := c.OSCommand.Quote(file.Name)
return c.OSCommand.RunCommand("git checkout -- %s", quotedFileName)
}
// Checkout checks out a branch (or commit), with --force if you set the force arg to true
type CheckoutOptions struct {
Force bool
EnvVars []string
}
func (c *GitCommand) Checkout(branch string, options CheckoutOptions) error {
forceArg := ""
if options.Force {
forceArg = "--force "
}
return c.OSCommand.RunCommandWithOptions(fmt.Sprintf("git checkout %s %s", forceArg, branch), RunCommandOptions{EnvVars: options.EnvVars})
}
// PrepareCommitSubProcess prepares a subprocess for `git commit`
func (c *GitCommand) PrepareCommitSubProcess() *exec.Cmd {
return c.OSCommand.PrepareSubProcess("git", "commit")
}
// PrepareCommitAmendSubProcess prepares a subprocess for `git commit --amend --allow-empty`
func (c *GitCommand) PrepareCommitAmendSubProcess() *exec.Cmd {
return c.OSCommand.PrepareSubProcess("git", "commit", "--amend", "--allow-empty")
}
// GetBranchGraph gets the color-formatted graph of the log for the given branch
// Currently it limits the result to 100 commits, but when we get async stuff
// working we can do lazy loading
func (c *GitCommand) GetBranchGraph(branchName string) (string, error) {
cmdStr := c.GetBranchGraphCmdStr(branchName)
return c.OSCommand.RunCommandWithOutput(cmdStr)
}
func (c *GitCommand) GetUpstreamForBranch(branchName string) (string, error) {
output, err := c.OSCommand.RunCommandWithOutput("git rev-parse --abbrev-ref --symbolic-full-name %s@{u}", branchName)
return strings.TrimSpace(output), err
}
// Ignore adds a file to the gitignore for the repo
func (c *GitCommand) Ignore(filename string) error {
return c.OSCommand.AppendLineToFile(".gitignore", filename)
}
func (c *GitCommand) ShowCmdStr(sha string, filterPath string) string {
filterPathArg := ""
if filterPath != "" {
filterPathArg = fmt.Sprintf(" -- %s", c.OSCommand.Quote(filterPath))
}
return fmt.Sprintf("git show --color=%s --no-renames --stat -p %s %s", c.colorArg(), sha, filterPathArg)
}
func (c *GitCommand) GetBranchGraphCmdStr(branchName string) string {
return fmt.Sprintf("git log --graph --color=always --abbrev-commit --decorate --date=relative --pretty=medium %s --", branchName)
}
// GetRemoteURL returns current repo remote url
func (c *GitCommand) GetRemoteURL() string {
url, _ := c.OSCommand.RunCommandWithOutput("git config --get remote.origin.url")
return utils.TrimTrailingNewline(url)
}
// CheckRemoteBranchExists Returns remote branch
func (c *GitCommand) CheckRemoteBranchExists(branch *Branch) bool {
_, err := c.OSCommand.RunCommandWithOutput(
"git show-ref --verify -- refs/remotes/origin/%s",
branch.Name,
)
return err == nil
}
// Diff returns the diff of a file
func (c *GitCommand) Diff(file *File, plain bool, cached bool) string {
// for now we assume an error means the file was deleted
s, _ := c.OSCommand.RunCommandWithOutput(c.DiffCmdStr(file, plain, cached))
return s
}
func (c *GitCommand) DiffCmdStr(file *File, plain bool, cached bool) string {
cachedArg := ""
trackedArg := "--"
colorArg := c.colorArg()
split := strings.Split(file.Name, " -> ") // in case of a renamed file we get the new filename
fileName := c.OSCommand.Quote(split[len(split)-1])
if cached {
cachedArg = "--cached"
}
if !file.Tracked && !file.HasStagedChanges && !cached {
trackedArg = "--no-index /dev/null"
}
if plain {
colorArg = "never"
}
return fmt.Sprintf("git diff --color=%s %s %s %s", colorArg, cachedArg, trackedArg, fileName)
}
func (c *GitCommand) ApplyPatch(patch string, flags ...string) error {
c.Log.Warn(patch)
filepath := filepath.Join(c.Config.GetUserConfigDir(), utils.GetCurrentRepoName(), time.Now().Format("Jan _2 15.04.05.000000000")+".patch")
if err := c.OSCommand.CreateFileWithContent(filepath, patch); err != nil {
return err
}
flagStr := ""
for _, flag := range flags {
flagStr += " --" + flag
}
return c.OSCommand.RunCommand("git apply %s %s", flagStr, c.OSCommand.Quote(filepath))
}
func (c *GitCommand) FastForward(branchName string, remoteName string, remoteBranchName string) error {
return c.OSCommand.RunCommand("git fetch %s %s:%s", remoteName, remoteBranchName, branchName)
}
func (c *GitCommand) RunSkipEditorCommand(command string) error {
cmd := c.OSCommand.ExecutableFromString(command)
lazyGitPath := c.OSCommand.GetLazygitPath()
cmd.Env = append(
cmd.Env,
"LAZYGIT_CLIENT_COMMAND=EXIT_IMMEDIATELY",
"GIT_EDITOR="+lazyGitPath,
"EDITOR="+lazyGitPath,
"VISUAL="+lazyGitPath,
)
return c.OSCommand.RunExecutable(cmd)
}
// GenericMerge takes a commandType of "merge" or "rebase" and a command of "abort", "skip" or "continue"
// By default we skip the editor in the case where a commit will be made
func (c *GitCommand) GenericMerge(commandType string, command string) error {
err := c.RunSkipEditorCommand(
fmt.Sprintf(
"git %s --%s",
commandType,
command,
),
)
if err != nil {
if !strings.Contains(err.Error(), "no rebase in progress") {
return err
}
c.Log.Warn(err)
}
// sometimes we need to do a sequence of things in a rebase but the user needs to
// fix merge conflicts along the way. When this happens we queue up the next step
// so that after the next successful rebase continue we can continue from where we left off
if commandType == "rebase" && command == "continue" && c.onSuccessfulContinue != nil {
f := c.onSuccessfulContinue
c.onSuccessfulContinue = nil
return f()
}
if command == "abort" {
c.onSuccessfulContinue = nil
}
return nil
}
func (c *GitCommand) RewordCommit(commits []*Commit, index int) (*exec.Cmd, error) {
todo, sha, err := c.GenerateGenericRebaseTodo(commits, index, "reword")
if err != nil {
return nil, err
}
return c.PrepareInteractiveRebaseCommand(sha, todo, false)
}
func (c *GitCommand) MoveCommitDown(commits []*Commit, index int) error {
// we must ensure that we have at least two commits after the selected one
if len(commits) <= index+2 {
// assuming they aren't picking the bottom commit
return errors.New(c.Tr.SLocalize("NoRoom"))
}
todo := ""
orderedCommits := append(commits[0:index], commits[index+1], commits[index])
for _, commit := range orderedCommits {
todo = "pick " + commit.Sha + " " + commit.Name + "\n" + todo
}
cmd, err := c.PrepareInteractiveRebaseCommand(commits[index+2].Sha, todo, true)
if err != nil {
return err
}
return c.OSCommand.RunPreparedCommand(cmd)
}
func (c *GitCommand) InteractiveRebase(commits []*Commit, index int, action string) error {
todo, sha, err := c.GenerateGenericRebaseTodo(commits, index, action)
if err != nil {
return err
}
cmd, err := c.PrepareInteractiveRebaseCommand(sha, todo, true)
if err != nil {
return err
}
return c.OSCommand.RunPreparedCommand(cmd)
}
// PrepareInteractiveRebaseCommand returns the cmd for an interactive rebase
// we tell git to run lazygit to edit the todo list, and we pass the client
// lazygit a todo string to write to the todo file
func (c *GitCommand) PrepareInteractiveRebaseCommand(baseSha string, todo string, overrideEditor bool) (*exec.Cmd, error) {
ex := c.OSCommand.GetLazygitPath()
debug := "FALSE"
if c.OSCommand.Config.GetDebug() {
debug = "TRUE"
}
splitCmd := str.ToArgv(fmt.Sprintf("git rebase --interactive --autostash --keep-empty --rebase-merges %s", baseSha))
cmd := c.OSCommand.command(splitCmd[0], splitCmd[1:]...)
gitSequenceEditor := ex
if todo == "" {
gitSequenceEditor = "true"
}
cmd.Env = os.Environ()
cmd.Env = append(
cmd.Env,
"LAZYGIT_CLIENT_COMMAND=INTERACTIVE_REBASE",
"LAZYGIT_REBASE_TODO="+todo,
"DEBUG="+debug,
"LANG=en_US.UTF-8", // Force using EN as language
"LC_ALL=en_US.UTF-8", // Force using EN as language
"GIT_SEQUENCE_EDITOR="+gitSequenceEditor,
)
if overrideEditor {
cmd.Env = append(cmd.Env, "GIT_EDITOR="+ex)
}
return cmd, nil
}
func (c *GitCommand) HardReset(baseSha string) error {
return c.OSCommand.RunCommand("git reset --hard " + baseSha)
}
func (c *GitCommand) SoftReset(baseSha string) error {
return c.OSCommand.RunCommand("git reset --soft " + baseSha)
}
func (c *GitCommand) GenerateGenericRebaseTodo(commits []*Commit, actionIndex int, action string) (string, string, error) {
baseIndex := actionIndex + 1
if len(commits) <= baseIndex {
return "", "", errors.New(c.Tr.SLocalize("CannotRebaseOntoFirstCommit"))
}
if action == "squash" || action == "fixup" {
baseIndex++
if len(commits) <= baseIndex {
return "", "", errors.New(c.Tr.SLocalize("CannotSquashOntoSecondCommit"))
}
}
todo := ""
for i, commit := range commits[0:baseIndex] {
a := "pick"
if i == actionIndex {
a = action
}
todo = a + " " + commit.Sha + " " + commit.Name + "\n" + todo
}
return todo, commits[baseIndex].Sha, nil
}
// AmendTo amends the given commit with whatever files are staged
func (c *GitCommand) AmendTo(sha string) error {
if err := c.CreateFixupCommit(sha); err != nil {
return err
}
return c.SquashAllAboveFixupCommits(sha)
}
// EditRebaseTodo sets the action at a given index in the git-rebase-todo file
func (c *GitCommand) EditRebaseTodo(index int, action string) error {
fileName := fmt.Sprintf("%s/rebase-merge/git-rebase-todo", c.DotGitDir)
bytes, err := ioutil.ReadFile(fileName)
if err != nil {
return err
}
content := strings.Split(string(bytes), "\n")
commitCount := c.getTodoCommitCount(content)
// we have the most recent commit at the bottom whereas the todo file has
// it at the bottom, so we need to subtract our index from the commit count
contentIndex := commitCount - 1 - index
splitLine := strings.Split(content[contentIndex], " ")
content[contentIndex] = action + " " + strings.Join(splitLine[1:], " ")
result := strings.Join(content, "\n")
return ioutil.WriteFile(fileName, []byte(result), 0644)
}
func (c *GitCommand) getTodoCommitCount(content []string) int {
// count lines that are not blank and are not comments
commitCount := 0
for _, line := range content {
if line != "" && !strings.HasPrefix(line, "#") {
commitCount++
}
}
return commitCount
}
// MoveTodoDown moves a rebase todo item down by one position
func (c *GitCommand) MoveTodoDown(index int) error {
fileName := fmt.Sprintf("%s/rebase-merge/git-rebase-todo", c.DotGitDir)
bytes, err := ioutil.ReadFile(fileName)
if err != nil {
return err
}
content := strings.Split(string(bytes), "\n")
commitCount := c.getTodoCommitCount(content)
contentIndex := commitCount - 1 - index
rearrangedContent := append(content[0:contentIndex-1], content[contentIndex], content[contentIndex-1])
rearrangedContent = append(rearrangedContent, content[contentIndex+1:]...)
result := strings.Join(rearrangedContent, "\n")
return ioutil.WriteFile(fileName, []byte(result), 0644)
}
// Revert reverts the selected commit by sha
func (c *GitCommand) Revert(sha string) error {
return c.OSCommand.RunCommand("git revert %s", sha)
}
// CherryPickCommits begins an interactive rebase with the given shas being cherry picked onto HEAD
func (c *GitCommand) CherryPickCommits(commits []*Commit) error {
todo := ""
for _, commit := range commits {
todo = "pick " + commit.Sha + " " + commit.Name + "\n" + todo
}
cmd, err := c.PrepareInteractiveRebaseCommand("HEAD", todo, false)
if err != nil {
return err
}
return c.OSCommand.RunPreparedCommand(cmd)
}
// GetCommitFiles get the specified commit files
func (c *GitCommand) GetCommitFiles(commitSha string, patchManager *PatchManager) ([]*CommitFile, error) {
files, err := c.OSCommand.RunCommandWithOutput("git diff-tree --no-commit-id --name-only -r --no-renames %s", commitSha)
if err != nil {
return nil, err
}
commitFiles := make([]*CommitFile, 0)
for _, file := range strings.Split(strings.TrimRight(files, "\n"), "\n") {
status := UNSELECTED
if patchManager != nil && patchManager.CommitSha == commitSha {
status = patchManager.GetFileStatus(file)
}
commitFiles = append(commitFiles, &CommitFile{
Sha: commitSha,
Name: file,
DisplayString: file,
Status: status,
})
}
return commitFiles, nil
}
// ShowCommitFile get the diff of specified commit file
func (c *GitCommand) ShowCommitFile(commitSha, fileName string, plain bool) (string, error) {
cmdStr := c.ShowCommitFileCmdStr(commitSha, fileName, plain)
return c.OSCommand.RunCommandWithOutput(cmdStr)
}
func (c *GitCommand) ShowCommitFileCmdStr(commitSha, fileName string, plain bool) string {
colorArg := c.colorArg()
if plain {
colorArg = "never"
}
return fmt.Sprintf("git show --no-renames --color=%s %s -- %s", colorArg, commitSha, fileName)
}
// CheckoutFile checks out the file for the given commit
func (c *GitCommand) CheckoutFile(commitSha, fileName string) error {
return c.OSCommand.RunCommand("git checkout %s %s", commitSha, fileName)
}
// DiscardOldFileChanges discards changes to a file from an old commit
func (c *GitCommand) DiscardOldFileChanges(commits []*Commit, commitIndex int, fileName string) error {
if err := c.BeginInteractiveRebaseForCommit(commits, commitIndex); err != nil {
return err
}
// check if file exists in previous commit (this command returns an error if the file doesn't exist)
if err := c.OSCommand.RunCommand("git cat-file -e HEAD^:%s", fileName); err != nil {
if err := c.OSCommand.Remove(fileName); err != nil {
return err
}
if err := c.StageFile(fileName); err != nil {
return err
}
} else if err := c.CheckoutFile("HEAD^", fileName); err != nil {
return err
}
// amend the commit
cmd, err := c.AmendHead()
if cmd != nil {
return errors.New("received unexpected pointer to cmd")
}
if err != nil {
return err
}
// continue
return c.GenericMerge("rebase", "continue")
}
// DiscardAnyUnstagedFileChanges discards any unstages file changes via `git checkout -- .`
func (c *GitCommand) DiscardAnyUnstagedFileChanges() error {
return c.OSCommand.RunCommand("git checkout -- .")
}
// RemoveTrackedFiles will delete the given file(s) even if they are currently tracked
func (c *GitCommand) RemoveTrackedFiles(name string) error {
return c.OSCommand.RunCommand("git rm -r --cached %s", name)
}
// RemoveUntrackedFiles runs `git clean -fd`
func (c *GitCommand) RemoveUntrackedFiles() error {
return c.OSCommand.RunCommand("git clean -fd")
}
// ResetHardHead runs `git reset --hard`
func (c *GitCommand) ResetHard(ref string) error {
return c.OSCommand.RunCommand("git reset --hard " + ref)
}
// ResetSoft runs `git reset --soft HEAD`
func (c *GitCommand) ResetSoft(ref string) error {
return c.OSCommand.RunCommand("git reset --soft " + ref)
}
// CreateFixupCommit creates a commit that fixes up a previous commit
func (c *GitCommand) CreateFixupCommit(sha string) error {
return c.OSCommand.RunCommand("git commit --fixup=%s", sha)
}
// SquashAllAboveFixupCommits squashes all fixup! commits above the given one
func (c *GitCommand) SquashAllAboveFixupCommits(sha string) error {
return c.RunSkipEditorCommand(
fmt.Sprintf(
"git rebase --interactive --autostash --autosquash %s^",
sha,
),
)
}
// StashSaveStagedChanges stashes only the currently staged changes. This takes a few steps
// shoutouts to Joe on https://stackoverflow.com/questions/14759748/stashing-only-staged-changes-in-git-is-it-possible
func (c *GitCommand) StashSaveStagedChanges(message string) error {
if err := c.OSCommand.RunCommand("git stash --keep-index"); err != nil {
return err
}
if err := c.StashSave(message); err != nil {
return err
}
if err := c.OSCommand.RunCommand("git stash apply stash@{1}"); err != nil {
return err
}
if err := c.OSCommand.PipeCommands("git stash show -p", "git apply -R"); err != nil {
return err
}
if err := c.OSCommand.RunCommand("git stash drop stash@{1}"); err != nil {
return err
}
// if you had staged an untracked file, that will now appear as 'AD' in git status
// meaning it's deleted in your working tree but added in your index. Given that it's
// now safely stashed, we need to remove it.
files := c.GetStatusFiles()
for _, file := range files {
if file.ShortStatus == "AD" {
if err := c.UnStageFile(file.Name, false); err != nil {
return err
}
}
}
return nil
}
// BeginInteractiveRebaseForCommit starts an interactive rebase to edit the current
// commit and pick all others. After this you'll want to call `c.GenericMerge("rebase", "continue")`
func (c *GitCommand) BeginInteractiveRebaseForCommit(commits []*Commit, commitIndex int) error {
if len(commits)-1 < commitIndex {
return errors.New("index outside of range of commits")
}
// we can make this GPG thing possible it just means we need to do this in two parts:
// one where we handle the possibility of a credential request, and the other
// where we continue the rebase
if c.usingGpg() {
return errors.New(c.Tr.SLocalize("DisabledForGPG"))
}
todo, sha, err := c.GenerateGenericRebaseTodo(commits, commitIndex, "edit")
if err != nil {
return err
}
cmd, err := c.PrepareInteractiveRebaseCommand(sha, todo, true)
if err != nil {
return err
}
if err := c.OSCommand.RunPreparedCommand(cmd); err != nil {
return err
}
return nil
}
func (c *GitCommand) SetUpstreamBranch(upstream string) error {
return c.OSCommand.RunCommand("git branch -u %s", upstream)
}
func (c *GitCommand) AddRemote(name string, url string) error {
return c.OSCommand.RunCommand("git remote add %s %s", name, url)
}
func (c *GitCommand) RemoveRemote(name string) error {
return c.OSCommand.RunCommand("git remote remove %s", name)
}
func (c *GitCommand) IsHeadDetached() bool {
err := c.OSCommand.RunCommand("git symbolic-ref -q HEAD")
return err != nil
}
func (c *GitCommand) DeleteRemoteBranch(remoteName string, branchName string) error {
return c.OSCommand.RunCommand("git push %s --delete %s", remoteName, branchName)
}
func (c *GitCommand) SetBranchUpstream(remoteName string, remoteBranchName string, branchName string) error {
return c.OSCommand.RunCommand("git branch --set-upstream-to=%s/%s %s", remoteName, remoteBranchName, branchName)
}
func (c *GitCommand) RenameRemote(oldRemoteName string, newRemoteName string) error {
return c.OSCommand.RunCommand("git remote rename %s %s", oldRemoteName, newRemoteName)
}
func (c *GitCommand) UpdateRemoteUrl(remoteName string, updatedUrl string) error {
return c.OSCommand.RunCommand("git remote set-url %s %s", remoteName, updatedUrl)
}
func (c *GitCommand) CreateLightweightTag(tagName string, commitSha string) error {
return c.OSCommand.RunCommand("git tag %s %s", tagName, commitSha)
}
func (c *GitCommand) DeleteTag(tagName string) error {
return c.OSCommand.RunCommand("git tag -d %s", tagName)
}
func (c *GitCommand) PushTag(remoteName string, tagName string) error {
return c.OSCommand.RunCommand("git push %s %s", remoteName, tagName)
}
func (c *GitCommand) FetchRemote(remoteName string) error {
return c.OSCommand.RunCommand("git fetch %s", remoteName)
}
// GetReflogCommits only returns the new reflog commits since the given lastReflogCommit
// if none is passed (i.e. it's value is nil) then we get all the reflog commits
func (c *GitCommand) GetReflogCommits(lastReflogCommit *Commit, filterPath string) ([]*Commit, bool, error) {
commits := make([]*Commit, 0)
re := regexp.MustCompile(`(\w+).*HEAD@\{([^\}]+)\}: (.*)`)
filterPathArg := ""
if filterPath != "" {
filterPathArg = fmt.Sprintf(" --follow -- %s", c.OSCommand.Quote(filterPath))
}
cmd := c.OSCommand.ExecutableFromString(fmt.Sprintf("git reflog --abbrev=20 --date=unix %s", filterPathArg))
onlyObtainedNewReflogCommits := false
err := RunLineOutputCmd(cmd, func(line string) (bool, error) {
match := re.FindStringSubmatch(line)
if len(match) <= 1 {
return false, nil
}
unixTimestamp, _ := strconv.Atoi(match[2])
commit := &Commit{
Sha: match[1],
Name: match[3],
UnixTimestamp: int64(unixTimestamp),
Status: "reflog",
}
if lastReflogCommit != nil && commit.Sha == lastReflogCommit.Sha && commit.UnixTimestamp == lastReflogCommit.UnixTimestamp {
onlyObtainedNewReflogCommits = true
// after this point we already have these reflogs loaded so we'll simply return the new ones
return true, nil
}
commits = append(commits, commit)
return false, nil
})
if err != nil {
return nil, false, err
}
return commits, onlyObtainedNewReflogCommits, nil
}
func (c *GitCommand) ConfiguredPager() string {
if os.Getenv("GIT_PAGER") != "" {
return os.Getenv("GIT_PAGER")
}
if os.Getenv("PAGER") != "" {
return os.Getenv("PAGER")
}
output, err := c.OSCommand.RunCommandWithOutput("git config --get-all core.pager")
if err != nil {
return ""
}
trimmedOutput := strings.TrimSpace(output)
return strings.Split(trimmedOutput, "\n")[0]
}
func (c *GitCommand) GetPager(width int) string {
useConfig := c.Config.GetUserConfig().GetBool("git.paging.useConfig")
if useConfig {
pager := c.ConfiguredPager()
return strings.Split(pager, "| less")[0]
}
templateValues := map[string]string{
"columnWidth": strconv.Itoa(width/2 - 6),
}
pagerTemplate := c.Config.GetUserConfig().GetString("git.paging.pager")
return utils.ResolvePlaceholderString(pagerTemplate, templateValues)
}
func (c *GitCommand) colorArg() string {
return c.Config.GetUserConfig().GetString("git.paging.colorArg")
}
func (c *GitCommand) RenameBranch(oldName string, newName string) error {
return c.OSCommand.RunCommand("git branch --move %s %s", oldName, newName)
}
func (c *GitCommand) WorkingTreeState() string {
rebaseMode, _ := c.RebaseMode()
if rebaseMode != "" {
return "rebasing"
}
merging, _ := c.IsInMergeState()
if merging {
return "merging"
}
return "normal"
}
| [
"\"GIT_PAGER\"",
"\"GIT_PAGER\"",
"\"PAGER\"",
"\"PAGER\""
]
| []
| [
"PAGER",
"GIT_PAGER"
]
| [] | ["PAGER", "GIT_PAGER"] | go | 2 | 0 | |
tests/models/test_cli.py | import json
import os
import subprocess
import sys
import numpy as np
import pandas as pd
import pytest
import re
import sklearn
import sklearn.datasets
import sklearn.neighbors
from unittest import mock
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import mlflow
from mlflow import pyfunc
import mlflow.sklearn
from mlflow.utils.file_utils import TempDir, path_to_local_file_uri
from mlflow.utils.environment import _mlflow_conda_env
from mlflow.utils import PYTHON_VERSION
from tests.models import test_pyfunc
from tests.helper_functions import (
pyfunc_build_image,
pyfunc_serve_from_docker_image,
pyfunc_serve_from_docker_image_with_env_override,
RestEndpoint,
get_safe_port,
pyfunc_serve_and_score_model,
)
from mlflow.protos.databricks_pb2 import ErrorCode, BAD_REQUEST
from mlflow.pyfunc.scoring_server import (
CONTENT_TYPE_JSON_SPLIT_ORIENTED,
CONTENT_TYPE_JSON,
CONTENT_TYPE_CSV,
)
# NB: for now, windows tests do not have conda available.
no_conda = ["--no-conda"] if sys.platform == "win32" else []
# NB: need to install mlflow since the pip version does not have mlflow models cli.
install_mlflow = ["--install-mlflow"] if not no_conda else []
extra_options = no_conda + install_mlflow
gunicorn_options = "--timeout 60 -w 5"
@pytest.fixture(scope="module")
def iris_data():
iris = sklearn.datasets.load_iris()
x = iris.data[:, :2]
y = iris.target
return x, y
@pytest.fixture(scope="module")
def sk_model(iris_data):
x, y = iris_data
knn_model = sklearn.neighbors.KNeighborsClassifier()
knn_model.fit(x, y)
return knn_model
@pytest.mark.large
def test_predict_with_old_mlflow_in_conda_and_with_orient_records(iris_data):
if no_conda:
pytest.skip("This test needs conda.")
# TODO: Enable this test after 1.0 is out to ensure we do not break the serve / predict
# TODO: Also add a test for serve, not just predict.
pytest.skip("TODO: enable this after 1.0 release is out.")
x, _ = iris_data
with TempDir() as tmp:
input_records_path = tmp.path("input_records.json")
pd.DataFrame(x).to_json(input_records_path, orient="records")
output_json_path = tmp.path("output.json")
test_model_path = tmp.path("test_model")
test_model_conda_path = tmp.path("conda.yml")
# create env with old mlflow!
_mlflow_conda_env(
path=test_model_conda_path,
additional_pip_deps=["mlflow=={}".format(test_pyfunc.MLFLOW_VERSION)],
)
pyfunc.save_model(
path=test_model_path,
loader_module=test_pyfunc.__name__.split(".")[-1],
code_path=[test_pyfunc.__file__],
conda_env=test_model_conda_path,
)
# explicit json format with orient records
p = subprocess.Popen(
[
"mlflow",
"models",
"predict",
"-m",
path_to_local_file_uri(test_model_path),
"-i",
input_records_path,
"-o",
output_json_path,
"-t",
"json",
"--json-format",
"records",
]
+ no_conda
)
assert 0 == p.wait()
actual = pd.read_json(output_json_path, orient="records")
actual = actual[actual.columns[0]].values
expected = test_pyfunc.PyFuncTestModel(check_version=False).predict(df=pd.DataFrame(x))
assert all(expected == actual)
@pytest.mark.large
@pytest.mark.allow_infer_pip_requirements_fallback
def test_mlflow_is_not_installed_unless_specified():
if no_conda:
pytest.skip("This test requires conda.")
with TempDir(chdr=True) as tmp:
fake_model_path = tmp.path("fake_model")
mlflow.pyfunc.save_model(fake_model_path, loader_module=__name__)
# Overwrite the logged `conda.yaml` to remove mlflow.
_mlflow_conda_env(path=os.path.join(fake_model_path, "conda.yaml"), install_mlflow=False)
# The following should fail because there should be no mlflow in the env:
p = subprocess.Popen(
["mlflow", "models", "predict", "-m", fake_model_path],
stderr=subprocess.PIPE,
cwd=tmp.path(""),
)
_, stderr = p.communicate()
stderr = stderr.decode("utf-8")
print(stderr)
assert p.wait() != 0
if PYTHON_VERSION.startswith("3"):
assert "ModuleNotFoundError: No module named 'mlflow'" in stderr
else:
assert "ImportError: No module named mlflow.pyfunc.scoring_server" in stderr
@pytest.mark.large
def test_model_with_no_deployable_flavors_fails_pollitely():
from mlflow.models import Model
with TempDir(chdr=True) as tmp:
m = Model(
artifact_path=None,
run_id=None,
utc_time_created="now",
flavors={"some": {}, "useless": {}, "flavors": {}},
)
os.mkdir(tmp.path("model"))
m.save(tmp.path("model", "MLmodel"))
# The following should fail because there should be no suitable flavor
p = subprocess.Popen(
["mlflow", "models", "predict", "-m", tmp.path("model")],
stderr=subprocess.PIPE,
cwd=tmp.path(""),
)
_, stderr = p.communicate()
stderr = stderr.decode("utf-8")
print(stderr)
assert p.wait() != 0
assert "No suitable flavor backend was found for the model." in stderr
@pytest.mark.large
def test_serve_gunicorn_opts(iris_data, sk_model):
if sys.platform == "win32":
pytest.skip("This test requires gunicorn which is not available on windows.")
with mlflow.start_run() as active_run:
mlflow.sklearn.log_model(sk_model, "model", registered_model_name="imlegit")
run_id = active_run.info.run_id
model_uris = [
"models:/{name}/{stage}".format(name="imlegit", stage="None"),
"runs:/{run_id}/model".format(run_id=run_id),
]
for model_uri in model_uris:
with TempDir() as tpm:
output_file_path = tpm.path("stoudt")
with open(output_file_path, "w") as output_file:
x, _ = iris_data
scoring_response = pyfunc_serve_and_score_model(
model_uri,
pd.DataFrame(x),
content_type=CONTENT_TYPE_JSON_SPLIT_ORIENTED,
stdout=output_file,
extra_args=["-w", "3"],
)
with open(output_file_path, "r") as output_file:
stdout = output_file.read()
actual = pd.read_json(scoring_response.content.decode("utf-8"), orient="records")
actual = actual[actual.columns[0]].values
expected = sk_model.predict(x)
assert all(expected == actual)
expected_command_pattern = re.compile(
("gunicorn.*-w 3.*mlflow.pyfunc.scoring_server.wsgi:app")
)
assert expected_command_pattern.search(stdout) is not None
@pytest.mark.large
def test_predict(iris_data, sk_model):
with TempDir(chdr=True) as tmp:
with mlflow.start_run() as active_run:
mlflow.sklearn.log_model(sk_model, "model", registered_model_name="impredicting")
model_uri = "runs:/{run_id}/model".format(run_id=active_run.info.run_id)
model_registry_uri = "models:/{name}/{stage}".format(name="impredicting", stage="None")
input_json_path = tmp.path("input.json")
input_csv_path = tmp.path("input.csv")
output_json_path = tmp.path("output.json")
x, _ = iris_data
pd.DataFrame(x).to_json(input_json_path, orient="split")
pd.DataFrame(x).to_csv(input_csv_path, index=False)
# Test with no conda & model registry URI
env_with_tracking_uri = os.environ.copy()
env_with_tracking_uri.update(MLFLOW_TRACKING_URI=mlflow.get_tracking_uri())
p = subprocess.Popen(
[
"mlflow",
"models",
"predict",
"-m",
model_registry_uri,
"-i",
input_json_path,
"-o",
output_json_path,
"--no-conda",
],
stderr=subprocess.PIPE,
env=env_with_tracking_uri,
)
assert p.wait() == 0
actual = pd.read_json(output_json_path, orient="records")
actual = actual[actual.columns[0]].values
expected = sk_model.predict(x)
assert all(expected == actual)
# With conda + --install-mlflow
p = subprocess.Popen(
[
"mlflow",
"models",
"predict",
"-m",
model_uri,
"-i",
input_json_path,
"-o",
output_json_path,
]
+ extra_options,
env=env_with_tracking_uri,
)
assert 0 == p.wait()
actual = pd.read_json(output_json_path, orient="records")
actual = actual[actual.columns[0]].values
expected = sk_model.predict(x)
assert all(expected == actual)
# explicit json format with default orient (should be split)
p = subprocess.Popen(
[
"mlflow",
"models",
"predict",
"-m",
model_uri,
"-i",
input_json_path,
"-o",
output_json_path,
"-t",
"json",
]
+ extra_options,
env=env_with_tracking_uri,
)
assert 0 == p.wait()
actual = pd.read_json(output_json_path, orient="records")
actual = actual[actual.columns[0]].values
expected = sk_model.predict(x)
assert all(expected == actual)
# explicit json format with orient==split
p = subprocess.Popen(
[
"mlflow",
"models",
"predict",
"-m",
model_uri,
"-i",
input_json_path,
"-o",
output_json_path,
"-t",
"json",
"--json-format",
"split",
]
+ extra_options,
env=env_with_tracking_uri,
)
assert 0 == p.wait()
actual = pd.read_json(output_json_path, orient="records")
actual = actual[actual.columns[0]].values
expected = sk_model.predict(x)
assert all(expected == actual)
# read from stdin, write to stdout.
p = subprocess.Popen(
["mlflow", "models", "predict", "-m", model_uri, "-t", "json", "--json-format", "split"]
+ extra_options,
universal_newlines=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=sys.stderr,
env=env_with_tracking_uri,
)
with open(input_json_path, "r") as f:
stdout, _ = p.communicate(f.read())
assert 0 == p.wait()
actual = pd.read_json(StringIO(stdout), orient="records")
actual = actual[actual.columns[0]].values
expected = sk_model.predict(x)
assert all(expected == actual)
# NB: We do not test orient=records here because records may loose column ordering.
# orient == records is tested in other test with simpler model.
# csv
p = subprocess.Popen(
[
"mlflow",
"models",
"predict",
"-m",
model_uri,
"-i",
input_csv_path,
"-o",
output_json_path,
"-t",
"csv",
]
+ extra_options,
env=env_with_tracking_uri,
)
assert 0 == p.wait()
actual = pd.read_json(output_json_path, orient="records")
actual = actual[actual.columns[0]].values
expected = sk_model.predict(x)
assert all(expected == actual)
@pytest.mark.large
def test_prepare_env_passes(sk_model):
if no_conda:
pytest.skip("This test requires conda.")
with TempDir(chdr=True):
with mlflow.start_run() as active_run:
mlflow.sklearn.log_model(sk_model, "model")
model_uri = "runs:/{run_id}/model".format(run_id=active_run.info.run_id)
# Test with no conda
p = subprocess.Popen(
["mlflow", "models", "prepare-env", "-m", model_uri, "--no-conda"],
stderr=subprocess.PIPE,
)
assert p.wait() == 0
# With conda
p = subprocess.Popen(
["mlflow", "models", "prepare-env", "-m", model_uri], stderr=subprocess.PIPE
)
assert p.wait() == 0
# Should be idempotent
p = subprocess.Popen(
["mlflow", "models", "prepare-env", "-m", model_uri], stderr=subprocess.PIPE
)
assert p.wait() == 0
@pytest.mark.large
def test_prepare_env_fails(sk_model):
if no_conda:
pytest.skip("This test requires conda.")
with TempDir(chdr=True):
with mlflow.start_run() as active_run:
mlflow.sklearn.log_model(
sk_model, "model", conda_env={"dependencies": ["mlflow-does-not-exist-dep==abc"]}
)
model_uri = "runs:/{run_id}/model".format(run_id=active_run.info.run_id)
# Test with no conda
p = subprocess.Popen(["mlflow", "models", "prepare-env", "-m", model_uri, "--no-conda"])
assert p.wait() == 0
# With conda - should fail due to bad conda environment.
p = subprocess.Popen(["mlflow", "models", "prepare-env", "-m", model_uri])
assert p.wait() != 0
@pytest.mark.large
@pytest.mark.parametrize("enable_mlserver", [True, False])
def test_build_docker(iris_data, sk_model, enable_mlserver):
with mlflow.start_run() as active_run:
if enable_mlserver:
# MLServer requires Python 3.7, so we'll force that Python version
with mock.patch("mlflow.utils.environment.PYTHON_VERSION", "3.7"):
mlflow.sklearn.log_model(sk_model, "model")
else:
mlflow.sklearn.log_model(sk_model, "model")
model_uri = "runs:/{run_id}/model".format(run_id=active_run.info.run_id)
x, _ = iris_data
df = pd.DataFrame(x)
extra_args = ["--install-mlflow"]
if enable_mlserver:
extra_args.append("--enable-mlserver")
image_name = pyfunc_build_image(model_uri, extra_args=extra_args)
host_port = get_safe_port()
scoring_proc = pyfunc_serve_from_docker_image(image_name, host_port)
_validate_with_rest_endpoint(scoring_proc, host_port, df, x, sk_model, enable_mlserver)
@pytest.mark.large
@pytest.mark.parametrize("enable_mlserver", [True, False])
def test_build_docker_with_env_override(iris_data, sk_model, enable_mlserver):
with mlflow.start_run() as active_run:
if enable_mlserver:
# MLServer requires Python 3.7, so we'll force that Python version
with mock.patch("mlflow.utils.environment.PYTHON_VERSION", "3.7"):
mlflow.sklearn.log_model(sk_model, "model")
else:
mlflow.sklearn.log_model(sk_model, "model")
model_uri = "runs:/{run_id}/model".format(run_id=active_run.info.run_id)
x, _ = iris_data
df = pd.DataFrame(x)
extra_args = ["--install-mlflow"]
if enable_mlserver:
extra_args.append("--enable-mlserver")
image_name = pyfunc_build_image(model_uri, extra_args=extra_args)
host_port = get_safe_port()
scoring_proc = pyfunc_serve_from_docker_image_with_env_override(
image_name, host_port, gunicorn_options
)
_validate_with_rest_endpoint(scoring_proc, host_port, df, x, sk_model, enable_mlserver)
def _validate_with_rest_endpoint(scoring_proc, host_port, df, x, sk_model, enable_mlserver=False):
with RestEndpoint(proc=scoring_proc, port=host_port) as endpoint:
for content_type in [CONTENT_TYPE_JSON_SPLIT_ORIENTED, CONTENT_TYPE_CSV, CONTENT_TYPE_JSON]:
scoring_response = endpoint.invoke(df, content_type)
assert scoring_response.status_code == 200, (
"Failed to serve prediction, got " "response %s" % scoring_response.text
)
np.testing.assert_array_equal(
np.array(json.loads(scoring_response.text)), sk_model.predict(x)
)
# Try examples of bad input, verify we get a non-200 status code
for content_type in [CONTENT_TYPE_JSON_SPLIT_ORIENTED, CONTENT_TYPE_CSV, CONTENT_TYPE_JSON]:
scoring_response = endpoint.invoke(data="", content_type=content_type)
expected_status_code = 500 if enable_mlserver else 400
assert scoring_response.status_code == expected_status_code, (
"Expected server failure with error code %s, got response with status code %s "
"and body %s"
% (expected_status_code, scoring_response.status_code, scoring_response.text)
)
if enable_mlserver:
# MLServer returns a different set of errors.
# Skip these assertions until this issue gets tackled:
# https://github.com/SeldonIO/MLServer/issues/360)
continue
scoring_response_dict = json.loads(scoring_response.content)
assert "error_code" in scoring_response_dict
assert scoring_response_dict["error_code"] == ErrorCode.Name(BAD_REQUEST)
assert "message" in scoring_response_dict
assert "stack_trace" in scoring_response_dict
| []
| []
| []
| [] | [] | python | 0 | 0 | |
src/testcases/CWE369_Divide_by_Zero/s01/CWE369_Divide_by_Zero__float_Environment_divide_12.java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__float_Environment_divide_12.java
Label Definition File: CWE369_Divide_by_Zero__float.label.xml
Template File: sources-sinks-12.tmpl.java
*/
/*
* @description
* CWE: 369 Divide by zero
* BadSource: Environment Read data from an environment variable
* GoodSource: A hardcoded non-zero number (two)
* Sinks: divide
* GoodSink: Check for zero before dividing
* BadSink : Dividing by a value that may be zero
* Flow Variant: 12 Control flow: if(IO.staticReturnsTrueOrFalse())
*
* */
package testcases.CWE369_Divide_by_Zero.s01;
import testcasesupport.*;
import java.util.logging.Level;
public class CWE369_Divide_by_Zero__float_Environment_divide_12 extends AbstractTestCase
{
public void bad() throws Throwable
{
float data;
if(IO.staticReturnsTrueOrFalse())
{
data = -1.0f; /* Initialize data */
/* get environment variable ADD */
/* POTENTIAL FLAW: Read data from an environment variable */
{
String stringNumber = System.getenv("ADD");
if (stringNumber != null)
{
try
{
data = Float.parseFloat(stringNumber.trim());
}
catch (NumberFormatException exceptNumberFormat)
{
IO.logger.log(Level.WARNING, "Number format exception parsing data from string", exceptNumberFormat);
}
}
}
}
else
{
/* FIX: Use a hardcoded number that won't a divide by zero */
data = 2.0f;
}
if(IO.staticReturnsTrueOrFalse())
{
/* POTENTIAL FLAW: Possibly divide by zero */
int result = (int)(100.0 / data);
IO.writeLine(result);
}
else
{
/* FIX: Check for value of or near zero before dividing */
if (Math.abs(data) > 0.000001)
{
int result = (int)(100.0 / data);
IO.writeLine(result);
}
else
{
IO.writeLine("This would result in a divide by zero");
}
}
}
/* goodG2B() - use goodsource and badsink by changing the first "if" so that
* both branches use the GoodSource */
private void goodG2B() throws Throwable
{
float data;
if(IO.staticReturnsTrueOrFalse())
{
/* FIX: Use a hardcoded number that won't a divide by zero */
data = 2.0f;
}
else
{
/* FIX: Use a hardcoded number that won't a divide by zero */
data = 2.0f;
}
if(IO.staticReturnsTrueOrFalse())
{
/* POTENTIAL FLAW: Possibly divide by zero */
int result = (int)(100.0 / data);
IO.writeLine(result);
}
else
{
/* POTENTIAL FLAW: Possibly divide by zero */
int result = (int)(100.0 / data);
IO.writeLine(result);
}
}
/* goodB2G() - use badsource and goodsink by changing the second "if" so that
* both branches use the GoodSink */
private void goodB2G() throws Throwable
{
float data;
if(IO.staticReturnsTrueOrFalse())
{
data = -1.0f; /* Initialize data */
/* get environment variable ADD */
/* POTENTIAL FLAW: Read data from an environment variable */
{
String stringNumber = System.getenv("ADD");
if (stringNumber != null)
{
try
{
data = Float.parseFloat(stringNumber.trim());
}
catch (NumberFormatException exceptNumberFormat)
{
IO.logger.log(Level.WARNING, "Number format exception parsing data from string", exceptNumberFormat);
}
}
}
}
else
{
data = -1.0f; /* Initialize data */
/* get environment variable ADD */
/* POTENTIAL FLAW: Read data from an environment variable */
{
String stringNumber = System.getenv("ADD");
if (stringNumber != null)
{
try
{
data = Float.parseFloat(stringNumber.trim());
}
catch (NumberFormatException exceptNumberFormat)
{
IO.logger.log(Level.WARNING, "Number format exception parsing data from string", exceptNumberFormat);
}
}
}
}
if(IO.staticReturnsTrueOrFalse())
{
/* FIX: Check for value of or near zero before dividing */
if (Math.abs(data) > 0.000001)
{
int result = (int)(100.0 / data);
IO.writeLine(result);
}
else
{
IO.writeLine("This would result in a divide by zero");
}
}
else
{
/* FIX: Check for value of or near zero before dividing */
if (Math.abs(data) > 0.000001)
{
int result = (int)(100.0 / data);
IO.writeLine(result);
}
else
{
IO.writeLine("This would result in a divide by zero");
}
}
}
public void good() throws Throwable
{
goodG2B();
goodB2G();
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
| [
"\"ADD\"",
"\"ADD\"",
"\"ADD\""
]
| []
| [
"ADD"
]
| [] | ["ADD"] | java | 1 | 0 | |
pkg/settings/setting.go | package settings
import (
"encoding/json"
"fmt"
"os"
"regexp"
"strconv"
"strings"
v32 "github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"
authsettings "github.com/rancher/rancher/pkg/auth/settings"
fleetconst "github.com/rancher/rancher/pkg/fleet"
"github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
)
const RancherVersionDev = "2.6.99"
var (
releasePattern = regexp.MustCompile("^v[0-9]")
settings = map[string]Setting{}
provider Provider
InjectDefaults string
AgentImage = NewSetting("agent-image", "rancher/rancher-agent:v2.6-head")
AgentRolloutTimeout = NewSetting("agent-rollout-timeout", "300s")
AgentRolloutWait = NewSetting("agent-rollout-wait", "true")
AuthImage = NewSetting("auth-image", v32.ToolsSystemImages.AuthSystemImages.KubeAPIAuth)
AuthTokenMaxTTLMinutes = NewSetting("auth-token-max-ttl-minutes", "0") // never expire
AuthorizationCacheTTLSeconds = NewSetting("authorization-cache-ttl-seconds", "10")
AuthorizationDenyCacheTTLSeconds = NewSetting("authorization-deny-cache-ttl-seconds", "10")
AzureGroupCacheSize = NewSetting("azure-group-cache-size", "10000")
CACerts = NewSetting("cacerts", "")
CLIURLDarwin = NewSetting("cli-url-darwin", "https://releases.rancher.com/cli/v1.0.0-alpha8/rancher-darwin-amd64-v1.0.0-alpha8.tar.gz")
CLIURLLinux = NewSetting("cli-url-linux", "https://releases.rancher.com/cli/v1.0.0-alpha8/rancher-linux-amd64-v1.0.0-alpha8.tar.gz")
CLIURLWindows = NewSetting("cli-url-windows", "https://releases.rancher.com/cli/v1.0.0-alpha8/rancher-windows-386-v1.0.0-alpha8.zip")
ClusterControllerStartCount = NewSetting("cluster-controller-start-count", "50")
EngineInstallURL = NewSetting("engine-install-url", "https://releases.rancher.com/install-docker/20.10.sh")
EngineISOURL = NewSetting("engine-iso-url", "https://releases.rancher.com/os/latest/rancheros-vmware.iso")
EngineNewestVersion = NewSetting("engine-newest-version", "v17.12.0")
EngineSupportedRange = NewSetting("engine-supported-range", "~v1.11.2 || ~v1.12.0 || ~v1.13.0 || ~v17.03.0 || ~v17.06.0 || ~v17.09.0 || ~v18.06.0 || ~v18.09.0 || ~v19.03.0 || ~v20.10.0 ")
FirstLogin = NewSetting("first-login", "true")
GlobalRegistryEnabled = NewSetting("global-registry-enabled", "false")
GithubProxyAPIURL = NewSetting("github-proxy-api-url", "https://api.github.com")
HelmVersion = NewSetting("helm-version", "dev")
HelmMaxHistory = NewSetting("helm-max-history", "10")
IngressIPDomain = NewSetting("ingress-ip-domain", "sslip.io")
InstallUUID = NewSetting("install-uuid", "")
InternalServerURL = NewSetting("internal-server-url", "")
InternalCACerts = NewSetting("internal-cacerts", "")
IsRKE = NewSetting("is-rke", "")
JailerTimeout = NewSetting("jailer-timeout", "60")
KubeconfigGenerateToken = NewSetting("kubeconfig-generate-token", "true")
KubeconfigTokenTTLMinutes = NewSetting("kubeconfig-token-ttl-minutes", "960") // 16 hours
KubernetesVersion = NewSetting("k8s-version", "")
KubernetesVersionToServiceOptions = NewSetting("k8s-version-to-service-options", "")
KubernetesVersionToSystemImages = NewSetting("k8s-version-to-images", "")
KubernetesVersionsCurrent = NewSetting("k8s-versions-current", "")
KubernetesVersionsDeprecated = NewSetting("k8s-versions-deprecated", "")
KDMBranch = NewSetting("kdm-branch", "dev-v2.6")
MachineVersion = NewSetting("machine-version", "dev")
Namespace = NewSetting("namespace", os.Getenv("CATTLE_NAMESPACE"))
PasswordMinLength = NewSetting("password-min-length", "12")
PeerServices = NewSetting("peer-service", os.Getenv("CATTLE_PEER_SERVICE"))
RDNSServerBaseURL = NewSetting("rdns-base-url", "https://api.lb.rancher.cloud/v1")
RkeVersion = NewSetting("rke-version", "")
RkeMetadataConfig = NewSetting("rke-metadata-config", getMetadataConfig())
ServerImage = NewSetting("server-image", "rancher/rancher")
ServerURL = NewSetting("server-url", "")
ServerVersion = NewSetting("server-version", "dev")
SystemAgentVersion = NewSetting("system-agent-version", "")
WinsAgentVersion = NewSetting("wins-agent-version", "")
CSIProxyAgentVersion = NewSetting("csi-proxy-agent-version", "")
CSIProxyAgentURL = NewSetting("csi-proxy-agent-url", "https://acs-mirror.azureedge.net/csi-proxy/%[1]s/binaries/csi-proxy-%[1]s.tar.gz")
SystemAgentInstallScript = NewSetting("system-agent-install-script", "https://raw.githubusercontent.com/rancher/system-agent/v0.2.3/install.sh")
WinsAgentInstallScript = NewSetting("wins-agent-install-script", "https://raw.githubusercontent.com/rancher/wins/v0.2.0/install.ps1")
SystemAgentInstallerImage = NewSetting("system-agent-installer-image", "rancher/system-agent-installer-")
SystemAgentUpgradeImage = NewSetting("system-agent-upgrade-image", "")
SystemDefaultRegistry = NewSetting("system-default-registry", "")
SystemNamespaces = NewSetting("system-namespaces", "kube-system,kube-public,cattle-system,cattle-alerting,cattle-logging,cattle-pipeline,cattle-prometheus,ingress-nginx,cattle-global-data,cattle-istio,kube-node-lease,cert-manager,cattle-global-nt,security-scan,cattle-fleet-system,cattle-fleet-local-system,calico-system,tigera-operator,cattle-impersonation-system,rancher-operator-system")
SystemUpgradeControllerChartVersion = NewSetting("system-upgrade-controller-chart-version", "")
TelemetryOpt = NewSetting("telemetry-opt", "")
TLSMinVersion = NewSetting("tls-min-version", "1.2")
TLSCiphers = NewSetting("tls-ciphers", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305")
UIBanners = NewSetting("ui-banners", "{}")
UIBrand = NewSetting("ui-brand", "")
UIDefaultLanding = NewSetting("ui-default-landing", "vue")
UIFeedBackForm = NewSetting("ui-feedback-form", "")
UIIndex = NewSetting("ui-index", "https://releases.rancher.com/ui/latest2/index.html")
UIPath = NewSetting("ui-path", "/usr/share/rancher/ui")
UIDashboardIndex = NewSetting("ui-dashboard-index", "https://releases.rancher.com/dashboard/latest/index.html")
UIDashboardPath = NewSetting("ui-dashboard-path", "/usr/share/rancher/ui-dashboard")
UIPreferred = NewSetting("ui-preferred", "vue")
UIOfflinePreferred = NewSetting("ui-offline-preferred", "dynamic")
UIIssues = NewSetting("ui-issues", "")
UIPL = NewSetting("ui-pl", "rancher")
UICommunityLinks = NewSetting("ui-community-links", "true")
UIKubernetesSupportedVersions = NewSetting("ui-k8s-supported-versions-range", ">= 1.11.0 <=1.14.x")
UIKubernetesDefaultVersion = NewSetting("ui-k8s-default-version-range", "<=1.14.x")
WhitelistDomain = NewSetting("whitelist-domain", "forums.rancher.com")
WhitelistEnvironmentVars = NewSetting("whitelist-envvars", "HTTP_PROXY,HTTPS_PROXY,NO_PROXY")
AuthUserInfoResyncCron = NewSetting("auth-user-info-resync-cron", "0 0 * * *")
AuthUserSessionTTLMinutes = NewSetting("auth-user-session-ttl-minutes", "960") // 16 hours
AuthUserInfoMaxAgeSeconds = NewSetting("auth-user-info-max-age-seconds", "3600") // 1 hour
APIUIVersion = NewSetting("api-ui-version", "1.1.6") // Please update the CATTLE_API_UI_VERSION in package/Dockerfile when updating the version here.
RotateCertsIfExpiringInDays = NewSetting("rotate-certs-if-expiring-in-days", "7") // 7 days
ClusterTemplateEnforcement = NewSetting("cluster-template-enforcement", "false")
InitialDockerRootDir = NewSetting("initial-docker-root-dir", "/var/lib/docker")
SystemCatalog = NewSetting("system-catalog", "external") // Options are 'external' or 'bundled'
ChartDefaultBranch = NewSetting("chart-default-branch", "dev-v2.6")
PartnerChartDefaultBranch = NewSetting("partner-chart-default-branch", "main")
RKE2ChartDefaultBranch = NewSetting("rke2-chart-default-branch", "main")
FleetDefaultWorkspaceName = NewSetting("fleet-default-workspace-name", fleetconst.ClustersDefaultNamespace) // fleetWorkspaceName to assign to clusters with none
ShellImage = NewSetting("shell-image", "rancher/shell:v0.1.16")
IgnoreNodeName = NewSetting("ignore-node-name", "") // nodes to ignore when syncing v1.node to v3.node
NoDefaultAdmin = NewSetting("no-default-admin", "")
RestrictedDefaultAdmin = NewSetting("restricted-default-admin", "false") // When bootstrapping the admin for the first time, give them the global role restricted-admin
AKSUpstreamRefresh = NewSetting("aks-refresh", "300")
EKSUpstreamRefreshCron = NewSetting("eks-refresh-cron", "*/5 * * * *") // EKSUpstreamRefreshCron is deprecated and will be replaced by EKSUpstreamRefresh
EKSUpstreamRefresh = NewSetting("eks-refresh", "300")
GKEUpstreamRefresh = NewSetting("gke-refresh", "300")
HideLocalCluster = NewSetting("hide-local-cluster", "false")
MachineProvisionImage = NewSetting("machine-provision-image", "rancher/machine:v0.15.0-rancher83")
SystemFeatureChartRefreshSeconds = NewSetting("system-feature-chart-refresh-seconds", "900")
FleetMinVersion = NewSetting("fleet-min-version", "")
RancherWebhookMinVersion = NewSetting("rancher-webhook-min-version", "")
Rke2DefaultVersion = NewSetting("rke2-default-version", "")
K3sDefaultVersion = NewSetting("k3s-default-version", "")
)
func FullShellImage() string {
return PrefixPrivateRegistry(ShellImage.Get())
}
func PrefixPrivateRegistry(image string) string {
private := SystemDefaultRegistry.Get()
if private == "" {
return image
}
return private + "/" + image
}
func IsRelease() bool {
return !strings.Contains(ServerVersion.Get(), "head") && releasePattern.MatchString(ServerVersion.Get())
}
func init() {
// setup auth setting
authsettings.AuthUserInfoResyncCron = AuthUserInfoResyncCron
authsettings.AuthUserSessionTTLMinutes = AuthUserSessionTTLMinutes
authsettings.AuthUserInfoMaxAgeSeconds = AuthUserInfoMaxAgeSeconds
authsettings.FirstLogin = FirstLogin
if InjectDefaults == "" {
return
}
defaults := map[string]string{}
if err := json.Unmarshal([]byte(InjectDefaults), &defaults); err != nil {
return
}
for name, defaultValue := range defaults {
value, ok := settings[name]
if !ok {
continue
}
value.Default = defaultValue
settings[name] = value
}
}
type Provider interface {
Get(name string) string
Set(name, value string) error
SetIfUnset(name, value string) error
SetAll(settings map[string]Setting) error
}
type Setting struct {
Name string
Default string
ReadOnly bool
}
func (s Setting) SetIfUnset(value string) error {
if provider == nil {
return s.Set(value)
}
return provider.SetIfUnset(s.Name, value)
}
func (s Setting) Set(value string) error {
if provider == nil {
s, ok := settings[s.Name]
if ok {
s.Default = value
settings[s.Name] = s
}
} else {
return provider.Set(s.Name, value)
}
return nil
}
func (s Setting) Get() string {
if provider == nil {
s := settings[s.Name]
return s.Default
}
return provider.Get(s.Name)
}
func (s Setting) GetInt() int {
v := s.Get()
i, err := strconv.Atoi(v)
if err == nil {
return i
}
logrus.Errorf("failed to parse setting %s=%s as int: %v", s.Name, v, err)
i, err = strconv.Atoi(s.Default)
if err != nil {
return 0
}
return i
}
func SetProvider(p Provider) error {
if err := p.SetAll(settings); err != nil {
return err
}
provider = p
return nil
}
func NewSetting(name, def string) Setting {
s := Setting{
Name: name,
Default: def,
}
settings[s.Name] = s
return s
}
func GetEnvKey(key string) string {
return "CATTLE_" + strings.ToUpper(strings.Replace(key, "-", "_", -1))
}
func getMetadataConfig() string {
branch := KDMBranch.Get()
data := map[string]interface{}{
"url": fmt.Sprintf("https://releases.rancher.com/kontainer-driver-metadata/%s/data.json", branch),
"refresh-interval-minutes": "1440",
}
ans, err := json.Marshal(data)
if err != nil {
logrus.Errorf("error getting metadata config %v", err)
return ""
}
return string(ans)
}
// GetSettingByID returns a setting that is stored with the given id
func GetSettingByID(id string) string {
if provider == nil {
s := settings[id]
return s.Default
}
return provider.Get(id)
}
func DefaultAgentSettings() []Setting {
return []Setting{
ServerVersion,
InstallUUID,
IngressIPDomain,
}
}
func DefaultAgentSettingsAsEnvVars() []v1.EnvVar {
defaultAgentSettings := DefaultAgentSettings()
envVars := make([]v1.EnvVar, 0, len(defaultAgentSettings))
for _, s := range defaultAgentSettings {
envVars = append(envVars, v1.EnvVar{
Name: GetEnvKey(s.Name),
Value: s.Get(),
})
}
return envVars
}
func GetRancherVersion() string {
rancherVersion := ServerVersion.Get()
if strings.HasPrefix(rancherVersion, "dev") || strings.HasPrefix(rancherVersion, "master") || strings.HasSuffix(rancherVersion, "-head") {
return RancherVersionDev
}
return strings.TrimPrefix(rancherVersion, "v")
}
| [
"\"CATTLE_NAMESPACE\"",
"\"CATTLE_PEER_SERVICE\""
]
| []
| [
"CATTLE_NAMESPACE",
"CATTLE_PEER_SERVICE"
]
| [] | ["CATTLE_NAMESPACE", "CATTLE_PEER_SERVICE"] | go | 2 | 0 | |
pubsub/publish.go | package pubsub
import (
"context"
"log"
"os"
gcp "cloud.google.com/go/pubsub"
)
// projectID is set from the GCP_PROJECT environment variable, which is
// automatically set by the Cloud Functions runtime.
var projectID = os.Getenv("GCP_PROJECT")
// Publisher is Google Pub/Sub publisher.
type Publisher struct {
topic *gcp.Topic
}
// NewPublisher creates a new instance of Pub/Sub publisher.
// It also creates the Pub/Sub topic if it does not exist.
func NewPublisher(topicID string) (*Publisher, error) {
ctx := context.Background()
client, err := gcp.NewClient(ctx, projectID)
if err != nil {
return nil, err
}
// Create the topic if it doesn't exist.
topic := client.Topic(topicID)
exists, err := topic.Exists(ctx)
if err != nil {
return nil, err
}
if !exists {
if _, err = client.CreateTopic(ctx, topicID); err != nil {
return nil, err
}
}
return &Publisher{topic: topic}, nil
}
// Publish data to the Pub/Sub topic synchronously.
func (p *Publisher) Publish(ctx context.Context, data []byte) error {
id, err := p.topic.Publish(ctx, &gcp.Message{Data: data}).Get(ctx)
if err != nil {
log.Printf("publish id: %s, data: %s, error: %v\n", id, string(data), err)
}
return err
}
| [
"\"GCP_PROJECT\""
]
| []
| [
"GCP_PROJECT"
]
| [] | ["GCP_PROJECT"] | go | 1 | 0 | |
libraries/logger/logger.go | package logger
import (
"os"
"strings"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
func syslogTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05"))
}
// GetLogger returns a *zap.SugaredLogger
func GetLogger(module string) *zap.SugaredLogger {
logLevel := os.Getenv("LOG_LEVEL")
upperModule := strings.ToUpper(module)
if os.Getenv("LOG_LEVEL_"+upperModule) != "" {
logLevel = os.Getenv("LOG_LEVEL_" + upperModule)
}
runEnv := os.Getenv("RUN_ENV")
var config zap.Config
if strings.ToUpper(runEnv) == "DEV" {
config = zap.NewDevelopmentConfig()
} else {
config = zap.NewProductionConfig()
}
config.Level.UnmarshalText([]byte(logLevel))
config.EncoderConfig.EncodeTime = syslogTimeEncoder
log, _ := config.Build()
return log.Named(module).Sugar()
}
| [
"\"LOG_LEVEL\"",
"\"LOG_LEVEL_\"+upperModule",
"\"LOG_LEVEL_\" + upperModule",
"\"RUN_ENV\""
]
| []
| [
"LOG_LEVEL_\" + upperModul",
"LOG_LEVEL_\"+upperModul",
"RUN_ENV",
"LOG_LEVEL"
]
| [] | ["LOG_LEVEL_\" + upperModul", "LOG_LEVEL_\"+upperModul", "RUN_ENV", "LOG_LEVEL"] | go | 4 | 0 | |
hack36/settings.py | """
Django settings for hack36 project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'uu8f5vwf7kvz74g60&4p%=fqbjsk57x@w5a7g*=$))-it@1nm#'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'drug',
'rest_framework',
'widget_tweaks',
]
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = '/'
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'hack36.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'hack36.wsgi.application'
REGISTRATION_OPEN = True
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# DATABASES = {
# 'default': dj_database_url.config(
# default=os.environ.get('DATABASE_URL')
# )
# }
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' | []
| []
| [
"DATABASE_URL"
]
| [] | ["DATABASE_URL"] | python | 1 | 0 | |
bigml/domain.py | # -*- coding: utf-8 -*-
#
# Copyright 2014-2020 BigML
#
# 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.
"""Domain class to handle domain assignation for VPCs
"""
import os
# Default domain and protocol
DEFAULT_DOMAIN = 'bigml.io'
DEFAULT_PROTOCOL = 'https'
# Base Domain
BIGML_DOMAIN = os.environ.get('BIGML_DOMAIN', DEFAULT_DOMAIN)
# Protocol for main server
BIGML_PROTOCOL = os.environ.get('BIGML_PROTOCOL',
DEFAULT_PROTOCOL)
# SSL Verification
BIGML_SSL_VERIFY = os.environ.get('BIGML_SSL_VERIFY')
# Domain for prediction server
BIGML_PREDICTION_DOMAIN = os.environ.get('BIGML_PREDICTION_DOMAIN',
BIGML_DOMAIN)
# Protocol for prediction server
BIGML_PREDICTION_PROTOCOL = os.environ.get('BIGML_PREDICTION_PROTOCOL',
DEFAULT_PROTOCOL)
# SSL Verification for prediction server
BIGML_PREDICTION_SSL_VERIFY = os.environ.get('BIGML_PREDICTION_SSL_VERIFY')
class Domain():
"""A Domain object to store the remote domain information for the API
The domain that serves the remote resources can be set globally for
all the resources either by setting the BIGML_DOMAIN environment
variable
export BIGML_DOMAIN=my_VPC.bigml.io
or can be given in the constructor using the `domain` argument.
my_domain = Domain("my_VPC.bigml.io")
You can also specify a separate domain to handle predictions. This can
be set by using the BIGML_PREDICTION_DOMAIN and
BIGML_PREDICTION_PROTOCOL
environment variables
export BIGML_PREDICTION_DOMAIN=my_prediction_server.bigml.com
export BIGML_PREDICITION_PROTOCOL=https
or the `prediction_server` and `prediction_protocol` arguments.
The constructor values will override the environment settings.
"""
def __init__(self, domain=None, prediction_domain=None,
prediction_protocol=None, protocol=None, verify=None,
prediction_verify=None):
"""Domain object constructor.
@param: domain string Domain name
@param: prediction_domain string Domain for the prediction server
(when different from the general domain)
@param: prediction_protocol string Protocol for prediction server
(when different from the general protocol)
@param: protocol string Protocol for the service
(when different from HTTPS)
@param: verify boolean Sets on/off the SSL verification
@param: prediction_verify boolean Sets on/off the SSL verification
for the prediction server (when different from the general
SSL verification)
"""
# Base domain for remote resources
self.general_domain = domain or BIGML_DOMAIN
self.general_protocol = protocol or BIGML_PROTOCOL
# Usually, predictions are served from the same domain
if prediction_domain is None:
if domain is not None:
self.prediction_domain = domain
self.prediction_protocol = protocol or BIGML_PROTOCOL
else:
self.prediction_domain = BIGML_PREDICTION_DOMAIN
self.prediction_protocol = BIGML_PREDICTION_PROTOCOL
# If the domain for predictions is different from the general domain,
# for instance in high-availability prediction servers
else:
self.prediction_domain = prediction_domain
self.prediction_protocol = prediction_protocol or \
BIGML_PREDICTION_PROTOCOL
# Check SSL when comming from `bigml.io` subdomains or when forced
# by the external BIGML_SSL_VERIFY environment variable or verify
# arguments
self.verify = None
self.verify_prediction = None
if self.general_protocol == BIGML_PROTOCOL and \
(verify is not None or BIGML_SSL_VERIFY is not None):
try:
self.verify = verify if verify is not None \
else bool(int(BIGML_SSL_VERIFY))
except ValueError:
pass
if self.verify is None:
self.verify = self.general_domain.lower().endswith(DEFAULT_DOMAIN)
if self.prediction_protocol == BIGML_PROTOCOL and \
(prediction_verify is not None or \
BIGML_PREDICTION_SSL_VERIFY is not None):
try:
self.verify_prediction = prediction_verify \
if prediction_verify is not None else \
bool(int(BIGML_PREDICTION_SSL_VERIFY))
except ValueError:
pass
if self.verify_prediction is None:
self.verify_prediction = (
(self.prediction_domain.lower().endswith(DEFAULT_DOMAIN) and
self.prediction_protocol == DEFAULT_PROTOCOL))
| []
| []
| [
"BIGML_PREDICTION_DOMAIN",
"BIGML_PREDICTION_SSL_VERIFY",
"BIGML_PROTOCOL",
"BIGML_DOMAIN",
"BIGML_SSL_VERIFY",
"BIGML_PREDICTION_PROTOCOL"
]
| [] | ["BIGML_PREDICTION_DOMAIN", "BIGML_PREDICTION_SSL_VERIFY", "BIGML_PROTOCOL", "BIGML_DOMAIN", "BIGML_SSL_VERIFY", "BIGML_PREDICTION_PROTOCOL"] | python | 6 | 0 | |
tests/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
client/cache/memcache/memcache_test.go | // Copyright 2014 beego Author. All Rights Reserved.
//
// 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 memcache
import (
"context"
"fmt"
"os"
"strconv"
"testing"
"time"
_ "github.com/bradfitz/gomemcache/memcache"
"github.com/beego/beego/v2/client/cache"
)
func TestMemcacheCache(t *testing.T) {
addr := os.Getenv("MEMCACHE_ADDR")
if addr == "" {
addr = "127.0.0.1:11211"
}
bm, err := cache.NewCache("memcache", fmt.Sprintf(`{"conn": "%s"}`, addr))
if err != nil {
t.Error("init err")
}
timeoutDuration := 10 * time.Second
if err = bm.Put(context.Background(), "astaxie", "1", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if res, _ := bm.IsExist(context.Background(), "astaxie"); !res {
t.Error("check err")
}
time.Sleep(11 * time.Second)
if res, _ := bm.IsExist(context.Background(), "astaxie"); res {
t.Error("check err")
}
if err = bm.Put(context.Background(), "astaxie", "1", timeoutDuration); err != nil {
t.Error("set Error", err)
}
val, _ := bm.Get(context.Background(), "astaxie")
if v, err := strconv.Atoi(string(val.([]byte))); err != nil || v != 1 {
t.Error("get err")
}
if err = bm.Incr(context.Background(), "astaxie"); err != nil {
t.Error("Incr Error", err)
}
val, _ = bm.Get(context.Background(), "astaxie")
if v, err := strconv.Atoi(string(val.([]byte))); err != nil || v != 2 {
t.Error("get err")
}
if err = bm.Decr(context.Background(), "astaxie"); err != nil {
t.Error("Decr Error", err)
}
val, _ = bm.Get(context.Background(), "astaxie")
if v, err := strconv.Atoi(string(val.([]byte))); err != nil || v != 1 {
t.Error("get err")
}
bm.Delete(context.Background(), "astaxie")
if res, _ := bm.IsExist(context.Background(), "astaxie"); res {
t.Error("delete err")
}
// test string
if err = bm.Put(context.Background(), "astaxie", "author", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if res, _ := bm.IsExist(context.Background(), "astaxie"); !res {
t.Error("check err")
}
val, _ = bm.Get(context.Background(), "astaxie")
if v := val.([]byte); string(v) != "author" {
t.Error("get err")
}
// test GetMulti
if err = bm.Put(context.Background(), "astaxie1", "author1", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if res, _ := bm.IsExist(context.Background(), "astaxie1"); !res {
t.Error("check err")
}
vv, _ := bm.GetMulti(context.Background(), []string{"astaxie", "astaxie1"})
if len(vv) != 2 {
t.Error("GetMulti ERROR")
}
if string(vv[0].([]byte)) != "author" && string(vv[0].([]byte)) != "author1" {
t.Error("GetMulti ERROR")
}
if string(vv[1].([]byte)) != "author1" && string(vv[1].([]byte)) != "author" {
t.Error("GetMulti ERROR")
}
vv, err = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"})
if len(vv) != 2 {
t.Error("GetMulti ERROR")
}
if vv[0] != nil {
t.Error("GetMulti ERROR")
}
if string(vv[1].([]byte)) != "author1" {
t.Error("GetMulti ERROR")
}
if err != nil && err.Error() == "key [astaxie0] error: key isn't exist" {
t.Error("GetMulti ERROR")
}
// test clear all
if err = bm.ClearAll(context.Background()); err != nil {
t.Error("clear all err")
}
}
| [
"\"MEMCACHE_ADDR\""
]
| []
| [
"MEMCACHE_ADDR"
]
| [] | ["MEMCACHE_ADDR"] | go | 1 | 0 | |
telegram_hook_test.go | package telegram_hook_test
import (
"errors"
"os"
"testing"
"github.com/rossmcdonald/telegram_hook"
log "github.com/sirupsen/logrus"
)
func TestNewHook(t *testing.T) {
_, err := telegram_hook.NewTelegramHook("", "", "")
if err == nil {
t.Errorf("No error on invalid Telegram API token.")
}
_, err = telegram_hook.NewTelegramHook("", os.Getenv("TELEGRAM_TOKEN"), "")
if err != nil {
t.Fatalf("Error on valid Telegram API token: %s", err)
}
h, _ := telegram_hook.NewTelegramHook("testing", os.Getenv("TELEGRAM_TOKEN"), os.Getenv("TELEGRAM_TARGET"))
if err != nil {
t.Fatalf("Error on valid Telegram API token and target: %s", err)
}
log.AddHook(h)
log.WithError(errors.New("an error")).WithFields(log.Fields{
"animal": "walrus",
"number": 1,
"size": 10,
"html": "<b>bold</b>",
}).Errorf("A walrus appears")
}
| [
"\"TELEGRAM_TOKEN\"",
"\"TELEGRAM_TOKEN\"",
"\"TELEGRAM_TARGET\""
]
| []
| [
"TELEGRAM_TARGET",
"TELEGRAM_TOKEN"
]
| [] | ["TELEGRAM_TARGET", "TELEGRAM_TOKEN"] | go | 2 | 0 | |
util/pkg/vfs/s3fs.go | /*
Copyright 2016 The Kubernetes 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 vfs
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"os"
"path"
"strings"
"sync"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/golang/glog"
"k8s.io/kops/util/pkg/hashing"
)
type S3Path struct {
s3Context *S3Context
bucket string
region string
key string
etag *string
}
var _ Path = &S3Path{}
var _ HasHash = &S3Path{}
// S3Acl is an ACL implementation for objects on S3
type S3Acl struct {
RequestACL *string
}
func newS3Path(s3Context *S3Context, bucket string, key string) *S3Path {
bucket = strings.TrimSuffix(bucket, "/")
key = strings.TrimPrefix(key, "/")
return &S3Path{
s3Context: s3Context,
bucket: bucket,
key: key,
}
}
func (p *S3Path) Path() string {
return "s3://" + p.bucket + "/" + p.key
}
func (p *S3Path) Bucket() string {
return p.bucket
}
func (p *S3Path) Key() string {
return p.key
}
func (p *S3Path) String() string {
return p.Path()
}
func (p *S3Path) Remove() error {
client, err := p.client()
if err != nil {
return err
}
glog.V(8).Infof("removing file %s", p)
request := &s3.DeleteObjectInput{}
request.Bucket = aws.String(p.bucket)
request.Key = aws.String(p.key)
_, err = client.DeleteObject(request)
if err != nil {
// TODO: Check for not-exists, return os.NotExist
return fmt.Errorf("error deleting %s: %v", p, err)
}
return nil
}
func (p *S3Path) Join(relativePath ...string) Path {
args := []string{p.key}
args = append(args, relativePath...)
joined := path.Join(args...)
return &S3Path{
s3Context: p.s3Context,
bucket: p.bucket,
key: joined,
}
}
func (p *S3Path) WriteFile(data io.ReadSeeker, aclObj ACL) error {
client, err := p.client()
if err != nil {
return err
}
glog.V(4).Infof("Writing file %q", p)
// We always use server-side-encryption; it doesn't really cost us anything
sse := "AES256"
request := &s3.PutObjectInput{}
request.Body = data
request.Bucket = aws.String(p.bucket)
request.Key = aws.String(p.key)
request.ServerSideEncryption = aws.String(sse)
acl := os.Getenv("KOPS_STATE_S3_ACL")
acl = strings.TrimSpace(acl)
if acl != "" {
glog.Infof("Using KOPS_STATE_S3_ACL=%s", acl)
request.ACL = aws.String(acl)
} else if aclObj != nil {
s3Acl, ok := aclObj.(*S3Acl)
if !ok {
return fmt.Errorf("write to %s with ACL of unexpected type %T", p, aclObj)
}
request.ACL = s3Acl.RequestACL
}
// We don't need Content-MD5: https://github.com/aws/aws-sdk-go/issues/208
glog.V(8).Infof("Calling S3 PutObject Bucket=%q Key=%q SSE=%q ACL=%q", p.bucket, p.key, sse, acl)
_, err = client.PutObject(request)
if err != nil {
if acl != "" {
return fmt.Errorf("error writing %s (with ACL=%q): %v", p, acl, err)
} else {
return fmt.Errorf("error writing %s: %v", p, err)
}
}
return nil
}
// To prevent concurrent creates on the same file while maintaining atomicity of writes,
// we take a process-wide lock during the operation.
// Not a great approach, but fine for a single process (with low concurrency)
// TODO: should we enable versioning?
var createFileLockS3 sync.Mutex
func (p *S3Path) CreateFile(data io.ReadSeeker, acl ACL) error {
createFileLockS3.Lock()
defer createFileLockS3.Unlock()
// Check if exists
_, err := p.ReadFile()
if err == nil {
return os.ErrExist
}
if !os.IsNotExist(err) {
return err
}
return p.WriteFile(data, acl)
}
// ReadFile implements Path::ReadFile
func (p *S3Path) ReadFile() ([]byte, error) {
var b bytes.Buffer
_, err := p.WriteTo(&b)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
// WriteTo implements io.WriterTo
func (p *S3Path) WriteTo(out io.Writer) (int64, error) {
client, err := p.client()
if err != nil {
return 0, err
}
glog.V(4).Infof("Reading file %q", p)
request := &s3.GetObjectInput{}
request.Bucket = aws.String(p.bucket)
request.Key = aws.String(p.key)
response, err := client.GetObject(request)
if err != nil {
if AWSErrorCode(err) == "NoSuchKey" {
return 0, os.ErrNotExist
}
return 0, fmt.Errorf("error fetching %s: %v", p, err)
}
defer response.Body.Close()
n, err := io.Copy(out, response.Body)
if err != nil {
return n, fmt.Errorf("error reading %s: %v", p, err)
}
return n, nil
}
func (p *S3Path) ReadDir() ([]Path, error) {
client, err := p.client()
if err != nil {
return nil, err
}
prefix := p.key
if prefix != "" && !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
request := &s3.ListObjectsInput{}
request.Bucket = aws.String(p.bucket)
request.Prefix = aws.String(prefix)
request.Delimiter = aws.String("/")
glog.V(4).Infof("Listing objects in S3 bucket %q with prefix %q", p.bucket, prefix)
var paths []Path
err = client.ListObjectsPages(request, func(page *s3.ListObjectsOutput, lastPage bool) bool {
for _, o := range page.Contents {
key := aws.StringValue(o.Key)
if key == prefix {
// We have reports (#548 and #520) of the directory being returned as a file
// And this will indeed happen if the directory has been created as a file,
// which seems to happen if you use some external tools to manipulate the S3 bucket.
// We need to tolerate that, so skip the parent directory.
glog.V(4).Infof("Skipping read of directory: %q", key)
continue
}
child := &S3Path{
s3Context: p.s3Context,
bucket: p.bucket,
key: key,
etag: o.ETag,
}
paths = append(paths, child)
}
return true
})
if err != nil {
return nil, fmt.Errorf("error listing %s: %v", p, err)
}
glog.V(8).Infof("Listed files in %v: %v", p, paths)
return paths, nil
}
func (p *S3Path) ReadTree() ([]Path, error) {
client, err := p.client()
if err != nil {
return nil, err
}
request := &s3.ListObjectsInput{}
request.Bucket = aws.String(p.bucket)
prefix := p.key
if prefix != "" && !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
request.Prefix = aws.String(prefix)
// No delimiter for recursive search
var paths []Path
err = client.ListObjectsPages(request, func(page *s3.ListObjectsOutput, lastPage bool) bool {
for _, o := range page.Contents {
key := aws.StringValue(o.Key)
child := &S3Path{
s3Context: p.s3Context,
bucket: p.bucket,
key: key,
etag: o.ETag,
}
paths = append(paths, child)
}
return true
})
if err != nil {
return nil, fmt.Errorf("error listing %s: %v", p, err)
}
return paths, nil
}
func (p *S3Path) client() (*s3.S3, error) {
var err error
if p.region == "" {
p.region, err = p.s3Context.getRegionForBucket(p.bucket)
if err != nil {
return nil, err
}
}
client, err := p.s3Context.getClient(p.region)
if err != nil {
return nil, err
}
return client, nil
}
func (p *S3Path) Base() string {
return path.Base(p.key)
}
func (p *S3Path) PreferredHash() (*hashing.Hash, error) {
return p.Hash(hashing.HashAlgorithmMD5)
}
func (p *S3Path) Hash(a hashing.HashAlgorithm) (*hashing.Hash, error) {
if a != hashing.HashAlgorithmMD5 {
return nil, nil
}
if p.etag == nil {
return nil, nil
}
md5 := strings.Trim(*p.etag, "\"")
md5Bytes, err := hex.DecodeString(md5)
if err != nil {
return nil, fmt.Errorf("Etag was not a valid MD5 sum: %q", *p.etag)
}
return &hashing.Hash{Algorithm: hashing.HashAlgorithmMD5, HashValue: md5Bytes}, nil
}
// AWSErrorCode returns the aws error code, if it is an awserr.Error, otherwise ""
func AWSErrorCode(err error) string {
if awsError, ok := err.(awserr.Error); ok {
return awsError.Code()
}
return ""
}
| [
"\"KOPS_STATE_S3_ACL\""
]
| []
| [
"KOPS_STATE_S3_ACL"
]
| [] | ["KOPS_STATE_S3_ACL"] | go | 1 | 0 | |
mrmap/MrMap/wsgi.py | """
WSGI config for MrMap project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MrMap.settings')
application = get_wsgi_application() | []
| []
| []
| [] | [] | python | 0 | 0 | |
selfdrive/controls/controlsd.py | #!/usr/bin/env python3
import os
import gc
import capnp
from cereal import car, log
from common.numpy_fast import clip
from common.realtime import sec_since_boot, set_realtime_priority, Ratekeeper, DT_CTRL
from common.profiler import Profiler
from common.params import Params, put_nonblocking
import cereal.messaging as messaging
from selfdrive.config import Conversions as CV
from selfdrive.boardd.boardd import can_list_to_can_capnp
from selfdrive.car.car_helpers import get_car, get_startup_alert
from selfdrive.controls.lib.lane_planner import CAMERA_OFFSET
from selfdrive.controls.lib.drive_helpers import get_events, \
create_event, \
EventTypes as ET, \
update_v_cruise, \
initialize_v_cruise
from selfdrive.controls.lib.longcontrol import LongControl, STARTING_TARGET_SPEED
from selfdrive.controls.lib.latcontrol_pid import LatControlPID
from selfdrive.controls.lib.latcontrol_indi import LatControlINDI
from selfdrive.controls.lib.latcontrol_lqr import LatControlLQR
from selfdrive.controls.lib.alertmanager import AlertManager
from selfdrive.controls.lib.vehicle_model import VehicleModel
from selfdrive.controls.lib.driver_monitor import DriverStatus, MAX_TERMINAL_ALERTS, MAX_TERMINAL_DURATION
from selfdrive.controls.lib.planner import LON_MPC_STEP
from selfdrive.controls.lib.gps_helpers import is_rhd_region
from selfdrive.locationd.calibration_helpers import Calibration, Filter
LANE_DEPARTURE_THRESHOLD = 0.1
ThermalStatus = log.ThermalData.ThermalStatus
State = log.ControlsState.OpenpilotState
HwType = log.HealthData.HwType
LaneChangeState = log.PathPlan.LaneChangeState
LaneChangeDirection = log.PathPlan.LaneChangeDirection
def add_lane_change_event(events, path_plan):
if path_plan.laneChangeState == LaneChangeState.preLaneChange:
if path_plan.laneChangeDirection == LaneChangeDirection.left:
event_name = 'preLaneChangeLeft'
if path_plan.autoLCAllowed:
event_name = 'preAutoLaneChangeLeft'
events.append(create_event(event_name, [ET.WARNING]))
else:
event_name = 'preLaneChangeRight'
if path_plan.autoLCAllowed:
event_name = 'preAutoLaneChangeRight'
events.append(create_event(event_name, [ET.WARNING]))
elif path_plan.laneChangeState in [LaneChangeState.laneChangeStarting, LaneChangeState.laneChangeFinishing]:
event_name = 'laneChange'
if path_plan.autoLCAllowed:
event_name = 'autoLaneChange'
events.append(create_event(event_name, [ET.WARNING]))
def isActive(state):
"""Check if the actuators are enabled"""
return state in [State.enabled, State.softDisabling]
def isEnabled(state):
"""Check if openpilot is engaged"""
return (isActive(state) or state == State.preEnabled)
def events_to_bytes(events):
# optimization when comparing capnp structs: str() or tree traverse are much slower
ret = []
for e in events:
if isinstance(e, capnp.lib.capnp._DynamicStructReader):
e = e.as_builder()
ret.append(e.to_bytes())
return ret
def data_sample(CI, CC, sm, can_sock, driver_status, state, mismatch_counter, params):
"""Receive data from sockets and create events for battery, temperature and disk space"""
# Update carstate from CAN and create events
can_strs = messaging.drain_sock_raw(can_sock, wait_for_one=True)
CS = CI.update(CC, can_strs)
sm.update(0)
events = list(CS.events)
add_lane_change_event(events, sm['pathPlan'])
enabled = isEnabled(state)
# Check for CAN timeout
if not can_strs:
events.append(create_event('canError', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE]))
overtemp = sm['thermal'].thermalStatus >= ThermalStatus.red
free_space = sm['thermal'].freeSpace < 0.07 # under 7% of space free no enable allowed
low_battery = sm['thermal'].batteryPercent < 1 and sm['thermal'].chargingError # at zero percent battery, while discharging, OP should not allowed
mem_low = sm['thermal'].memUsedPercent > 90
# Create events for battery, temperature and disk space
if low_battery:
events.append(create_event('lowBattery', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
if overtemp:
events.append(create_event('overheat', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
if free_space:
events.append(create_event('outOfSpace', [ET.NO_ENTRY]))
if mem_low:
events.append(create_event('lowMemory', [ET.NO_ENTRY, ET.SOFT_DISABLE, ET.PERMANENT]))
if CS.stockAeb:
events.append(create_event('stockAeb', []))
# GPS coords RHD parsing, once every restart
if sm.updated['gpsLocation'] and not driver_status.is_rhd_region_checked:
is_rhd = is_rhd_region(sm['gpsLocation'].latitude, sm['gpsLocation'].longitude)
driver_status.is_rhd_region = is_rhd
driver_status.is_rhd_region_checked = True
put_nonblocking("IsRHD", "1" if is_rhd else "0")
# Handle calibration
cal_status = sm['liveCalibration'].calStatus
cal_perc = sm['liveCalibration'].calPerc
cal_rpy = [0,0,0]
if cal_status != Calibration.CALIBRATED:
if cal_status == Calibration.UNCALIBRATED:
events.append(create_event('calibrationIncomplete', [ET.NO_ENTRY, ET.SOFT_DISABLE, ET.PERMANENT]))
else:
events.append(create_event('calibrationInvalid', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
else:
rpy = sm['liveCalibration'].rpyCalib
if len(rpy) == 3:
cal_rpy = rpy
# When the panda and controlsd do not agree on controls_allowed
# we want to disengage openpilot. However the status from the panda goes through
# another socket other than the CAN messages and one can arrive earlier than the other.
# Therefore we allow a mismatch for two samples, then we trigger the disengagement.
if not enabled:
mismatch_counter = 0
controls_allowed = sm['health'].controlsAllowed
if not controls_allowed and enabled:
mismatch_counter += 1
if mismatch_counter >= 200:
events.append(create_event('controlsMismatch', [ET.IMMEDIATE_DISABLE]))
# Driver monitoring
if sm.updated['model']:
driver_status.set_policy(sm['model'])
if sm.updated['driverMonitoring']:
driver_status.get_pose(sm['driverMonitoring'], cal_rpy, CS.vEgo, enabled)
#if driver_status.terminal_alert_cnt >= MAX_TERMINAL_ALERTS or driver_status.terminal_time >= MAX_TERMINAL_DURATION:
# events.append(create_event("tooDistracted", [ET.NO_ENTRY]))
return CS, events, cal_perc, mismatch_counter
def state_transition(frame, CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM):
"""Compute conditional state transitions and execute actions on state transitions"""
enabled = isEnabled(state)
v_cruise_kph_last = v_cruise_kph
# if stock cruise is completely disabled, then we can use our own set speed logic
if not CP.enableCruise:
v_cruise_kph = update_v_cruise(v_cruise_kph, CS.buttonEvents, enabled)
elif CP.enableCruise and CS.cruiseState.enabled:
v_cruise_kph = CS.cruiseState.speed * CV.MS_TO_KPH
# decrease the soft disable timer at every step, as it's reset on
# entrance in SOFT_DISABLING state
soft_disable_timer = max(0, soft_disable_timer - 1)
# DISABLED
if state == State.disabled:
if get_events(events, [ET.ENABLE]):
if get_events(events, [ET.NO_ENTRY]):
for e in get_events(events, [ET.NO_ENTRY]):
AM.add(frame, str(e) + "NoEntry", enabled)
else:
if get_events(events, [ET.PRE_ENABLE]):
state = State.preEnabled
else:
state = State.enabled
AM.add(frame, "enable", enabled)
v_cruise_kph = initialize_v_cruise(CS.vEgo, CS.buttonEvents, v_cruise_kph_last)
# ENABLED
elif state == State.enabled:
if get_events(events, [ET.USER_DISABLE]):
state = State.disabled
AM.add(frame, "disable", enabled)
elif get_events(events, [ET.IMMEDIATE_DISABLE]):
state = State.disabled
for e in get_events(events, [ET.IMMEDIATE_DISABLE]):
AM.add(frame, e, enabled)
elif get_events(events, [ET.SOFT_DISABLE]):
state = State.softDisabling
soft_disable_timer = 300 # 3s
for e in get_events(events, [ET.SOFT_DISABLE]):
AM.add(frame, e, enabled)
# SOFT DISABLING
elif state == State.softDisabling:
if get_events(events, [ET.USER_DISABLE]):
state = State.disabled
AM.add(frame, "disable", enabled)
elif get_events(events, [ET.IMMEDIATE_DISABLE]):
state = State.disabled
for e in get_events(events, [ET.IMMEDIATE_DISABLE]):
AM.add(frame, e, enabled)
elif not get_events(events, [ET.SOFT_DISABLE]):
# no more soft disabling condition, so go back to ENABLED
state = State.enabled
elif get_events(events, [ET.SOFT_DISABLE]) and soft_disable_timer > 0:
for e in get_events(events, [ET.SOFT_DISABLE]):
AM.add(frame, e, enabled)
elif soft_disable_timer <= 0:
state = State.disabled
# PRE ENABLING
elif state == State.preEnabled:
if get_events(events, [ET.USER_DISABLE]):
state = State.disabled
AM.add(frame, "disable", enabled)
elif get_events(events, [ET.IMMEDIATE_DISABLE, ET.SOFT_DISABLE]):
state = State.disabled
for e in get_events(events, [ET.IMMEDIATE_DISABLE, ET.SOFT_DISABLE]):
AM.add(frame, e, enabled)
elif not get_events(events, [ET.PRE_ENABLE]):
state = State.enabled
return state, soft_disable_timer, v_cruise_kph, v_cruise_kph_last
def state_control(frame, rcv_frame, plan, path_plan, CS, CP, state, events, v_cruise_kph, v_cruise_kph_last,
AM, rk, driver_status, LaC, LoC, read_only, is_metric, cal_perc, last_blinker_frame, dragon_lat_control, dragon_display_steering_limit_alert, dragon_lead_car_moving_alert):
"""Given the state, this function returns an actuators packet"""
actuators = car.CarControl.Actuators.new_message()
enabled = isEnabled(state)
active = isActive(state)
# check if user has interacted with the car
driver_engaged = len(CS.buttonEvents) > 0 or \
v_cruise_kph != v_cruise_kph_last or \
CS.steeringPressed
if CS.leftBlinker or CS.rightBlinker:
last_blinker_frame = frame
# add eventual driver distracted events
events = driver_status.update(events, driver_engaged, isActive(state), CS.standstill)
# send FCW alert if triggered by planner
if plan.fcw or CS.stockFcw:
AM.add(frame, "fcw", enabled)
# State specific actions
if state in [State.preEnabled, State.disabled]:
if dragon_lead_car_moving_alert:
for e in get_events(events, [ET.WARNING]):
extra_text = ""
if e in ["leadCarDetected", "leadCarMoving"]:
AM.add(frame, e, enabled, extra_text_2=extra_text)
LaC.reset()
LoC.reset(v_pid=CS.vEgo)
elif state in [State.enabled, State.softDisabling]:
# parse warnings from car specific interface
for e in get_events(events, [ET.WARNING]):
extra_text = ""
if e == "belowSteerSpeed":
if is_metric:
extra_text = str(int(round(CP.minSteerSpeed * CV.MS_TO_KPH))) + " kph"
else:
extra_text = str(int(round(CP.minSteerSpeed * CV.MS_TO_MPH))) + " mph"
AM.add(frame, e, enabled, extra_text_2=extra_text)
plan_age = DT_CTRL * (frame - rcv_frame['plan'])
dt = min(plan_age, LON_MPC_STEP + DT_CTRL) + DT_CTRL # no greater than dt mpc + dt, to prevent too high extraps
a_acc_sol = plan.aStart + (dt / LON_MPC_STEP) * (plan.aTarget - plan.aStart)
v_acc_sol = plan.vStart + dt * (a_acc_sol + plan.aStart) / 2.0
# Gas/Brake PID loop
actuators.gas, actuators.brake = LoC.update(active, CS.vEgo, CS.brakePressed, CS.standstill, CS.cruiseState.standstill,
v_cruise_kph, v_acc_sol, plan.vTargetFuture, a_acc_sol, CP)
# Steering PID loop and lateral MPC
actuators.steer, actuators.steerAngle, lac_log = LaC.update(active, CS.vEgo, CS.steeringAngle, CS.steeringRate, CS.steeringTorqueEps, CS.steeringPressed, CS.steeringRateLimited, CP, path_plan)
# Send a "steering required alert" if saturation count has reached the limit
if dragon_display_steering_limit_alert:
if dragon_lat_control and lac_log.saturated and not CS.steeringPressed:
# Check if we deviated from the path
left_deviation = actuators.steer > 0 and path_plan.dPoly[3] > 0.1
right_deviation = actuators.steer < 0 and path_plan.dPoly[3] < -0.1
if left_deviation or right_deviation:
AM.add(frame, "steerSaturated", enabled)
# Parse permanent warnings to display constantly
for e in get_events(events, [ET.PERMANENT]):
extra_text_1, extra_text_2 = "", ""
if e == "calibrationIncomplete":
extra_text_1 = str(cal_perc) + "%"
if is_metric:
extra_text_2 = str(int(round(Filter.MIN_SPEED * CV.MS_TO_KPH))) + " kph"
else:
extra_text_2 = str(int(round(Filter.MIN_SPEED * CV.MS_TO_MPH))) + " mph"
AM.add(frame, str(e) + "Permanent", enabled, extra_text_1=extra_text_1, extra_text_2=extra_text_2)
return actuators, v_cruise_kph, driver_status, v_acc_sol, a_acc_sol, lac_log, last_blinker_frame
def data_send(sm, pm, CS, CI, CP, VM, state, events, actuators, v_cruise_kph, rk, AM,
driver_status, LaC, LoC, read_only, start_time, v_acc, a_acc, lac_log, events_prev,
last_blinker_frame, is_ldw_enabled):
"""Send actuators and hud commands to the car, send controlsstate and MPC logging"""
CC = car.CarControl.new_message()
CC.enabled = isEnabled(state)
CC.actuators = actuators
CC.cruiseControl.override = True
CC.cruiseControl.cancel = not CP.enableCruise or (not isEnabled(state) and CS.cruiseState.enabled)
# Some override values for Honda
brake_discount = (1.0 - clip(actuators.brake * 3., 0.0, 1.0)) # brake discount removes a sharp nonlinearity
CC.cruiseControl.speedOverride = float(max(0.0, (LoC.v_pid + CS.cruiseState.speedOffset) * brake_discount) if CP.enableCruise else 0.0)
CC.cruiseControl.accelOverride = CI.calc_accel_override(CS.aEgo, sm['plan'].aTarget, CS.vEgo, sm['plan'].vTarget)
CC.hudControl.setSpeed = float(v_cruise_kph * CV.KPH_TO_MS)
CC.hudControl.speedVisible = isEnabled(state)
CC.hudControl.lanesVisible = isEnabled(state)
CC.hudControl.leadVisible = sm['plan'].hasLead
right_lane_visible = sm['pathPlan'].rProb > 0.5
left_lane_visible = sm['pathPlan'].lProb > 0.5
CC.hudControl.rightLaneVisible = bool(right_lane_visible)
CC.hudControl.leftLaneVisible = bool(left_lane_visible)
recent_blinker = (sm.frame - last_blinker_frame) * DT_CTRL < 5.0 # 5s blinker cooldown
ldw_allowed = CS.vEgo > 31 * CV.MPH_TO_MS and not recent_blinker and is_ldw_enabled and not isActive(state)
md = sm['model']
if len(md.meta.desirePrediction):
l_lane_change_prob = md.meta.desirePrediction[log.PathPlan.Desire.laneChangeLeft - 1]
r_lane_change_prob = md.meta.desirePrediction[log.PathPlan.Desire.laneChangeRight - 1]
l_lane_close = left_lane_visible and (sm['pathPlan'].lPoly[3] < (1.08 - CAMERA_OFFSET))
r_lane_close = right_lane_visible and (sm['pathPlan'].rPoly[3] > -(1.08 + CAMERA_OFFSET))
if ldw_allowed:
CC.hudControl.leftLaneDepart = bool(l_lane_change_prob > LANE_DEPARTURE_THRESHOLD and l_lane_close)
CC.hudControl.rightLaneDepart = bool(r_lane_change_prob > LANE_DEPARTURE_THRESHOLD and r_lane_close)
if CC.hudControl.rightLaneDepart or CC.hudControl.leftLaneDepart:
AM.add(sm.frame, 'ldwPermanent', False)
events.append(create_event('ldw', [ET.PERMANENT]))
AM.process_alerts(sm.frame)
CC.hudControl.visualAlert = AM.visual_alert
if not read_only:
# send car controls over can
can_sends = CI.apply(CC)
pm.send('sendcan', can_list_to_can_capnp(can_sends, msgtype='sendcan', valid=CS.canValid))
force_decel = driver_status.awareness < 0.
# controlsState
dat = messaging.new_message()
dat.init('controlsState')
dat.valid = CS.canValid
dat.controlsState = {
"alertText1": AM.alert_text_1,
"alertText2": AM.alert_text_2,
"alertSize": AM.alert_size,
"alertStatus": AM.alert_status,
"alertBlinkingRate": AM.alert_rate,
"alertType": AM.alert_type,
"alertSound": AM.audible_alert,
"awarenessStatus": max(driver_status.awareness, -0.1) if isEnabled(state) else 1.0,
"driverMonitoringOn": bool(driver_status.face_detected),
"canMonoTimes": list(CS.canMonoTimes),
"planMonoTime": sm.logMonoTime['plan'],
"pathPlanMonoTime": sm.logMonoTime['pathPlan'],
"enabled": isEnabled(state),
"active": isActive(state),
"vEgo": CS.vEgo,
"vEgoRaw": CS.vEgoRaw,
"angleSteers": CS.steeringAngle,
"curvature": VM.calc_curvature((CS.steeringAngle - sm['pathPlan'].angleOffset) * CV.DEG_TO_RAD, CS.vEgo),
"steerOverride": CS.steeringPressed,
"state": state,
"engageable": not bool(get_events(events, [ET.NO_ENTRY])),
"longControlState": LoC.long_control_state,
"vPid": float(LoC.v_pid),
"vCruise": float(v_cruise_kph),
"upAccelCmd": float(LoC.pid.p),
"uiAccelCmd": float(LoC.pid.i),
"ufAccelCmd": float(LoC.pid.f),
"angleSteersDes": float(LaC.angle_steers_des),
"vTargetLead": float(v_acc),
"aTarget": float(a_acc),
"jerkFactor": float(sm['plan'].jerkFactor),
"gpsPlannerActive": sm['plan'].gpsPlannerActive,
"vCurvature": sm['plan'].vCurvature,
"decelForModel": sm['plan'].longitudinalPlanSource == log.Plan.LongitudinalPlanSource.model,
"cumLagMs": -rk.remaining * 1000.,
"startMonoTime": int(start_time * 1e9),
"mapValid": sm['plan'].mapValid,
"forceDecel": bool(force_decel),
}
if CP.lateralTuning.which() == 'pid':
dat.controlsState.lateralControlState.pidState = lac_log
elif CP.lateralTuning.which() == 'lqr':
dat.controlsState.lateralControlState.lqrState = lac_log
elif CP.lateralTuning.which() == 'indi':
dat.controlsState.lateralControlState.indiState = lac_log
pm.send('controlsState', dat)
# carState
cs_send = messaging.new_message()
cs_send.init('carState')
cs_send.valid = CS.canValid
cs_send.carState = CS
cs_send.carState.events = events
pm.send('carState', cs_send)
# carEvents - logged every second or on change
events_bytes = events_to_bytes(events)
if (sm.frame % int(1. / DT_CTRL) == 0) or (events_bytes != events_prev):
ce_send = messaging.new_message()
ce_send.init('carEvents', len(events))
ce_send.carEvents = events
pm.send('carEvents', ce_send)
# carParams - logged every 50 seconds (> 1 per segment)
if (sm.frame % int(50. / DT_CTRL) == 0):
cp_send = messaging.new_message()
cp_send.init('carParams')
cp_send.carParams = CP
pm.send('carParams', cp_send)
# carControl
cc_send = messaging.new_message()
cc_send.init('carControl')
cc_send.valid = CS.canValid
cc_send.carControl = CC
pm.send('carControl', cc_send)
return CC, events_bytes
def controlsd_thread(sm=None, pm=None, can_sock=None):
gc.disable()
# start the loop
set_realtime_priority(3)
params = Params()
is_metric = params.get("IsMetric", encoding='utf8') == "1"
is_ldw_enabled = params.get("IsLdwEnabled", encoding='utf8') == "1"
passive = params.get("Passive", encoding='utf8') == "1"
openpilot_enabled_toggle = params.get("OpenpilotEnabledToggle", encoding='utf8') == "1"
community_feature_toggle = params.get("CommunityFeaturesToggle", encoding='utf8') == "1"
passive = passive or not openpilot_enabled_toggle
# Pub/Sub Sockets
if pm is None:
pm = messaging.PubMaster(['sendcan', 'controlsState', 'carState', 'carControl', 'carEvents', 'carParams'])
if sm is None:
sm = messaging.SubMaster(['thermal', 'health', 'liveCalibration', 'driverMonitoring', 'plan', 'pathPlan', \
'model', 'gpsLocation'], ignore_alive=['gpsLocation'])
if can_sock is None:
can_timeout = None if os.environ.get('NO_CAN_TIMEOUT', False) else 100
can_sock = messaging.sub_sock('can', timeout=can_timeout)
# wait for health and CAN packets
hw_type = messaging.recv_one(sm.sock['health']).health.hwType
has_relay = hw_type in [HwType.blackPanda, HwType.uno]
print("Waiting for CAN messages...")
messaging.get_one_can(can_sock)
CI, CP = get_car(can_sock, pm.sock['sendcan'], has_relay)
car_recognized = CP.carName != 'mock'
# If stock camera is disconnected, we loaded car controls and it's not chffrplus
controller_available = CP.enableCamera and CI.CC is not None and not passive
community_feature_disallowed = CP.communityFeature and not community_feature_toggle
read_only = not car_recognized or not controller_available or CP.dashcamOnly or community_feature_disallowed
if read_only:
CP.safetyModel = car.CarParams.SafetyModel.noOutput
# Write CarParams for radard and boardd safety mode
params.put("CarParams", CP.to_bytes())
params.put("LongitudinalControl", "1" if CP.openpilotLongitudinalControl else "0")
CC = car.CarControl.new_message()
AM = AlertManager()
startup_alert = get_startup_alert(car_recognized, controller_available)
AM.add(sm.frame, startup_alert, False)
LoC = LongControl(CP, CI.compute_gb)
VM = VehicleModel(CP)
if CP.lateralTuning.which() == 'pid':
LaC = LatControlPID(CP)
elif CP.lateralTuning.which() == 'indi':
LaC = LatControlINDI(CP)
elif CP.lateralTuning.which() == 'lqr':
LaC = LatControlLQR(CP)
driver_status = DriverStatus()
is_rhd = params.get("IsRHD")
if is_rhd is not None:
driver_status.is_rhd = bool(int(is_rhd))
state = State.disabled
soft_disable_timer = 0
v_cruise_kph = 255
v_cruise_kph_last = 0
mismatch_counter = 0
last_blinker_frame = 0
events_prev = []
sm['liveCalibration'].calStatus = Calibration.INVALID
sm['pathPlan'].sensorValid = True
sm['pathPlan'].posenetValid = True
sm['thermal'].freeSpace = 1.
# detect sound card presence
sounds_available = not os.path.isfile('/EON') or (os.path.isdir('/proc/asound/card0') and open('/proc/asound/card0/state').read().strip() == 'ONLINE')
# controlsd is driven by can recv, expected at 100Hz
rk = Ratekeeper(100, print_delay_threshold=None)
# internet_needed = params.get("Offroad_ConnectivityNeeded", encoding='utf8') is not None
prof = Profiler(False) # off by default
# dragonpilot
ts_last_check = 0.
dragon_toyota_stock_dsu = False
dragon_lat_control = True
dragon_display_steering_limit_alert = True
dragon_stopped_has_lead_count = 0
dragon_lead_car_moving_alert = False
while True:
# dragonpilot, don't check for param too often as it's a kernel call
ts = sec_since_boot()
if ts - ts_last_check > 5.:
dragon_toyota_stock_dsu = True if params.get("DragonToyotaStockDSU", encoding='utf8') == "1" else False
dragon_lat_control = False if params.get("DragonLatCtrl", encoding='utf8') == "0" else True
dragon_display_steering_limit_alert = False if params.get("DragonDisplaySteeringLimitAlert", encoding='utf8') == "0" else True
dragon_lead_car_moving_alert = True if params.get("DragonEnableLeadCarMovingAlert", encoding='utf8') == "1" else False
ts_last_check = ts
start_time = sec_since_boot()
prof.checkpoint("Ratekeeper", ignore=True)
# Sample data and compute car events
CS, events, cal_perc, mismatch_counter = data_sample(CI, CC, sm, can_sock, driver_status, state, mismatch_counter, params)
prof.checkpoint("Sample")
# Create alerts
if not sm.all_alive_and_valid():
events.append(create_event('commIssue', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
if not sm['pathPlan'].mpcSolutionValid:
events.append(create_event('plannerError', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE]))
if not sm['pathPlan'].sensorValid:
events.append(create_event('sensorDataInvalid', [ET.NO_ENTRY, ET.PERMANENT]))
if not sm['pathPlan'].paramsValid:
events.append(create_event('vehicleModelInvalid', [ET.WARNING]))
if not sm['pathPlan'].posenetValid:
events.append(create_event('posenetInvalid', [ET.NO_ENTRY, ET.WARNING]))
if not sm['plan'].radarValid:
events.append(create_event('radarFault', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
if sm['plan'].radarCanError:
events.append(create_event('radarCanError', [ET.NO_ENTRY, ET.SOFT_DISABLE]))
if not CS.canValid:
if dragon_toyota_stock_dsu:
events.append(create_event('pcmDisable', [ET.USER_DISABLE]))
else:
events.append(create_event('canError', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE]))
if not sounds_available:
events.append(create_event('soundsUnavailable', [ET.NO_ENTRY, ET.PERMANENT]))
#if internet_needed:
# events.append(create_event('internetConnectivityNeeded', [ET.NO_ENTRY, ET.PERMANENT]))
if community_feature_disallowed:
events.append(create_event('communityFeatureDisallowed', [ET.PERMANENT]))
if not dragon_toyota_stock_dsu:
# Only allow engagement with brake pressed when stopped behind another stopped car
if CS.brakePressed and sm['plan'].vTargetFuture >= STARTING_TARGET_SPEED and not CP.radarOffCan and CS.vEgo < 0.3:
events.append(create_event('noTarget', [ET.NO_ENTRY, ET.IMMEDIATE_DISABLE]))
if dragon_lead_car_moving_alert:
# when car has a lead and is standstill and lead is barely moving, we start counting
if not CP.radarOffCan and sm['plan'].hasLead and CS.vEgo <= 0.01 and 0.3 >= abs(sm['plan'].vTarget) >= 0:
dragon_stopped_has_lead_count += 1
else:
dragon_stopped_has_lead_count = 0
# when we detect lead car over a sec and the lead car is started moving, we are ready to send alerts
# once the condition is triggered, we want to keep the trigger
if dragon_stopped_has_lead_count >= 100:
if abs(sm['plan'].vTargetFuture) >= 0.1:
events.append(create_event('leadCarMoving', [ET.WARNING]))
else:
events.append(create_event('leadCarDetected', [ET.WARNING]))
# we remove alert once our car is moving
if CS.vEgo > 0.:
dragon_stopped_has_lead_count = 0
if not read_only:
# update control state
state, soft_disable_timer, v_cruise_kph, v_cruise_kph_last = \
state_transition(sm.frame, CS, CP, state, events, soft_disable_timer, v_cruise_kph, AM)
prof.checkpoint("State transition")
# Compute actuators (runs PID loops and lateral MPC)
actuators, v_cruise_kph, driver_status, v_acc, a_acc, lac_log, last_blinker_frame = \
state_control(sm.frame, sm.rcv_frame, sm['plan'], sm['pathPlan'], CS, CP, state, events, v_cruise_kph, v_cruise_kph_last, AM, rk,
driver_status, LaC, LoC, read_only, is_metric, cal_perc, last_blinker_frame, dragon_lat_control, dragon_display_steering_limit_alert, dragon_lead_car_moving_alert)
prof.checkpoint("State Control")
# Publish data
CC, events_prev = data_send(sm, pm, CS, CI, CP, VM, state, events, actuators, v_cruise_kph, rk, AM, driver_status, LaC,
LoC, read_only, start_time, v_acc, a_acc, lac_log, events_prev, last_blinker_frame, is_ldw_enabled)
prof.checkpoint("Sent")
rk.monitor_time()
prof.display()
def main(sm=None, pm=None, logcan=None):
controlsd_thread(sm, pm, logcan)
if __name__ == "__main__":
main()
| []
| []
| [
"NO_CAN_TIMEOUT"
]
| [] | ["NO_CAN_TIMEOUT"] | python | 1 | 0 | |
golang/vendor/github.com/go-openapi/runtime/client/runtime_test.go | // Copyright 2015 go-swagger maintainers
//
// 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 client
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"os"
"testing"
"time"
"golang.org/x/net/context"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/stretchr/testify/assert"
)
// task This describes a task. Tasks require a content property to be set.
type task struct {
// Completed
Completed bool `json:"completed" xml:"completed"`
// Content Task content can contain [GFM](https://help.github.com/articles/github-flavored-markdown/).
Content string `json:"content" xml:"content"`
// ID This id property is autogenerated when a task is created.
ID int64 `json:"id" xml:"id"`
}
func TestRuntime_TLSAuthConfig(t *testing.T) {
var opts TLSClientOptions
opts.CA = "../fixtures/certs/myCA.crt"
opts.Key = "../fixtures/certs/myclient.key"
opts.Certificate = "../fixtures/certs/myclient.crt"
opts.ServerName = "somewhere"
cfg, err := TLSClientAuth(opts)
if assert.NoError(t, err) {
if assert.NotNil(t, cfg) {
assert.Len(t, cfg.Certificates, 1)
assert.NotNil(t, cfg.RootCAs)
assert.Equal(t, "somewhere", cfg.ServerName)
}
}
}
func TestRuntime_Concurrent(t *testing.T) {
// test that it can make a simple request
// and get the response for it.
// defaults all the way down
result := []task{
{false, "task 1 content", 1},
{false, "task 2 content", 2},
}
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime)
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
_ = jsongen.Encode(result)
}))
defer server.Close()
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return nil
})
hu, _ := url.Parse(server.URL)
rt := New(hu.Host, "/", []string{"http"})
resCC := make(chan interface{})
errCC := make(chan error)
var res interface{}
var err error
for j := 0; j < 6; j++ {
go func() {
resC := make(chan interface{})
errC := make(chan error)
go func() {
var resp interface{}
var errp error
for i := 0; i < 3; i++ {
resp, errp = rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Method: "GET",
PathPattern: "/",
Params: rwrtr,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if response.Code() == 200 {
var result []task
if err := consumer.Consume(response.Body(), &result); err != nil {
return nil, err
}
return result, nil
}
return nil, errors.New("Generic error")
}),
})
<-time.After(100 * time.Millisecond)
}
resC <- resp
errC <- errp
}()
resCC <- <-resC
errCC <- <-errC
}()
}
c := 6
for c > 0 {
res = <-resCC
err = <-errCC
c--
}
if assert.NoError(t, err) {
assert.IsType(t, []task{}, res)
actual := res.([]task)
assert.EqualValues(t, result, actual)
}
}
func TestRuntime_Canary(t *testing.T) {
// test that it can make a simple request
// and get the response for it.
// defaults all the way down
result := []task{
{false, "task 1 content", 1},
{false, "task 2 content", 2},
}
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime)
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
_ = jsongen.Encode(result)
}))
defer server.Close()
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return nil
})
hu, _ := url.Parse(server.URL)
rt := New(hu.Host, "/", []string{"http"})
res, err := rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Method: "GET",
PathPattern: "/",
Params: rwrtr,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if response.Code() == 200 {
var result []task
if err := consumer.Consume(response.Body(), &result); err != nil {
return nil, err
}
return result, nil
}
return nil, errors.New("Generic error")
}),
})
if assert.NoError(t, err) {
assert.IsType(t, []task{}, res)
actual := res.([]task)
assert.EqualValues(t, result, actual)
}
}
type tasks struct {
Tasks []task `xml:"task"`
}
func TestRuntime_XMLCanary(t *testing.T) {
// test that it can make a simple XML request
// and get the response for it.
result := tasks{
Tasks: []task{
{false, "task 1 content", 1},
{false, "task 2 content", 2},
},
}
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add(runtime.HeaderContentType, runtime.XMLMime)
rw.WriteHeader(http.StatusOK)
xmlgen := xml.NewEncoder(rw)
_ = xmlgen.Encode(result)
}))
defer server.Close()
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return nil
})
hu, _ := url.Parse(server.URL)
rt := New(hu.Host, "/", []string{"http"})
res, err := rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Method: "GET",
PathPattern: "/",
Params: rwrtr,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if response.Code() == 200 {
var result tasks
if err := consumer.Consume(response.Body(), &result); err != nil {
return nil, err
}
return result, nil
}
return nil, errors.New("Generic error")
}),
})
if assert.NoError(t, err) {
assert.IsType(t, tasks{}, res)
actual := res.(tasks)
assert.EqualValues(t, result, actual)
}
}
func TestRuntime_TextCanary(t *testing.T) {
// test that it can make a simple text request
// and get the response for it.
result := "1: task 1 content; 2: task 2 content"
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add(runtime.HeaderContentType, runtime.TextMime)
rw.WriteHeader(http.StatusOK)
_, _ = rw.Write([]byte(result))
}))
defer server.Close()
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return nil
})
hu, _ := url.Parse(server.URL)
rt := New(hu.Host, "/", []string{"http"})
res, err := rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Method: "GET",
PathPattern: "/",
Params: rwrtr,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if response.Code() == 200 {
var result string
if err := consumer.Consume(response.Body(), &result); err != nil {
return nil, err
}
return result, nil
}
return nil, errors.New("Generic error")
}),
})
if assert.NoError(t, err) {
assert.IsType(t, "", res)
actual := res.(string)
assert.EqualValues(t, result, actual)
}
}
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (fn roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return fn(req)
}
func TestRuntime_CustomTransport(t *testing.T) {
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return nil
})
result := []task{
{false, "task 1 content", 1},
{false, "task 2 content", 2},
}
rt := New("localhost:3245", "/", []string{"ws", "wss", "https"})
rt.Transport = roundTripperFunc(func(req *http.Request) (*http.Response, error) {
if req.URL.Scheme != "https" {
return nil, errors.New("this was not a https request")
}
var resp http.Response
resp.StatusCode = 200
resp.Header = make(http.Header)
resp.Header.Set("content-type", "application/json")
buf := bytes.NewBuffer(nil)
enc := json.NewEncoder(buf)
_ = enc.Encode(result)
resp.Body = ioutil.NopCloser(buf)
return &resp, nil
})
res, err := rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Method: "GET",
PathPattern: "/",
Schemes: []string{"ws", "wss", "https"},
Params: rwrtr,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if response.Code() == 200 {
var result []task
if err := consumer.Consume(response.Body(), &result); err != nil {
return nil, err
}
return result, nil
}
return nil, errors.New("Generic error")
}),
})
if assert.NoError(t, err) {
assert.IsType(t, []task{}, res)
actual := res.([]task)
assert.EqualValues(t, result, actual)
}
}
func TestRuntime_CustomCookieJar(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
authenticated := false
for _, cookie := range req.Cookies() {
if cookie.Name == "sessionid" && cookie.Value == "abc" {
authenticated = true
}
}
if !authenticated {
username, password, ok := req.BasicAuth()
if ok && username == "username" && password == "password" {
authenticated = true
http.SetCookie(rw, &http.Cookie{Name: "sessionid", Value: "abc"})
}
}
if authenticated {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime)
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
_ = jsongen.Encode([]task{})
} else {
rw.WriteHeader(http.StatusUnauthorized)
}
}))
defer server.Close()
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return nil
})
hu, _ := url.Parse(server.URL)
rt := New(hu.Host, "/", []string{"http"})
rt.Jar, _ = cookiejar.New(nil)
submit := func(authInfo runtime.ClientAuthInfoWriter) {
_, err := rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Method: "GET",
PathPattern: "/",
Params: rwrtr,
AuthInfo: authInfo,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if response.Code() == 200 {
return nil, nil
}
return nil, errors.New("Generic error")
}),
})
assert.NoError(t, err)
}
submit(BasicAuth("username", "password"))
submit(nil)
}
func TestRuntime_AuthCanary(t *testing.T) {
// test that it can make a simple request
// and get the response for it.
// defaults all the way down
result := []task{
{false, "task 1 content", 1},
{false, "task 2 content", 2},
}
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.Header.Get("Authorization") != "Bearer the-super-secret-token" {
rw.WriteHeader(400)
return
}
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime)
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
_ = jsongen.Encode(result)
}))
defer server.Close()
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return nil
})
hu, _ := url.Parse(server.URL)
rt := New(hu.Host, "/", []string{"http"})
res, err := rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Params: rwrtr,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if response.Code() == 200 {
var result []task
if err := consumer.Consume(response.Body(), &result); err != nil {
return nil, err
}
return result, nil
}
return nil, errors.New("Generic error")
}),
AuthInfo: BearerToken("the-super-secret-token"),
})
if assert.NoError(t, err) {
assert.IsType(t, []task{}, res)
actual := res.([]task)
assert.EqualValues(t, result, actual)
}
}
func TestRuntime_PickConsumer(t *testing.T) {
result := []task{
{false, "task 1 content", 1},
{false, "task 2 content", 2},
}
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.Header.Get("Content-Type") != "application/octet-stream" {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8")
rw.WriteHeader(400)
return
}
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8")
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
_ = jsongen.Encode(result)
}))
defer server.Close()
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return req.SetBodyParam(bytes.NewBufferString("hello"))
})
hu, _ := url.Parse(server.URL)
rt := New(hu.Host, "/", []string{"http"})
res, err := rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Method: "POST",
PathPattern: "/",
Schemes: []string{"http"},
ConsumesMediaTypes: []string{"application/octet-stream"},
Params: rwrtr,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if response.Code() == 200 {
var result []task
if err := consumer.Consume(response.Body(), &result); err != nil {
return nil, err
}
return result, nil
}
return nil, errors.New("Generic error")
}),
AuthInfo: BearerToken("the-super-secret-token"),
})
if assert.NoError(t, err) {
assert.IsType(t, []task{}, res)
actual := res.([]task)
assert.EqualValues(t, result, actual)
}
}
func TestRuntime_ContentTypeCanary(t *testing.T) {
// test that it can make a simple request
// and get the response for it.
// defaults all the way down
result := []task{
{false, "task 1 content", 1},
{false, "task 2 content", 2},
}
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.Header.Get("Authorization") != "Bearer the-super-secret-token" {
rw.WriteHeader(400)
return
}
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8")
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
_ = jsongen.Encode(result)
}))
defer server.Close()
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return nil
})
hu, _ := url.Parse(server.URL)
rt := New(hu.Host, "/", []string{"http"})
rt.do = nil
res, err := rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Method: "GET",
PathPattern: "/",
Schemes: []string{"http"},
Params: rwrtr,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if response.Code() == 200 {
var result []task
if err := consumer.Consume(response.Body(), &result); err != nil {
return nil, err
}
return result, nil
}
return nil, errors.New("Generic error")
}),
AuthInfo: BearerToken("the-super-secret-token"),
})
if assert.NoError(t, err) {
assert.IsType(t, []task{}, res)
actual := res.([]task)
assert.EqualValues(t, result, actual)
}
}
func TestRuntime_ChunkedResponse(t *testing.T) {
// test that it can make a simple request
// and get the response for it.
// defaults all the way down
result := []task{
{false, "task 1 content", 1},
{false, "task 2 content", 2},
}
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.Header.Get("Authorization") != "Bearer the-super-secret-token" {
rw.WriteHeader(400)
return
}
rw.Header().Add(runtime.HeaderTransferEncoding, "chunked")
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8")
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
_ = jsongen.Encode(result)
}))
defer server.Close()
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return nil
})
//specDoc, err := spec.Load("../../fixtures/codegen/todolist.simple.yml")
hu, _ := url.Parse(server.URL)
rt := New(hu.Host, "/", []string{"http"})
res, err := rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Method: "GET",
PathPattern: "/",
Schemes: []string{"http"},
Params: rwrtr,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if response.Code() == 200 {
var result []task
if err := consumer.Consume(response.Body(), &result); err != nil {
return nil, err
}
return result, nil
}
return nil, errors.New("Generic error")
}),
AuthInfo: BearerToken("the-super-secret-token"),
})
if assert.NoError(t, err) {
assert.IsType(t, []task{}, res)
actual := res.([]task)
assert.EqualValues(t, result, actual)
}
}
func TestRuntime_DebugValue(t *testing.T) {
original := os.Getenv("DEBUG")
// Emtpy DEBUG means Debug is False
_ = os.Setenv("DEBUG", "")
runtime := New("", "/", []string{"https"})
assert.False(t, runtime.Debug)
// Non-Empty Debug means Debug is True
_ = os.Setenv("DEBUG", "1")
runtime = New("", "/", []string{"https"})
assert.True(t, runtime.Debug)
_ = os.Setenv("DEBUG", "true")
runtime = New("", "/", []string{"https"})
assert.True(t, runtime.Debug)
_ = os.Setenv("DEBUG", "foo")
runtime = New("", "/", []string{"https"})
assert.True(t, runtime.Debug)
// Make sure DEBUG is initial value once again
_ = os.Setenv("DEBUG", original)
}
func TestRuntime_OverrideScheme(t *testing.T) {
runtime := New("", "/", []string{"https"})
sch := runtime.pickScheme([]string{"http"})
assert.Equal(t, "https", sch)
}
func TestRuntime_OverrideClient(t *testing.T) {
client := &http.Client{}
runtime := NewWithClient("", "/", []string{"https"}, client)
var i int
runtime.clientOnce.Do(func() { i++ })
assert.Equal(t, client, runtime.client)
assert.Equal(t, 0, i)
}
func TestRuntime_OverrideClientOperation(t *testing.T) {
client := &http.Client{}
rt := NewWithClient("", "/", []string{"https"}, client)
var i int
rt.clientOnce.Do(func() { i++ })
assert.Equal(t, client, rt.client)
assert.Equal(t, 0, i)
var seen *http.Client
rt.do = func(_ context.Context, cl *http.Client, _ *http.Request) (*http.Response, error) {
seen = cl
res := new(http.Response)
res.StatusCode = 200
res.Body = ioutil.NopCloser(bytes.NewBufferString("OK"))
return res, nil
}
client2 := new(http.Client)
client2.Timeout = 3 * time.Second
if assert.NotEqual(t, client, client2) {
_, err := rt.Submit(&runtime.ClientOperation{
Client: client2,
Params: runtime.ClientRequestWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
return nil
}),
Reader: runtime.ClientResponseReaderFunc(func(_ runtime.ClientResponse, _ runtime.Consumer) (interface{}, error) {
return nil, nil
}),
})
if assert.NoError(t, err) {
assert.Equal(t, client2, seen)
}
}
}
func TestRuntime_PreserveTrailingSlash(t *testing.T) {
var redirected bool
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8")
if req.URL.Path == "/api/tasks" {
redirected = true
return
}
if req.URL.Path == "/api/tasks/" {
rw.WriteHeader(http.StatusOK)
}
}))
defer server.Close()
hu, _ := url.Parse(server.URL)
rt := New(hu.Host, "/", []string{"http"})
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
return nil
})
_, err := rt.Submit(&runtime.ClientOperation{
ID: "getTasks",
Method: "GET",
PathPattern: "/api/tasks/",
Params: rwrtr,
Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
if redirected {
return nil, errors.New("expected Submit to preserve trailing slashes - this caused a redirect")
}
if response.Code() == http.StatusOK {
return nil, nil
}
return nil, errors.New("Generic error")
}),
})
assert.NoError(t, err)
}
| [
"\"DEBUG\""
]
| []
| [
"DEBUG"
]
| [] | ["DEBUG"] | go | 1 | 0 | |
quanx/xmly_speed.py | '''
Author: whyour
Github: https://github.com/whyour
Date: 2020-11-19 23:25:22
LastEditors: whyour
LastEditTime: 2020-11-30 13:17:26
'''
import requests
import json
import rsa
import base64
import time
from itertools import groupby
import hashlib
from datetime import datetime, timedelta
import os
import re
# 喜马拉雅极速版
# 使用参考 https://github.com/Zero-S1/xmly_speed/blob/master/xmly_speed.md
###################################################
# 对应方案2: 下载到本地,需要此处填写
cookies1 = "1&_device=iPhone&632AA533-6D8A-44AF-8AB9-D333DEA8CDC9&2.1.9; 1&_token=310589613&ABB2E210140C0EBD264E12609D7EFE6EFDAF3FECA5369AE59BF90BD1A328F2C132817CB297E685M23AA33C51CB2568_; NSUP=42EFC05F%2C42012D0B%2C1617484709888; XD=ayoU1ynH3Hd0my7OKJxjyOuR3B13TZ7wzY1czop9JF+h26PZCSbywjUSbPj1YjCG8b73WetL8stlFnAWQovD3A==; XUM=632AA533-6D8A-44AF-8AB9-D333DEA8CDC9; ainr=0; c-oper=%E6%9C%AA%E7%9F%A5; channel=ios-b1; device_model=iPhone 11; idfa=632AA533-6D8A-44AF-8AB9-D333DEA8CDC9; impl=com.ximalaya.tingLite; ip=10.54.223.235; net-mode=WIFI; res=828%2C1792; _xmLog=h5&9a52d904-5c6a-48ad-8f7d-f6d26fc8b59f&2.2.5"
cookies2 = ""
cookiesList = [cookies1, ] # 多账号准备
# 通知服务
BARK = '' # bark服务,自行搜索; secrets可填;形如jfjqxDx3xxxxxxxxSaK的字符串
SCKEY = '' # Server酱的SCKEY; secrets可填
TG_BOT_TOKEN = '' # tg机器人的TG_BOT_TOKEN; secrets可填
TG_USER_ID = '' # tg机器人的TG_USER_ID; secrets可填
TG_PROXY_IP = '' # tg机器人的TG_PROXY_IP; secrets可填
TG_PROXY_PORT = '' # tg机器人的TG_PROXY_PORT; secrets可填
###################################################
# 对应方案1: GitHub action自动运行,此处无需填写;
if "XMLY_SPEED_COOKIE" in os.environ:
"""
判断是否运行自GitHub action,"XMLY_SPEED_COOKIE" 该参数与 repo里的Secrets的名称保持一致
"""
print("执行自GitHub action")
xmly_speed_cookie = os.environ["XMLY_SPEED_COOKIE"]
cookiesList = [] # 重置cookiesList
for line in xmly_speed_cookie.split('\n'):
if not line:
continue
cookiesList.append(line)
# GitHub action运行需要填写对应的secrets
if "BARK" in os.environ and os.environ["BARK"]:
BARK = os.environ["BARK"]
print("BARK 推送打开")
if "SCKEY" in os.environ and os.environ["SCKEY"]:
BARK = os.environ["SCKEY"]
print("serverJ 推送打开")
if "TG_BOT_TOKEN" in os.environ and os.environ["TG_BOT_TOKEN"] and "TG_USER_ID" in os.environ and os.environ["TG_USER_ID"]:
TG_BOT_TOKEN = os.environ["TG_BOT_TOKEN"]
TG_USER_ID = os.environ["TG_USER_ID"]
print("Telegram 推送打开")
###################################################
# 可选项
# 自定义设备命名,非必须 ;devices=["iPhone7P","huawei"];与cookiesList对应
devices = []
notify_time = 19 # 通知时间,24小时制,默认19
XMLY_ACCUMULATE_TIME = 1 # 希望刷时长的,此处置1,默认打开;关闭置0
UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 iting/1.0.12 kdtunion_iting/1.0 iting(main)/1.0.12/ios_1"
# 非iOS设备的需要的自行修改,自己抓包 与cookie形式类似
def str2dict(str_cookie):
if type(str_cookie) == dict:
return str_cookie
tmp = str_cookie.split(";")
dict_cookie = {}
try:
for i in tmp:
j = i.split("=")
if not j[0]:
continue
dict_cookie[j[0].strip()] = j[1].strip()
assert dict_cookie["1&_token"].split("&")[0]
regex = r"&\d\.\d\.\d+"
appid = "&1.1.9"
dict_cookie["1&_device"] = re.sub(
regex, appid, dict_cookie["1&_device"], 0, re.MULTILINE)
print(dict_cookie["1&_device"])
except (IndexError, KeyError):
print("cookie填写出错 ❌,仔细查看说明")
raise
return dict_cookie
def get_time():
mins = int(time.time())
date_stamp = (mins-57600) % 86400
utc_dt = datetime.utcnow() # UTC时间
bj_dt = utc_dt+timedelta(hours=8) # 北京时间
_datatime = bj_dt.strftime("%Y%m%d", )
notify_time = bj_dt.strftime("%H %M")
print(f"\n当前时间戳: {mins}")
print(f"北京时间: {bj_dt}\n\n")
return mins, date_stamp, _datatime, notify_time
def read(cookies):
print("\n【阅读】")
headers = {
'Host': '51gzdhh.xyz',
'accept': 'application/json, text/plain, */*',
'origin': 'http://xiaokuohao.work',
'user-agent': 'Mozilla/5.0 (Linux; Android 6.0.1; MI 6 Plus Build/V417IR; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/52.0.2743.100 Mobile Safari/537.36 iting(main)/1.8.18/android_1 kdtUnion_iting/1.8.18',
'referer': 'http://xiaokuohao.work/static/web/dxmly/index.html',
'accept-encoding': 'gzip, deflate',
'accept-language': 'zh-CN,en-US;q=0.8',
'x-requested-with': 'com.ximalaya.ting.lite',
}
params = (
('hid', '233'),
)
try:
response = requests.get(
'https://51gzdhh.xyz/api/new/newConfig', headers=headers, params=params)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
result = response.json()
pid = str(result["pid"])
headers = {
'Host': '51gzdhh.xyz',
'content-length': '37',
'accept': 'application/json, text/plain, */*',
'origin': 'http://xiaokuohao.work',
'user-agent': 'Mozilla/5.0 (Linux; Android 6.0.1; MI 6 Plus Build/V417IR; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/52.0.2743.100 Mobile Safari/537.36 iting(main)/1.8.18/android_1 kdtUnion_iting/1.8.18',
'content-type': 'application/x-www-form-urlencoded',
'referer': 'http://xiaokuohao.work/static/web/dxmly/index.html',
'accept-encoding': 'gzip, deflate',
'accept-language': 'zh-CN,en-US;q=0.8',
'x-requested-with': 'com.ximalaya.ting.lite',
}
uid = get_uid(cookies)
data = {"pid": str(pid), "mtuserid": uid}
try:
response = requests.post(
'https://51gzdhh.xyz/api/new/hui/complete', headers=headers, data=json.dumps(data))
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
result = response.json()
if result["status"] == -2:
# print("无法阅读,尝试从安卓端手动开启")
return
# print(result["completeList"])
if result["isComplete"] or result["count_finish"] == 9:
print("今日完成阅读")
return
headers = {
'Host': '51gzdhh.xyz',
'accept': 'application/json, text/plain, */*',
'origin': 'http://xiaokuohao.work',
'user-agent': 'Mozilla/5.0 (Linux; Android 6.0.1; MI 6 Plus Build/V417IR; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/52.0.2743.100 Mobile Safari/537.36 iting(main)/1.8.18/android_1 kdtUnion_iting/1.8.18',
'referer': 'http://xiaokuohao.work/static/web/dxmly/index.html',
'accept-encoding': 'gzip, deflate',
'accept-language': 'zh-CN,en-US;q=0.8',
'x-requested-with': 'com.ximalaya.ting.lite',
}
taskIds = set(['242', '239', '241', '240', '238', '236',
'237', '235', '234'])-set(result["completeList"])
params = (
('userid', str(uid)),
('pid', pid),
('taskid', taskIds.pop()),
('imei', ''),
)
try:
response = requests.get(
'https://51gzdhh.xyz/new/userCompleteNew', headers=headers, params=params)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return 0
result = response.json()
print(result)
def ans_receive(cookies, paperId, lastTopicId, receiveType):
headers = {
'User-Agent': UserAgent,
'Content-Type': 'application/json;charset=utf-8',
'Host': 'm.ximalaya.com',
'Origin': 'https://m.ximalaya.com',
'Referer': 'https://m.ximalaya.com/growth-ssr-speed-welfare-center/page/quiz',
}
_checkData = f"""lastTopicId={lastTopicId}&numOfAnswers=3&receiveType={receiveType}"""
checkData = rsa_encrypt(str(_checkData), pubkey_str)
data = {
"paperId": paperId,
"checkData": checkData,
"lastTopicId": lastTopicId,
"numOfAnswers": 3,
"receiveType": receiveType
}
try:
response = requests.post('https://m.ximalaya.com/speed/web-earn/topic/receive',
headers=headers, cookies=cookies, data=json.dumps(data))
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return 0
return response.json()
def ans_restore(cookies):
headers = {
'User-Agent': UserAgent,
'Content-Type': 'application/json;charset=utf-8',
'Host': 'm.ximalaya.com',
'Origin': 'https://m.ximalaya.com',
'Referer': 'https://m.ximalaya.com/growth-ssr-speed-welfare-center/page/quiz',
}
checkData = rsa_encrypt("restoreType=2", pubkey_str)
data = {
"restoreType": 2,
"checkData": checkData,
}
try:
response = requests.post('https://m.ximalaya.com/speed/web-earn/topic/restore',
headers=headers, cookies=cookies, data=json.dumps(data))
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return 0
result = response.json()
if "errorCode" in result:
return 0
return 1
def ans_getTimes(cookies):
headers = {
'Host': 'm.ximalaya.com',
'Accept': 'application/json, text/plain, */*',
'Connection': 'keep-alive',
'User-Agent': UserAgent,
'Accept-Language': 'zh-cn',
'Referer': 'https://m.ximalaya.com/growth-ssr-speed-welfare-center/page/quiz',
'Accept-Encoding': 'gzip, deflate, br',
}
try:
response = requests.get(
'https://m.ximalaya.com/speed/web-earn/topic/user', headers=headers, cookies=cookies)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return {"stamina": 0,
"remainingTimes": 0}
print(response.text)
result = response.json()
stamina = result["data"]["stamina"]
remainingTimes = result["data"]["remainingTimes"]
return {"stamina": stamina,
"remainingTimes": remainingTimes}
def ans_start(cookies):
headers = {
'Host': 'm.ximalaya.com',
'Accept': 'application/json, text/plain, */*',
'Connection': 'keep-alive',
'User-Agent': UserAgent,
'Accept-Language': 'zh-cn',
'Referer': 'https://m.ximalaya.com/growth-ssr-speed-welfare-center/page/quiz',
'Accept-Encoding': 'gzip, deflate, br',
}
try:
response = requests.get(
'https://m.ximalaya.com/speed/web-earn/topic/start', headers=headers, cookies=cookies)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return 0, 0, 0
# print(response.text)
result = response.json()
try:
paperId = result["data"]["paperId"]
dateStr = result["data"]["dateStr"]
lastTopicId = result["data"]["topics"][2]["topicId"]
print(paperId, dateStr, lastTopicId)
return paperId, dateStr, lastTopicId
except:
print("❌1 重新抓包 2 手动答题")
return 0, 0, 0
def _str2key(s):
b_str = base64.b64decode(s)
if len(b_str) < 162:
return False
hex_str = ''
for x in b_str:
h = hex(x)[2:]
h = h.rjust(2, '0')
hex_str += h
m_start = 29 * 2
e_start = 159 * 2
m_len = 128 * 2
e_len = 3 * 2
modulus = hex_str[m_start:m_start + m_len]
exponent = hex_str[e_start:e_start + e_len]
return modulus, exponent
def rsa_encrypt(s, pubkey_str):
key = _str2key(pubkey_str)
modulus = int(key[0], 16)
exponent = int(key[1], 16)
pubkey = rsa.PublicKey(modulus, exponent)
return base64.b64encode(rsa.encrypt(s.encode(), pubkey)).decode()
pubkey_str = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVhaR3Or7suUlwHUl2Ly36uVmboZ3+HhovogDjLgRE9CbaUokS2eqGaVFfbxAUxFThNDuXq/fBD+SdUgppmcZrIw4HMMP4AtE2qJJQH/KxPWmbXH7Lv+9CisNtPYOlvWJ/GHRqf9x3TBKjjeJ2CjuVxlPBDX63+Ecil2JR9klVawIDAQAB"
def lottery_info(cookies):
print("\n【幸运大转盘】")
"""
转盘信息查询
"""
headers = {
'Host': 'm.ximalaya.com',
'Accept': 'application/json, text/plain, */*',
'Connection': 'keep-alive',
'User-Agent': UserAgent,
'Accept-Language': 'zh-cn',
'Referer': 'https://m.ximalaya.com/xmds-node-spa/apps/speed-ad-sweepstake-h5/home',
'Accept-Encoding': 'gzip, deflate, br',
}
try:
response = requests.get(
'https://m.ximalaya.com/speed/web-earn/inspire/lottery/info', headers=headers, cookies=cookies)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
result = response.json()
remainingTimes = result["data"]["remainingTimes"]
print(f'转盘info: {result["data"]}\n')
if remainingTimes in [0, 1]:
print("今日完毕")
return
response = requests.get(
'https://m.ximalaya.com/speed/web-earn/inspire/lottery/token', headers=headers, cookies=cookies)
print("token", response.text)
token = response.json()["data"]["id"]
data = {
"token": token,
"sign": rsa_encrypt(f"token={token}&userId={get_uid(cookies)}", pubkey_str),
}
response = requests.post('https://m.ximalaya.com/speed/web-earn/inspire/lottery/chance',
headers=headers, cookies=cookies, data=json.dumps(data))
result = response.json()
print("chance", result)
data = {
"sign": rsa_encrypt(str(result["data"]["chanceId"]), pubkey_str),
}
response = requests.post('https://m.ximalaya.com/speed/web-earn/inspire/lottery/action',
headers=headers, cookies=cookies, data=json.dumps(data))
print(response.text)
def index_baoxiang_award(cookies):
print("\n 【首页、宝箱奖励及翻倍】")
headers = {
'User-Agent': UserAgent,
'Host': 'mobile.ximalaya.com',
}
uid = cookies["1&_token"].split("&")[0]
currentTimeMillis = int(time.time()*1000)-2
try:
response = requests.post('https://mobile.ximalaya.com/pizza-category/activity/getAward?activtyId=baoxiangAward',
headers=headers, cookies=cookies)
except:
return
result = response.json()
print("宝箱奖励: ", result)
if "ret" in result and result["ret"] == 0:
awardReceiveId = result["awardReceiveId"]
headers = {
'Host': 'mobile.ximalaya.com',
'Accept': '*/*',
'User-Agent': UserAgent,
'Accept-Language': 'zh-Hans-CN;q=1, en-CN;q=0.9',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
}
params = (
('activtyId', 'baoxiangAward'),
('awardReceiveId', awardReceiveId),
)
try:
response = requests.get('http://mobile.ximalaya.com/pizza-category/activity/awardMultiple',
headers=headers, params=params, cookies=cookies)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
print("翻倍 ", response.text)
uid = get_uid(cookies)
###################################
params = (
('activtyId', 'indexSegAward'),
('ballKey', str(uid)),
('currentTimeMillis', str(currentTimeMillis)),
('sawVideoSignature', f'{currentTimeMillis}+{uid}'),
('version', '2'),
)
try:
response = requests.get('https://mobile.ximalaya.com/pizza-category/activity/getAward',
headers=headers, cookies=cookies, params=params)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
result = response.json()
print("首页奖励: ", result)
if "ret" in result and result["ret"] == 0:
awardReceiveId = result["awardReceiveId"]
headers = {
'Host': 'mobile.ximalaya.com',
'Accept': '*/*',
'User-Agent': UserAgent,
'Accept-Language': 'zh-Hans-CN;q=1, en-CN;q=0.9',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
}
params = (
('activtyId', 'indexSegAward'),
('awardReceiveId', awardReceiveId),
)
try:
response = requests.get('http://mobile.ximalaya.com/pizza-category/activity/awardMultiple',
headers=headers, params=params, cookies=cookies)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
print("翻倍: ", response.text)
def checkin(cookies, _datatime):
print("\n【连续签到】")
headers = {
'Host': 'm.ximalaya.com',
'Accept': 'application/json, text/plain, */*',
'Connection': 'keep-alive',
'User-Agent': UserAgent,
'Accept-Language': 'zh-cn',
'Referer': 'https://m.ximalaya.com/growth-ssr-speed-welfare-center/page/welfare',
'Accept-Encoding': 'gzip, deflate, br',
}
params = (
('time', f"""{int(time.time()*1000)}"""),
)
try:
response = requests.get('https://m.ximalaya.com/speed/task-center/check-in/record',
headers=headers, params=params, cookies=cookies)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return 0
result = json.loads(response.text)
print(result)
print(f"""连续签到{result["continuousDays"]}/{result["historyDays"]}天""")
print(result["isTickedToday"])
if not result["isTickedToday"]:
print("!!!开始签到")
# if result["canMakeUp"]:
# print("canMakeUp 第30天需要手动")
# return
headers = {
'User-Agent': UserAgent,
'Content-Type': 'application/json;charset=utf-8',
'Host': 'm.ximalaya.com',
'Origin': 'https://m.ximalaya.com',
'Referer': 'https://m.ximalaya.com/growth-ssr-speed-welfare-center/page/welfare',
}
uid = get_uid(cookies)
data = {
"checkData": rsa_encrypt(f"date={_datatime}&uid={uid}", pubkey_str),
"makeUp": False
}
response = requests.post('https://m.ximalaya.com/speed/task-center/check-in/check',
headers=headers, cookies=cookies, data=json.dumps(data))
print(response.text)
return result["continuousDays"]
def ad_score(cookies, businessType, taskId):
headers = {
'Host': 'm.ximalaya.com',
'Accept': 'application/json, text/plain ,*/*',
'Connection': 'keep-alive',
'User-Agent': UserAgent,
'Accept-Language': 'zh-cn',
'Content-Type': 'application/json;charset=utf-8',
'Accept-Encoding': 'gzip, deflate, br',
}
try:
response = requests.get(
'https://m.ximalaya.com/speed/task-center/ad/token', headers=headers, cookies=cookies)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
result = response.json()
token = result["id"]
uid = get_uid(cookies)
data = {
"taskId": taskId,
"businessType": businessType,
"rsaSign": rsa_encrypt(f"""businessType={businessType}&token={token}&uid={uid}""", pubkey_str),
}
try:
response = requests.post(f'https://m.ximalaya.com/speed/task-center/ad/score',
headers=headers, cookies=cookies, data=json.dumps(data))
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
print(response.text)
print("\n")
def bubble(cookies):
print("\n【bubble】")
headers = {
'User-Agent': UserAgent,
'Content-Type': 'application/json;charset=utf-8',
'Host': 'm.ximalaya.com',
'Origin': 'https://m.ximalaya.com',
'Referer': 'https://m.ximalaya.com/xmds-node-spa/apps/speed-growth-open-components/bubble',
}
uid = get_uid(cookies)
data = {"listenTime": "41246", "signature": "2b1cc9e8831cff8874d9c",
"currentTimeMillis": "1596695606145", "uid": uid, "expire": False}
try:
response = requests.post('https://m.ximalaya.com/speed/web-earn/listen/bubbles',
headers=headers, cookies=cookies, data=json.dumps(data))
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
result = response.json()
# print(result)
if not result["data"]["effectiveBubbles"]:
print("暂无有效气泡")
return
for i in result["data"]["effectiveBubbles"]:
print(i["id"])
tmp = receive(cookies, i["id"])
if "errorCode" in tmp:
print("❌ 每天手动收听一段时间,暂无其他方法")
return
time.sleep(1)
ad_score(cookies, 7, i["id"])
for i in result["data"]["expiredBubbles"]:
ad_score(cookies, 6, i["id"])
def receive(cookies, taskId):
headers = {
'Host': 'm.ximalaya.com',
'Accept': 'application/json, text/plain, */*',
'Connection': 'keep-alive',
'User-Agent': UserAgent,
'Accept-Language': 'zh-cn',
'Referer': 'https://m.ximalaya.com/xmds-node-spa/apps/speed-growth-open-components/bubble',
'Accept-Encoding': 'gzip, deflate, br',
}
try:
response = requests.get(
f'https://m.ximalaya.com/speed/web-earn/listen/receive/{taskId}', headers=headers, cookies=cookies)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
print("receive: ", response.text)
return response.json()
def getOmnipotentCard(cookies, mins, date_stamp, _datatime):
print("\n 【领取万能卡】")
headers = {
'User-Agent': UserAgent,
'Content-Type': 'application/json;charset=utf-8',
'Host': 'm.ximalaya.com',
'Origin': 'https://m.ximalaya.com',
'Referer': 'https://m.ximalaya.com/xmds-node-spa/apps/speed-growth-activities/card-collection/home',
}
try:
count = requests.get('https://m.ximalaya.com/speed/web-earn/card/omnipotentCardInfo',
headers=headers, cookies=cookies,).json()["data"]["count"]
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
if count == 5:
print("今日已满")
return
token = requests.get('https://m.ximalaya.com/speed/web-earn/card/token/1',
headers=headers, cookies=cookies,).json()["data"]["id"]
uid = get_uid(cookies)
data = {
"listenTime": mins-date_stamp,
"signData": rsa_encrypt(f"{_datatime}{token}{uid}", pubkey_str),
"token": token
}
try:
response = requests.post('https://m.ximalaya.com/speed/web-earn/card/getOmnipotentCard',
headers=headers, cookies=cookies, data=json.dumps(data))
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
print(response.text)
def cardReportTime(cookies, mins, date_stamp, _datatime):
print("\n【收听获得抽卡机会】")
headers = {
'User-Agent': UserAgent,
'Content-Type': 'application/json;charset=utf-8',
'Host': 'm.ximalaya.com',
'Origin': 'https://m.ximalaya.com',
'Referer': 'https://m.ximalaya.com/xmds-node-spa/apps/speed-growth-activities/card-collection/home',
}
listenTime = mins-date_stamp
uid = get_uid(cookies)
data = {"listenTime": listenTime,
"signData": rsa_encrypt(f"{_datatime}{listenTime}{uid}", pubkey_str), }
try:
response = requests.post('https://m.ximalaya.com/speed/web-earn/card/reportTime',
headers=headers, cookies=cookies, data=json.dumps(data)).json()
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
try:
response["data"]["upperLimit"]
print("今日已达上限")
except:
return
def account(cookies):
print("\n【 打印账号信息】")
headers = {
'Host': 'm.ximalaya.com',
'Content-Type': 'application/json;charset=utf-8',
'Connection': 'keep-alive',
'Accept': 'application/json, text/plain, */*',
'User-Agent': UserAgent,
'Referer': 'https://m.ximalaya.com/speed/web-earn/wallet',
'Accept-Language': 'zh-cn',
'Accept-Encoding': 'gzip, deflate, br',
}
try:
response = requests.get(
'https://m.ximalaya.com/speed/web-earn/account/coin', headers=headers, cookies=cookies)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return '', '', ''
result = response.json()
total = result["total"]/10000
todayTotal = result["todayTotal"]/10000
historyTotal = result["historyTotal"]/10000
print(f"""
当前剩余:{total}
今日获得:{todayTotal}
累计获得:{historyTotal}
""")
return total, todayTotal, historyTotal
def answer(cookies):
print("\n【答题】")
ans_times = ans_getTimes(cookies)
if not ans_times:
return
if ans_times["stamina"] == 0:
print("时间未到")
for _ in range(ans_times["stamina"]):
paperId, _, lastTopicId = ans_start(cookies)
if paperId == 0:
return
tmp = ans_receive(cookies, paperId, lastTopicId, 1)
print(tmp)
if "errorCode" in tmp:
print("❌ 每天手动收听一段时间,暂无其他方法")
return
time.sleep(1)
tmp = ans_receive(cookies, paperId, lastTopicId, 2)
print(tmp)
if tmp == 0:
return
time.sleep(1)
if ans_times["remainingTimes"] > 0:
print("[看视频回复体力]")
if ans_restore(cookies) == 0:
return
for _ in range(5):
paperId, _, lastTopicId = ans_start(cookies)
if paperId == 0:
return
tmp = ans_receive(cookies, paperId, lastTopicId, 1)
print(tmp)
if "errorCode" in tmp:
print("❌ 每天手动收听一段时间,暂无其他方法")
return
time.sleep(1)
tmp = ans_receive(cookies, paperId, lastTopicId, 2)
print(tmp)
if tmp == 0:
return
time.sleep(1)
def saveListenTime(cookies, date_stamp):
print("\n【刷时长1】")
headers = {
'User-Agent': UserAgent,
'Host': 'mobile.ximalaya.com',
'Content-Type': 'application/x-www-form-urlencoded',
}
listentime = date_stamp
print(f"上传本地收听时长1: {listentime//60}分钟")
currentTimeMillis = int(time.time()*1000)-2
uid = get_uid(cookies)
sign = hashlib.md5(
f'currenttimemillis={currentTimeMillis}&listentime={listentime}&uid={uid}&23627d1451047b8d257a96af5db359538f081d651df75b4aa169508547208159'.encode()).hexdigest()
data = {
'activtyId': 'listenAward',
'currentTimeMillis': currentTimeMillis,
'listenTime': str(listentime),
'nativeListenTime': str(listentime),
'signature': sign,
'uid': uid
}
try:
response = requests.post('http://mobile.ximalaya.com/pizza-category/ball/saveListenTime',
headers=headers, cookies=cookies, data=data)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
print(response.text)
def listenData(cookies, date_stamp):
print("\n【刷时长2】")
headers = {
'User-Agent': 'ting_v1.1.9_c5(CFNetwork, iOS 14.0.1, iPhone9,2)',
'Host': 'm.ximalaya.com',
'Content-Type': 'application/json',
}
listentime = date_stamp-1
print(f"上传本地收听时长2: {listentime//60}分钟")
currentTimeMillis = int(time.time()*1000)
uid = get_uid(cookies)
sign = hashlib.md5(
f'currenttimemillis={currentTimeMillis}&listentime={listentime}&uid={uid}&23627d1451047b8d257a96af5db359538f081d651df75b4aa169508547208159'.encode()).hexdigest()
data = {
'currentTimeMillis': currentTimeMillis,
'listenTime': str(listentime),
'signature': sign,
'uid': uid
}
try:
response = requests.post('http://m.ximalaya.com/speed/web-earn/listen/client/data',
headers=headers, cookies=cookies, data=json.dumps(data))
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
print(response.text)
def card_exchangeCoin(cookies, themeId, cardIdList, _datatime):
headers = {
'Host': 'm.ximalaya.com',
'Accept': 'application/json, text/plain, */*',
'Connection': 'keep-alive',
'User-Agent': UserAgent,
'Accept-Language': 'zh-cn',
'Referer': 'https://m.ximalaya.com/xmds-node-spa/apps/speed-growth-activities/card-collection/home',
'Accept-Encoding': 'gzip, deflate, br',
}
token = requests.get('https://m.ximalaya.com/speed/web-earn/card/token/3',
headers=headers, cookies=cookies,).json()["data"]["id"]
uid = get_uid(cookies)
data = {
"cardIdList": cardIdList,
"themeId": themeId,
"signData": rsa_encrypt(f"{_datatime}{token}{uid}", pubkey_str),
"token": token
}
headers = {
'User-Agent': UserAgent,
'Content-Type': 'application/json;charset=utf-8',
'Host': 'm.ximalaya.com',
'Origin': 'https://m.ximalaya.com',
'Referer': 'https://m.ximalaya.com/xmds-node-spa/apps/speed-growth-activities/card-collection/home',
}
try:
response = requests.post('https://m.ximalaya.com/speed/web-earn/card/exchangeCoin',
headers=headers, cookies=cookies, data=json.dumps(data))
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
print("card_exchangeCoin: ", response.text)
def card_exchangeCard(cookies, toCardAwardId, fromRecordIdList):
fromRecordIdList = sorted(fromRecordIdList)
headers = {
'User-Agent': UserAgent,
'Content-Type': 'application/json;charset=utf-8',
'Host': 'm.ximalaya.com',
'Origin': 'https://m.ximalaya.com',
'Referer': 'https://m.ximalaya.com/xmds-node-spa/apps/speed-growth-activities/card-collection/home',
}
data = {
"toCardAwardId": toCardAwardId,
"fromRecordIdList": fromRecordIdList,
"exchangeType": 1,
}
try:
response = requests.post('https://m.ximalaya.com/speed/web-earn/card/exchangeCard',
headers=headers, cookies=cookies, data=json.dumps(data))
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
print(response.text)
def draw_5card(cookies, drawRecordIdList): # 五连抽
drawRecordIdList = sorted(drawRecordIdList)
headers = {
'User-Agent': UserAgent,
'Content-Type': 'application/json;charset=utf-8',
'Host': 'm.ximalaya.com',
'Origin': 'https://m.ximalaya.com',
'Referer': 'https://m.ximalaya.com/xmds-node-spa/apps/speed-growth-activities/card-collection/home',
}
uid = get_uid(cookies)
data = {
"signData": rsa_encrypt(f"{''.join(str(i) for i in drawRecordIdList)}{uid}", pubkey_str),
"drawRecordIdList": drawRecordIdList,
"drawType": 2,
}
try:
response = requests.post('https://m.ximalaya.com/speed/web-earn/card/draw',
headers=headers, cookies=cookies, data=json.dumps(data))
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
print("五连抽: ", response.text)
def card(cookies, _datatime):
print("\n【抽卡】")
headers = {
'Host': 'm.ximalaya.com',
'Accept': 'application/json, text/plain, */*',
'Connection': 'keep-alive',
'User-Agent': UserAgent,
'Accept-Language': 'zh-cn',
'Referer': 'https://m.ximalaya.com/xmds-node-spa/apps/speed-growth-activities/card-collection/home',
'Accept-Encoding': 'gzip, deflate, br',
}
try:
response = requests.get(
'https://m.ximalaya.com/speed/web-earn/card/userCardInfo', headers=headers, cookies=cookies)
except:
print("网络请求异常,为避免GitHub action报错,直接跳过")
return
data = response.json()["data"]
#######
# 5连抽
drawRecordIdList = data["drawRecordIdList"]
print("抽卡机会: ", drawRecordIdList)
for _ in range(len(drawRecordIdList)//5):
tmp = []
for _ in range(5):
tmp.append(drawRecordIdList.pop())
draw_5card(cookies, tmp)
########
# 手牌兑换金币
# 1 万能卡 10 碎片
print("检查手牌,卡牌兑金币")
themeId_id_map = {
2: [2, 3],
3: [4, 5, 6, 7],
4: [8, 9, 10, 11, 12],
5: [13, 14, 15, 16, 17, 18],
6: [19, 20, 21, 22],
7: [23, 24, 25, 26, 27],
8: [28, 29, 30, 31, 32],
9: [33, 34, 35, 36, 37]
}
try:
response = requests.get(
'https://m.ximalaya.com/speed/web-earn/card/userCardInfo', headers=headers, cookies=cookies)
except:
return
data = response.json()["data"]
userCardsList = data["userCardsList"] # 手牌
lstg = groupby(userCardsList, key=lambda x: x["themeId"])
for key, group in lstg:
if key in [1, 10]:
continue
themeId = key
ids = list(group)
tmp_recordId = []
tmp_id = []
for i in ids:
if i["id"] in tmp_id:
continue
tmp_recordId.append(i["recordId"])
tmp_id.append(i["id"])
if len(tmp_recordId) == len(themeId_id_map[key]):
print("可以兑换")
card_exchangeCoin(cookies, themeId, tmp_recordId, _datatime)
###############
# 万能卡兑换稀有卡
response = requests.get(
'https://m.ximalaya.com/speed/web-earn/card/userCardInfo', headers=headers, cookies=cookies)
data = response.json()["data"]
userCardsList = data["userCardsList"]
omnipotentCard = [i for i in userCardsList if i["id"] == 1]
cityCardId = [i["id"] for i in userCardsList if i["themeId"] == 9]
need = set(themeId_id_map[9])-set(cityCardId)
print("万能卡: ", [i['recordId'] for i in omnipotentCard])
for _ in range(len(omnipotentCard)//4):
tmp = []
for _ in range(4):
tmp.append(omnipotentCard.pop())
fromRecordIdList = [i['recordId'] for i in tmp]
if need:
print("万能卡兑换稀有卡:")
card_exchangeCard(cookies, need.pop(), fromRecordIdList)
def get_uid(cookies):
return cookies["1&_token"].split("&")[0]
def serverJ(title, content):
print("\n")
sckey = SCKEY
if "SCKEY" in os.environ:
"""
判断是否运行自GitHub action,"SCKEY" 该参数与 repo里的Secrets的名称保持一致
"""
sckey = os.environ["SCKEY"]
if not sckey:
print("server酱服务的SCKEY未设置!!\n取消推送")
return
print("serverJ服务启动")
data = {
"text": title,
"desp": content.replace("\n", "\n\n")+"\n\n [打赏作者](https://github.com/Zero-S1/xmly_speed/blob/master/thanks.md)"
}
response = requests.post(f"https://sc.ftqq.com/{sckey}.send", data=data)
print(response.text)
def bark(title, content):
print("\n")
bark_token = BARK
if "BARK" in os.environ:
bark_token = os.environ["BARK"]
if not bark_token:
print("bark服务的bark_token未设置!!\n取消推送")
return
print("bark服务启动")
response = requests.get(
f"""https://api.day.app/{bark_token}/{title}/{content}""")
print(response.text)
def telegram(title, content):
print("\n")
bot_token = TG_BOT_TOKEN
user_id = TG_USER_ID
if not bot_token or not user_id:
print("tg服务的bot_token或者user_id未设置!!\n取消推送")
return
print("tg服务启动")
url=f"https://api.telegram.org/bot{TG_BOT_TOKEN}/sendMessage"
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'chat_id': str(TG_USER_ID), 'text': f"""{title}\n\n{content}""", 'disable_web_page_preview': 'true'}
proxyStr = "http://{}:{}".format(TG_PROXY_IP, TG_PROXY_PORT)
proxies = {"http": proxyStr, "https": proxyStr }
response = requests.post(url=url,headers=headers, params=payload,proxies=proxies)
print(response.text)
def run():
print(f"喜马拉雅极速版 (https://github.com/Zero-S1/xmly_speed/blob/master/xmly_speed.md ) ,欢迎打赏¯\(°_o)/¯")
mins, date_stamp, _datatime, _notify_time = get_time()
table = []
for k, v in enumerate(cookiesList):
print(f">>>>>>>【账号开始{k+1}】\n")
cookies = str2dict(v)
if XMLY_ACCUMULATE_TIME == 1:
saveListenTime(cookies, date_stamp)
listenData(cookies, date_stamp)
read(cookies) # 阅读
bubble(cookies) # 收金币气泡
# continue
continuousDays = checkin(cookies, _datatime) # 自动签到
# lottery_info(cookies) # 大转盘4次
answer(cookies) # 答题赚金币
cardReportTime(cookies, mins, date_stamp, _datatime) # 卡牌
getOmnipotentCard(cookies, mins, date_stamp, _datatime) # 领取万能卡
card(cookies, _datatime) # 抽卡
index_baoxiang_award(cookies) # 首页、宝箱奖励及翻倍
total, todayTotal, historyTotal = account(cookies)
try:
device = devices[k]
except IndexError:
device = cookies['device_model']
else:
device = f"设备{k+1}"
table.append((device, total, todayTotal,
historyTotal, continuousDays,))
print("###"*20)
print("\n"*4)
if int(_notify_time.split()[0]) == notify_time and int(_notify_time.split()[1]) >= 30:
# if 1:
message = ''
for i in table:
message += f"设备:{i[0].replace(' ',''):<9}\n"
message += f"当前剩余:{i[1]:<6.2f}\n"
message += f"今天:+{i[2]:<4.2f}\n"
message += f"历史:{i[3]:<7.2f}\n"
message += f"连续签到:{i[4]}/30\n"
bark("⏰ 喜马拉雅极速版", message)
serverJ("⏰ 喜马拉雅极速版", message)
telegram("⏰ 喜马拉雅极速版", message)
if __name__ == "__main__":
run()
| []
| []
| [
"SCKEY",
"XMLY_SPEED_COOKIE",
"BARK",
"TG_BOT_TOKEN",
"TG_USER_ID"
]
| [] | ["SCKEY", "XMLY_SPEED_COOKIE", "BARK", "TG_BOT_TOKEN", "TG_USER_ID"] | python | 5 | 0 | |
paste_test.go | package hibp
import (
"fmt"
"os"
"testing"
)
// TestPasteAccount tests the BreachedAccount() method of the breaches API
func TestPasteAccount(t *testing.T) {
testTable := []struct {
testName string
accountName string
isBreached bool
shouldFail bool
}{
{"account-exists is breached once", "[email protected]", true, false},
{"opt-out is not breached", "[email protected]", false, true},
{"empty account name", "", false, true},
}
apiKey := os.Getenv("HIBP_API_KEY")
if apiKey == "" {
t.SkipNow()
}
hc := New(WithApiKey(apiKey), WithRateLimitSleep())
for _, tc := range testTable {
t.Run(tc.testName, func(t *testing.T) {
pasteDetails, _, err := hc.PasteApi.PastedAccount(tc.accountName)
if err != nil && !tc.shouldFail {
t.Error(err)
}
if pasteDetails == nil && tc.isBreached {
t.Errorf("breach for the account %q is expected, but returned 0 results.",
tc.accountName)
}
if pasteDetails != nil && !tc.isBreached {
t.Errorf("breach for the account %q is expected to be not breached, but returned breach details.",
tc.accountName)
}
})
}
}
// ExamplePasteApi_PastedAccount is a code example to show how to fetch a specific paste
// based on its name from the HIBP pastes API using the PastedAccount() method
func ExamplePasteApi_PastedAccount() {
apiKey := os.Getenv("HIBP_API_KEY")
if apiKey == "" {
panic("A API key is required for this API")
}
hc := New(WithApiKey(apiKey))
pd, _, err := hc.PasteApi.PastedAccount("[email protected]")
if err != nil {
panic(err)
}
for _, p := range pd {
fmt.Printf("Your account was part of the %q paste\n", p.Title)
}
}
| [
"\"HIBP_API_KEY\"",
"\"HIBP_API_KEY\""
]
| []
| [
"HIBP_API_KEY"
]
| [] | ["HIBP_API_KEY"] | go | 1 | 0 | |
modules/services/cache_service.py | import os
import redis
from modules.utils.yaml_parser import Config
import logging
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
class CacheService:
# retrieve caching properties from config
cache_ttl = int(Config.get_config_val(key="cache", key_1depth="ttl"))
cache_max_size = int(Config.get_config_val(key="cache", key_1depth="max_size"))
cache = redis.from_url(Config.get_config_val(key="cache", key_1depth="redis_url")) # instead use a wrapper and retrieve from os.environ.get("REDIS_URL")
# create a cache service
# cache = TTLCache(maxsize=cache_max_size, ttl=cache_ttl)
@classmethod
def get_object(cls, key):
"""
retrieves the object from cache
:param key:
:return:
"""
value = None
try:
if cls.cache.exists(key) == 1:
value = cls.cache.get(key).decode("utf-8")
else:
value = None
except KeyError as ke:
logger.error("Either key expired or not present : {0}".format(ke))
value = None
except Exception as e:
logger.error("internal exception while using cache : {0}".format(e))
value = None
return value
@classmethod
def set_object(cls, key, value):
logger.info("key : {0}, value : {1}".format(key, value))
cls.cache.set(key, value, ex=cls.cache_ttl)
@classmethod
def remove_objects(cls, key):
try:
logger.info("removing value from cache for : {0}".format(key))
cls.cache.delete(key)
except KeyError as ke:
logger.error("already removed from cache for key : {0}. Exception is : {1}".format(key, ke)) | []
| []
| [
"REDIS_URL"
]
| [] | ["REDIS_URL"] | python | 1 | 0 | |
rplugin/python3/deoplete/sources/deoplete_go/cgo.py | import os
import re
from clang_index import Clang_Index
class cgo(object):
def get_inline_source(buffer):
# TODO(zchee): very slow. about 100ms
if 'import "C"' not in buffer:
return (0, '')
pos_import_c = list(buffer).index('import "C"')
c_inline = buffer[:pos_import_c]
if c_inline[len(c_inline) - 1] == '*/':
comment_start = \
next(i for i, v in zip(range(len(c_inline) - 1, 0, -1),
reversed(c_inline)) if v == '/*')
c_inline = c_inline[comment_start + 1:len(c_inline) - 1]
return (len(c_inline), '\n'.join(c_inline))
def get_pkgconfig(packages):
out = []
pkgconfig = cgo.find_binary_path('pkg-config')
if pkgconfig != '':
for pkg in packages:
flag = \
os.popen(pkgconfig + " " + pkg + " --cflags --libs").read()
out += flag.rstrip().split(' ')
return out
def parse_candidates(result):
completion = {'dup': 1, 'word': ''}
_type = ""
word = ""
placeholder = ""
sep = ' '
for chunk in [x for x in result.string if x.spelling]:
chunk_spelling = chunk.spelling
# ignore inline fake main(void), and '_' prefix function
if chunk_spelling == 'main' or chunk_spelling.find('_') is 0:
return completion
if chunk.isKindTypedText():
word += chunk_spelling
placeholder += chunk_spelling
elif chunk.isKindResultType():
_type += chunk_spelling
else:
placeholder += chunk_spelling
completion['word'] = word
completion['abbr'] = completion['info'] = placeholder + sep + _type
completion['kind'] = \
' '.join([(Clang_Index.kinds[result.cursorKind]
if (result.cursorKind in Clang_Index.kinds) else
str(result.cursorKind))])
return completion
def complete(index, cache, cgo_options, line_count, source):
cgo_pattern = r'#cgo (\S+): (.+)'
flags = set()
for key, value in re.findall(cgo_pattern, source):
if key == 'pkg-config':
for flag in cgo.get_pkgconfig(value.split()):
flags.add(flag)
else:
if '${SRCDIR}' in key:
key = key.replace('${SRCDIR}', './')
flags.add('%s=%s' % (key, value))
cgo_flags = ['-std', cgo_options['std']] + list(flags)
fname = 'cgo_inline.c'
main = """
int main(void) {
}
"""
template = source + main
files = [(fname, template)]
# clang.TranslationUnit
# PARSE_NONE = 0
# PARSE_DETAILED_PROCESSING_RECORD = 1
# PARSE_INCOMPLETE = 2
# PARSE_PRECOMPILED_PREAMBLE = 4
# PARSE_CACHE_COMPLETION_RESULTS = 8
# PARSE_SKIP_FUNCTION_BODIES = 64
# PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128
options = 15
# Index.parse(path, args=None, unsaved_files=None, options = 0)
tu = index.parse(
fname, cgo_flags, unsaved_files=files, options=options
)
# TranslationUnit.codeComplete(path, line, column, ...)
cr = tu.codeComplete(
fname, (line_count + 2),
1,
unsaved_files=files,
include_macros=True,
include_code_patterns=True,
include_brief_comments=False
)
if cgo_options['sort_algo'] == 'priority':
results = sorted(cr.results, key=cgo.get_priority)
elif cgo_options['sort_algo'] == 'alphabetical':
results = sorted(cr.results, key=cgo.get_abbrevation)
else:
results = cr.results
# Go string to C string
# The C string is allocated in the C heap using malloc.
# It is the caller's responsibility to arrange for it to be
# freed, such as by calling C.free (be sure to include stdlib.h
# if C.free is needed).
# func C.CString(string) *C.char
#
# Go []byte slice to C array
# The C array is allocated in the C heap using malloc.
# It is the caller's responsibility to arrange for it to be
# freed, such as by calling C.free (be sure to include stdlib.h
# if C.free is needed).
# func C.CBytes([]byte) unsafe.Pointer
#
# C string to Go string
# func C.GoString(*C.char) string
#
# C data with explicit length to Go string
# func C.GoStringN(*C.char, C.int) string
#
# C data with explicit length to Go []byte
# func C.GoBytes(unsafe.Pointer, C.int) []byte
cache[source] = [
{
'word': 'CString',
'abbr': 'CString(string) *C.char',
'info': 'CString(string) *C.char',
'kind': 'function',
'dup': 1
},
{
'word': 'CBytes',
'abbr': 'CBytes([]byte) unsafe.Pointer',
'info': 'CBytes([]byte) unsafe.Pointer',
'kind': 'function',
'dup': 1
},
{
'word': 'GoString',
'abbr': 'GoString(*C.char) string',
'info': 'GoString(*C.char) string',
'kind': 'function',
'dup': 1
},
{
'word': 'GoStringN',
'abbr': 'GoStringN(*C.char, C.int) string',
'info': 'GoStringN(*C.char, C.int) string',
'kind': 'function',
'dup': 1
},
{
'word': 'GoBytes',
'abbr': 'GoBytes(unsafe.Pointer, C.int) []byte',
'info': 'GoBytes(unsafe.Pointer, C.int) []byte',
'kind': 'function',
'dup': 1
},
]
cache[source] += \
list(map(cgo.parse_candidates, results))
return cache[source]
def get_priority(x):
return x.string.priority
def get_abbr(strings):
for chunks in strings:
if chunks.isKindTypedText():
return chunks.spelling
return ""
def get_abbrevation(x):
return cgo.get_abbr(x.string).lower()
def find_binary_path(cmd):
def is_exec(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(cmd)
if fpath:
if is_exec(cmd):
return cmd
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
binary = os.path.join(path, cmd)
if is_exec(binary):
return binary
return ''
| []
| []
| [
"PATH"
]
| [] | ["PATH"] | python | 1 | 0 | |
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/util/factory_test.go | /*
Copyright 2014 The Kubernetes Authors All rights reserved.
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 util
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/user"
"path"
"reflect"
"sort"
"strings"
"testing"
"time"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/testapi"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/api/validation"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api"
"k8s.io/kubernetes/pkg/client/unversioned/fake"
"k8s.io/kubernetes/pkg/client/unversioned/testclient"
"k8s.io/kubernetes/pkg/controller"
"k8s.io/kubernetes/pkg/kubectl"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/util/flag"
"k8s.io/kubernetes/pkg/watch"
)
func TestNewFactoryDefaultFlagBindings(t *testing.T) {
factory := NewFactory(nil)
if !factory.flags.HasFlags() {
t.Errorf("Expected flags, but didn't get any")
}
}
func TestNewFactoryNoFlagBindings(t *testing.T) {
clientConfig := clientcmd.NewDefaultClientConfig(*clientcmdapi.NewConfig(), &clientcmd.ConfigOverrides{})
factory := NewFactory(clientConfig)
if factory.flags.HasFlags() {
t.Errorf("Expected zero flags, but got %v", factory.flags)
}
}
func TestPodSelectorForObject(t *testing.T) {
f := NewFactory(nil)
svc := &api.Service{
ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test"},
Spec: api.ServiceSpec{
Selector: map[string]string{
"foo": "bar",
},
},
}
expected := "foo=bar"
got, err := f.PodSelectorForObject(svc)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if expected != got {
t.Fatalf("Selector mismatch! Expected %s, got %s", expected, got)
}
}
func TestPortsForObject(t *testing.T) {
f := NewFactory(nil)
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"},
Spec: api.PodSpec{
Containers: []api.Container{
{
Ports: []api.ContainerPort{
{
ContainerPort: 101,
},
},
},
},
},
}
expected := []string{"101"}
got, err := f.PortsForObject(pod)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(expected) != len(got) {
t.Fatalf("Ports size mismatch! Expected %d, got %d", len(expected), len(got))
}
sort.Strings(expected)
sort.Strings(got)
for i, port := range got {
if port != expected[i] {
t.Fatalf("Port mismatch! Expected %s, got %s", expected[i], port)
}
}
}
func TestLabelsForObject(t *testing.T) {
f := NewFactory(nil)
tests := []struct {
name string
object runtime.Object
expected string
err error
}{
{
name: "successful re-use of labels",
object: &api.Service{
ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", Labels: map[string]string{"svc": "test"}},
TypeMeta: unversioned.TypeMeta{Kind: "Service", APIVersion: "v1"},
},
expected: "svc=test",
err: nil,
},
{
name: "empty labels",
object: &api.Service{
ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", Labels: map[string]string{}},
TypeMeta: unversioned.TypeMeta{Kind: "Service", APIVersion: "v1"},
},
expected: "",
err: nil,
},
{
name: "nil labels",
object: &api.Service{
ObjectMeta: api.ObjectMeta{Name: "zen", Namespace: "test", Labels: nil},
TypeMeta: unversioned.TypeMeta{Kind: "Service", APIVersion: "v1"},
},
expected: "",
err: nil,
},
}
for _, test := range tests {
gotLabels, err := f.LabelsForObject(test.object)
if err != test.err {
t.Fatalf("%s: Error mismatch: Expected %v, got %v", test.name, test.err, err)
}
got := kubectl.MakeLabels(gotLabels)
if test.expected != got {
t.Fatalf("%s: Labels mismatch! Expected %s, got %s", test.name, test.expected, got)
}
}
}
func TestCanBeExposed(t *testing.T) {
factory := NewFactory(nil)
tests := []struct {
kind unversioned.GroupKind
expectErr bool
}{
{
kind: api.Kind("ReplicationController"),
expectErr: false,
},
{
kind: api.Kind("Node"),
expectErr: true,
},
}
for _, test := range tests {
err := factory.CanBeExposed(test.kind)
if test.expectErr && err == nil {
t.Error("unexpected non-error")
}
if !test.expectErr && err != nil {
t.Errorf("unexpected error: %v", err)
}
}
}
func TestFlagUnderscoreRenaming(t *testing.T) {
factory := NewFactory(nil)
factory.flags.SetNormalizeFunc(flag.WordSepNormalizeFunc)
factory.flags.Bool("valid_flag", false, "bool value")
// In case of failure of this test check this PR: spf13/pflag#23
if factory.flags.Lookup("valid_flag").Name != "valid-flag" {
t.Fatalf("Expected flag name to be valid-flag, got %s", factory.flags.Lookup("valid_flag").Name)
}
}
func loadSchemaForTest() (validation.Schema, error) {
pathToSwaggerSpec := "../../../../api/swagger-spec/" + testapi.Default.GroupVersion().Version + ".json"
data, err := ioutil.ReadFile(pathToSwaggerSpec)
if err != nil {
return nil, err
}
return validation.NewSwaggerSchemaFromBytes(data)
}
func TestRefetchSchemaWhenValidationFails(t *testing.T) {
schema, err := loadSchemaForTest()
if err != nil {
t.Errorf("Error loading schema: %v", err)
t.FailNow()
}
output, err := json.Marshal(schema)
if err != nil {
t.Errorf("Error serializing schema: %v", err)
t.FailNow()
}
requests := map[string]int{}
c := &fake.RESTClient{
Codec: testapi.Default.Codec(),
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
switch p, m := req.URL.Path, req.Method; {
case strings.HasPrefix(p, "/swaggerapi") && m == "GET":
requests[p] = requests[p] + 1
return &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewBuffer(output))}, nil
default:
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
return nil, nil
}
}),
}
dir := os.TempDir() + "/schemaCache"
os.RemoveAll(dir)
fullDir, err := substituteUserHome(dir)
if err != nil {
t.Errorf("Error getting fullDir: %v", err)
t.FailNow()
}
cacheFile := path.Join(fullDir, "foo", "bar", schemaFileName)
err = writeSchemaFile(output, fullDir, cacheFile, "foo", "bar")
if err != nil {
t.Errorf("Error building old cache schema: %v", err)
t.FailNow()
}
obj := &extensions.Deployment{}
data, err := runtime.Encode(testapi.Extensions.Codec(), obj)
if err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
// Re-get request, should use HTTP and write
if getSchemaAndValidate(c, data, "foo", "bar", dir); err != nil {
t.Errorf("unexpected error validating: %v", err)
}
if requests["/swaggerapi/foo/bar"] != 1 {
t.Errorf("expected 1 schema request, saw: %d", requests["/swaggerapi/foo/bar"])
}
}
func TestValidateCachesSchema(t *testing.T) {
schema, err := loadSchemaForTest()
if err != nil {
t.Errorf("Error loading schema: %v", err)
t.FailNow()
}
output, err := json.Marshal(schema)
if err != nil {
t.Errorf("Error serializing schema: %v", err)
t.FailNow()
}
requests := map[string]int{}
c := &fake.RESTClient{
Codec: testapi.Default.Codec(),
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
switch p, m := req.URL.Path, req.Method; {
case strings.HasPrefix(p, "/swaggerapi") && m == "GET":
requests[p] = requests[p] + 1
return &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewBuffer(output))}, nil
default:
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
return nil, nil
}
}),
}
dir := os.TempDir() + "/schemaCache"
os.RemoveAll(dir)
obj := &api.Pod{}
data, err := runtime.Encode(testapi.Default.Codec(), obj)
if err != nil {
t.Errorf("unexpected error: %v", err)
t.FailNow()
}
// Initial request, should use HTTP and write
if getSchemaAndValidate(c, data, "foo", "bar", dir); err != nil {
t.Errorf("unexpected error validating: %v", err)
}
if _, err := os.Stat(path.Join(dir, "foo", "bar", schemaFileName)); err != nil {
t.Errorf("unexpected missing cache file: %v", err)
}
if requests["/swaggerapi/foo/bar"] != 1 {
t.Errorf("expected 1 schema request, saw: %d", requests["/swaggerapi/foo/bar"])
}
// Same version and group, should skip HTTP
if getSchemaAndValidate(c, data, "foo", "bar", dir); err != nil {
t.Errorf("unexpected error validating: %v", err)
}
if requests["/swaggerapi/foo/bar"] != 2 {
t.Errorf("expected 1 schema request, saw: %d", requests["/swaggerapi/foo/bar"])
}
// Different API group, should go to HTTP and write
if getSchemaAndValidate(c, data, "foo", "baz", dir); err != nil {
t.Errorf("unexpected error validating: %v", err)
}
if _, err := os.Stat(path.Join(dir, "foo", "baz", schemaFileName)); err != nil {
t.Errorf("unexpected missing cache file: %v", err)
}
if requests["/swaggerapi/foo/baz"] != 1 {
t.Errorf("expected 1 schema request, saw: %d", requests["/swaggerapi/foo/baz"])
}
// Different version, should go to HTTP and write
if getSchemaAndValidate(c, data, "foo2", "bar", dir); err != nil {
t.Errorf("unexpected error validating: %v", err)
}
if _, err := os.Stat(path.Join(dir, "foo2", "bar", schemaFileName)); err != nil {
t.Errorf("unexpected missing cache file: %v", err)
}
if requests["/swaggerapi/foo2/bar"] != 1 {
t.Errorf("expected 1 schema request, saw: %d", requests["/swaggerapi/foo2/bar"])
}
// No cache dir, should go straight to HTTP and not write
if getSchemaAndValidate(c, data, "foo", "blah", ""); err != nil {
t.Errorf("unexpected error validating: %v", err)
}
if requests["/swaggerapi/foo/blah"] != 1 {
t.Errorf("expected 1 schema request, saw: %d", requests["/swaggerapi/foo/blah"])
}
if _, err := os.Stat(path.Join(dir, "foo", "blah", schemaFileName)); err == nil || !os.IsNotExist(err) {
t.Errorf("unexpected cache file error: %v", err)
}
}
func TestSubstitueUser(t *testing.T) {
usr, err := user.Current()
if err != nil {
t.Logf("SKIPPING TEST: unexpected error: %v", err)
return
}
tests := []struct {
input string
expected string
expectErr bool
}{
{input: "~/foo", expected: path.Join(os.Getenv("HOME"), "foo")},
{input: "~" + usr.Username + "/bar", expected: usr.HomeDir + "/bar"},
{input: "/foo/bar", expected: "/foo/bar"},
{input: "~doesntexit/bar", expectErr: true},
}
for _, test := range tests {
output, err := substituteUserHome(test.input)
if test.expectErr {
if err == nil {
t.Error("unexpected non-error")
}
continue
}
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if output != test.expected {
t.Errorf("expected: %s, saw: %s", test.expected, output)
}
}
}
func newPodList(count, isUnready, isUnhealthy int, labels map[string]string) *api.PodList {
pods := []api.Pod{}
for i := 0; i < count; i++ {
newPod := api.Pod{
ObjectMeta: api.ObjectMeta{
Name: fmt.Sprintf("pod-%d", i+1),
Namespace: api.NamespaceDefault,
CreationTimestamp: unversioned.Date(2016, time.April, 1, 1, 0, i, 0, time.UTC),
Labels: labels,
},
Status: api.PodStatus{
Conditions: []api.PodCondition{
{
Status: api.ConditionTrue,
Type: api.PodReady,
},
},
},
}
pods = append(pods, newPod)
}
if isUnready > -1 && isUnready < count {
pods[isUnready].Status.Conditions[0].Status = api.ConditionFalse
}
if isUnhealthy > -1 && isUnhealthy < count {
pods[isUnhealthy].Status.ContainerStatuses = []api.ContainerStatus{{RestartCount: 5}}
}
return &api.PodList{
Items: pods,
}
}
func TestGetFirstPod(t *testing.T) {
labelSet := map[string]string{"test": "selector"}
tests := []struct {
name string
podList *api.PodList
watching []watch.Event
sortBy func([]*api.Pod) sort.Interface
expected *api.Pod
expectedNum int
expectedErr bool
}{
{
name: "kubectl logs - two ready pods",
podList: newPodList(2, -1, -1, labelSet),
sortBy: func(pods []*api.Pod) sort.Interface { return controller.ActivePods(pods) },
expected: &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "pod-2",
Namespace: api.NamespaceDefault,
CreationTimestamp: unversioned.Date(2016, time.April, 1, 1, 0, 1, 0, time.UTC),
Labels: map[string]string{"test": "selector"},
},
Status: api.PodStatus{
Conditions: []api.PodCondition{
{
Status: api.ConditionTrue,
Type: api.PodReady,
},
},
},
},
expectedNum: 2,
},
{
name: "kubectl logs - one unhealthy, one healthy",
podList: newPodList(2, -1, 1, labelSet),
sortBy: func(pods []*api.Pod) sort.Interface { return controller.ActivePods(pods) },
expected: &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "pod-2",
Namespace: api.NamespaceDefault,
CreationTimestamp: unversioned.Date(2016, time.April, 1, 1, 0, 1, 0, time.UTC),
Labels: map[string]string{"test": "selector"},
},
Status: api.PodStatus{
Conditions: []api.PodCondition{
{
Status: api.ConditionTrue,
Type: api.PodReady,
},
},
ContainerStatuses: []api.ContainerStatus{{RestartCount: 5}},
},
},
expectedNum: 2,
},
{
name: "kubectl attach - two ready pods",
podList: newPodList(2, -1, -1, labelSet),
sortBy: func(pods []*api.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) },
expected: &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "pod-1",
Namespace: api.NamespaceDefault,
CreationTimestamp: unversioned.Date(2016, time.April, 1, 1, 0, 0, 0, time.UTC),
Labels: map[string]string{"test": "selector"},
},
Status: api.PodStatus{
Conditions: []api.PodCondition{
{
Status: api.ConditionTrue,
Type: api.PodReady,
},
},
},
},
expectedNum: 2,
},
{
name: "kubectl attach - wait for ready pod",
podList: newPodList(1, 1, -1, labelSet),
watching: []watch.Event{
{
Type: watch.Modified,
Object: &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "pod-1",
Namespace: api.NamespaceDefault,
CreationTimestamp: unversioned.Date(2016, time.April, 1, 1, 0, 0, 0, time.UTC),
Labels: map[string]string{"test": "selector"},
},
Status: api.PodStatus{
Conditions: []api.PodCondition{
{
Status: api.ConditionTrue,
Type: api.PodReady,
},
},
},
},
},
},
sortBy: func(pods []*api.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) },
expected: &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "pod-1",
Namespace: api.NamespaceDefault,
CreationTimestamp: unversioned.Date(2016, time.April, 1, 1, 0, 0, 0, time.UTC),
Labels: map[string]string{"test": "selector"},
},
Status: api.PodStatus{
Conditions: []api.PodCondition{
{
Status: api.ConditionTrue,
Type: api.PodReady,
},
},
},
},
expectedNum: 1,
},
}
for i := range tests {
test := tests[i]
client := &testclient.Fake{}
client.PrependReactor("list", "pods", func(action testclient.Action) (handled bool, ret runtime.Object, err error) {
return true, test.podList, nil
})
if len(test.watching) > 0 {
watcher := watch.NewFake()
for _, event := range test.watching {
switch event.Type {
case watch.Added:
go watcher.Add(event.Object)
case watch.Modified:
go watcher.Modify(event.Object)
}
}
client.PrependWatchReactor("pods", testclient.DefaultWatchReactor(watcher, nil))
}
selector := labels.Set(labelSet).AsSelector()
pod, numPods, err := GetFirstPod(client, api.NamespaceDefault, selector, 1*time.Minute, test.sortBy)
if !test.expectedErr && err != nil {
t.Errorf("%s: unexpected error: %v", test.name, err)
continue
}
if test.expectedErr && err == nil {
t.Errorf("%s: expected an error", test.name)
continue
}
if test.expectedNum != numPods {
t.Errorf("%s: expected %d pods, got %d", test.name, test.expectedNum, numPods)
continue
}
if !reflect.DeepEqual(test.expected, pod) {
t.Errorf("%s:\nexpected pod:\n%#v\ngot:\n%#v\n\n", test.name, test.expected, pod)
}
}
}
| [
"\"HOME\""
]
| []
| [
"HOME"
]
| [] | ["HOME"] | go | 1 | 0 | |
blockchain/algorand.go | package blockchain
import (
"fmt"
"github.com/algorand/go-algorand-sdk/client/algod"
"github.com/algorand/go-algorand-sdk/client/kmd"
transaction "github.com/algorand/go-algorand-sdk/future"
"github.com/google/uuid"
"github.com/uncopied/uncopier/database/dbmodel"
"os"
)
func AlgorandCreateNFT(asset *dbmodel.Asset, assetViewURL string) (string, error) {
createAlgorandAsset := os.Getenv("ALGORAND_CREATE_ASSET")
if createAlgorandAsset == "true" {
return AlgorandCreateNFT_(asset, assetViewURL)
} else {
return uuid.New().String(),nil
}
}
const UNCOPIED = "UNCOPIED"
func AlgorandCreateNFT_(asset *dbmodel.Asset, assetViewURL string) (string, error) {
kmdAddress := os.Getenv("ALGORAND_KMDADDRESS") // "http://localhost:7833"
kmdToken := os.Getenv("ALGORAND_KMDTOKEN") //"206ba3f9ad1d83523fb2a303dd055cd99ce10c5be01e35ee88285fe51438f02a"
algodAddress := os.Getenv("ALGORAND_ALGODADDRESS") //"http://localhost:8080"
algodToken := os.Getenv("ALGORAND_ALGODTOKEN") // "da61ace80780af7b1c78456c7d1d2a511758a754d2c219e1a6b37c32763f5bfe"
walletName := os.Getenv("ALGORAND_WALLETNAME") //"mylinuxwallet"
walletPassword := os.Getenv("ALGORAND_WALLETPASSWORD") // "password123"
accountAddr := os.Getenv("ALGORAND_ACCOUNTADDR") //"C2MCKQYJCU4RNWCQVWWSWEHGPAD37BEMQTIMVD6XF36AUIPKOXWIZOO7ZE"
// Create a kmd client
kmdClient, err := kmd.MakeClient(kmdAddress, kmdToken)
if err != nil {
fmt.Printf("failed to make kmd client: %s\n", err)
return "",err
}
fmt.Println("Made a kmd client")
// Create an algod client
algodClient, err := algod.MakeClient(algodAddress, algodToken)
if err != nil {
fmt.Printf("failed to make algod client: %s\n", err)
return "",err
}
fmt.Println("Made an algod client")
// Get the list of wallets
listResponse, err := kmdClient.ListWallets()
if err != nil {
fmt.Printf("error listing wallets: %s\n", err)
return "",err
}
// Find our wallet name in the list
var exampleWalletID string
fmt.Printf("Got %d wallet(s):\n", len(listResponse.Wallets))
for _, wallet := range listResponse.Wallets {
fmt.Printf("ID: %s\tName: %s\n", wallet.ID, wallet.Name)
if wallet.Name == walletName {
fmt.Printf("found wallet '%s' with ID: %s\n", wallet.Name, wallet.ID)
exampleWalletID = wallet.ID
break
}
}
// Get a wallet handle. The wallet handle is used for things like signing transactions
// and creating accounts. Wallet handles do expire, but they can be renewed
initResponse, err := kmdClient.InitWalletHandle(exampleWalletID, walletPassword)
if err != nil {
fmt.Printf("Error initializing wallet handle: %s\n", err)
return "",err
}
// Extract the wallet handle
exampleWalletHandleToken := initResponse.WalletHandleToken
defaultFrozen := false // whether user accounts will need to be unfrozen before transacting
totalIssuance := uint64(1) // total number of this asset in circulation
decimals := uint32(0) // hint to GUIs for interpreting base unit
reserve := accountAddr // specified address is considered the asset reserve (it has no special privileges, this is only informational)
freeze := accountAddr // specified address can freeze or unfreeze user asset holdings
clawback := accountAddr // specified address can revoke user asset holdings and send them to other addresses
manager := accountAddr // specified address can change reserve, freeze, clawback, and manager
unitName := UNCOPIED // used to display asset units to user
assetName := asset.AssetLabel // "friendly name" of asset
noteStr := asset.Note
if noteStr == "" {
noteStr = asset.CertificateLabel
}
note := []byte(noteStr) // arbitrary data to be stored in the transaction; here, none is stored
//assetURL := "https://uncopied.org/c/v/"+strconv.Itoa(int(asset.ID)) // optional string pointing to a URL relating to the asset. 32 character length.
assetMetadataHash := asset.MD5HashMetadata // optional hash commitment of some sort relating to the asset. 32 character length.
// Get the suggested transaction parameters
txParams, err := algodClient.BuildSuggestedParams()
if err != nil {
fmt.Printf("error getting suggested tx params: %s\n", err)
return "",err
}
// signing and sending "txn" allows "accountAddr" to create an asset
txn, err := transaction.MakeAssetCreateTxn(accountAddr, note, txParams,
totalIssuance, decimals, defaultFrozen, manager, reserve, freeze, clawback,
unitName, assetName, assetViewURL, assetMetadataHash)
if err != nil {
fmt.Printf("Failed to make asset: %s\n", err)
return "",err
}
fmt.Printf("Asset created AssetName: %s\n", txn.AssetConfigTxnFields.AssetParams.AssetName)
// Sign the transaction
signResponse, err := kmdClient.SignTransaction(exampleWalletHandleToken, walletPassword, txn)
if err != nil {
fmt.Printf("Failed to sign transaction with kmd: %s\n", err)
return "",err
}
fmt.Printf("kmd made signed transaction with bytes: %x\n", signResponse.SignedTransaction)
// Broadcast the transaction to the network
// Note that this transaction will get rejected because the accounts do not have any tokens
sendResponse, err := algodClient.SendRawTransaction(signResponse.SignedTransaction)
if err != nil {
fmt.Printf("failed to send transaction: %s\n", err)
return "",err
}
fmt.Printf("Transaction ID: %s\n", sendResponse.TxID)
return sendResponse.TxID, nil
//found wallet 'mylinuxwallet' with ID: 0377a9874ab7818c861ba465647e7e7b
//Asset created AssetName: Portrait of a Lady (1/15)
//kmd made signed transaction with bytes: 82a3736967c440f2745f123d5744c13b6210ab1a74b2f395fc022a9bd738d7cc5f0c34661740c162c4555753bad6a422078bb8b16bb566e4e0da9593a696398927931fdae28d08a374786e89a46170617289a2616dc4203062633737373332396132393139666436666661393662616365396134373739a2616eb9506f727472616974206f662061204c6164792028312f313529a26175be68747470733a2f2f756e636f706965642e6f72672f78456b4d5a2e706e67a163c4201698254309153916d850adad2b10e67807bf848c84d0ca8fd72efc0a21ea75eca166c4201698254309153916d850adad2b10e67807bf848c84d0ca8fd72efc0a21ea75eca16dc4201698254309153916d850adad2b10e67807bf848c84d0ca8fd72efc0a21ea75eca172c4201698254309153916d850adad2b10e67807bf848c84d0ca8fd72efc0a21ea75eca17401a2756ea66c6164792d31a3666565cd03e8a26676ce009db404a367656eac6d61696e6e65742d76312e30a26768c420c061c4d8fc1dbdded2d7604be4568e3f6d041987ac37bde4b620b5ab39248adfa26c76ce009db7eca46e6f7465c4117465737420617373657420637265617465a3736e64c4201698254309153916d850adad2b10e67807bf848c84d0ca8fd72efc0a21ea75eca474797065a461636667
//failed to send transaction: HTTP 400 Bad Request: TransactionPool.Remember: transaction AJLT4KTFCSFILGVORFMQQPDTVV5PAKQIHCTQZ6SONUY33RBO76YA: account C2MCKQYJCU4RNWCQVWWSWEHGPAD37BEMQTIMVD6XF36AUIPKOXWIZOO7ZE balance 197000 below min 200000 (1 assets)
//Made a kmd client
//Made an algod client
//Got 2 wallet(s):
//ID: 0377a9874ab7818c861ba465647e7e7b Name: mylinuxwallet
//found wallet 'mylinuxwallet' with ID: 0377a9874ab7818c861ba465647e7e7b
//Asset created AssetName: Portrait of a Lady (1/15)
//kmd made signed transaction with bytes: 82a3736967c4406808b780e411798800420fe58d3f50f30946ba5f25fcbef955d2fb17de47b2f2ee8ec4f75b3d1b9df3497e7ab8ee27e6b465f9f2a0bc6300baa50aea8f592a0aa374786e89a46170617289a2616dc4203062633737373332396132393139666436666661393662616365396134373739a2616eb9506f727472616974206f662061204c6164792028312f313529a26175be68747470733a2f2f756e636f706965642e6f72672f78456b4d5a2e706e67a163c4201698254309153916d850adad2b10e67807bf848c84d0ca8fd72efc0a21ea75eca166c4201698254309153916d850adad2b10e67807bf848c84d0ca8fd72efc0a21ea75eca16dc4201698254309153916d850adad2b10e67807bf848c84d0ca8fd72efc0a21ea75eca172c4201698254309153916d850adad2b10e67807bf848c84d0ca8fd72efc0a21ea75eca17401a2756ea66c6164792d31a3666565cd03e8a26676ce009db441a367656eac6d61696e6e65742d76312e30a26768c420c061c4d8fc1dbdded2d7604be4568e3f6d041987ac37bde4b620b5ab39248adfa26c76ce009db829a46e6f7465c4117465737420617373657420637265617465a3736e64c4201698254309153916d850adad2b10e67807bf848c84d0ca8fd72efc0a21ea75eca474797065a461636667
//Transaction ID: TGQ4B7ISZYUKOTU4K2OVYVZLH256UJLCMUWNBVSX6AYEFLXUHGGA
}
| [
"\"ALGORAND_CREATE_ASSET\"",
"\"ALGORAND_KMDADDRESS\"",
"\"ALGORAND_KMDTOKEN\"",
"\"ALGORAND_ALGODADDRESS\"",
"\"ALGORAND_ALGODTOKEN\"",
"\"ALGORAND_WALLETNAME\"",
"\"ALGORAND_WALLETPASSWORD\"",
"\"ALGORAND_ACCOUNTADDR\""
]
| []
| [
"ALGORAND_KMDADDRESS",
"ALGORAND_ALGODADDRESS",
"ALGORAND_WALLETPASSWORD",
"ALGORAND_ALGODTOKEN",
"ALGORAND_WALLETNAME",
"ALGORAND_KMDTOKEN",
"ALGORAND_ACCOUNTADDR",
"ALGORAND_CREATE_ASSET"
]
| [] | ["ALGORAND_KMDADDRESS", "ALGORAND_ALGODADDRESS", "ALGORAND_WALLETPASSWORD", "ALGORAND_ALGODTOKEN", "ALGORAND_WALLETNAME", "ALGORAND_KMDTOKEN", "ALGORAND_ACCOUNTADDR", "ALGORAND_CREATE_ASSET"] | go | 8 | 0 | |
internal/ingress/controller/util.go | /*
Copyright 2015 The Kubernetes 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 (
"fmt"
"os"
"os/exec"
"path"
"strconv"
"strings"
"syscall"
api "k8s.io/api/core/v1"
networking "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/ingress-nginx/internal/ingress"
"k8s.io/klog/v2"
)
// newUpstream creates an upstream without servers.
func newUpstream(name string) *ingress.Backend {
return &ingress.Backend{
Name: name,
Endpoints: []ingress.Endpoint{},
Service: &api.Service{},
SessionAffinity: ingress.SessionAffinityConfig{
CookieSessionAffinity: ingress.CookieSessionAffinity{
Locations: make(map[string][]string),
},
},
}
}
// upstreamName returns a formatted upstream name based on namespace, service, and port
func upstreamName(namespace string, service *networking.IngressServiceBackend) string {
if service != nil {
if service.Port.Number > 0 {
return fmt.Sprintf("%s-%s-%d", namespace, service.Name, service.Port.Number)
}
if service.Port.Name != "" {
return fmt.Sprintf("%s-%s-%s", namespace, service.Name, service.Port.Name)
}
}
return fmt.Sprintf("%s-INVALID", namespace)
}
// upstreamServiceNameAndPort verifies if service is not nil, and then return the
// correct serviceName and Port
func upstreamServiceNameAndPort(service *networking.IngressServiceBackend) (string, intstr.IntOrString) {
if service != nil {
if service.Port.Number > 0 {
return service.Name, intstr.FromInt(int(service.Port.Number))
}
if service.Port.Name != "" {
return service.Name, intstr.FromString(service.Port.Name)
}
}
return "", intstr.IntOrString{}
}
// sysctlSomaxconn returns the maximum number of connections that can be queued
// for acceptance (value of net.core.somaxconn)
// http://nginx.org/en/docs/http/ngx_http_core_module.html#listen
func sysctlSomaxconn() int {
maxConns, err := getSysctl("net/core/somaxconn")
if err != nil || maxConns < 512 {
klog.V(3).InfoS("Using default net.core.somaxconn", "value", maxConns)
return 511
}
return maxConns
}
// rlimitMaxNumFiles returns hard limit for RLIMIT_NOFILE
func rlimitMaxNumFiles() int {
var rLimit syscall.Rlimit
err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
if err != nil {
klog.ErrorS(err, "Error reading system maximum number of open file descriptors (RLIMIT_NOFILE)")
return 0
}
return int(rLimit.Max)
}
const (
defBinary = "/usr/local/nginx/sbin/nginx"
cfgPath = "/etc/nginx/nginx.conf"
)
// NginxExecTester defines the interface to execute
// command like reload or test configuration
type NginxExecTester interface {
ExecCommand(args ...string) *exec.Cmd
Test(cfg string) ([]byte, error)
}
// NginxCommand stores context around a given nginx executable path
type NginxCommand struct {
Binary string
}
// NewNginxCommand returns a new NginxCommand from which path
// has been detected from environment variable NGINX_BINARY or default
func NewNginxCommand() NginxCommand {
command := NginxCommand{
Binary: defBinary,
}
binary := os.Getenv("NGINX_BINARY")
if binary != "" {
command.Binary = binary
}
return command
}
// ExecCommand instanciates an exec.Cmd object to call nginx program
func (nc NginxCommand) ExecCommand(args ...string) *exec.Cmd {
cmdArgs := []string{}
cmdArgs = append(cmdArgs, "-c", cfgPath)
cmdArgs = append(cmdArgs, args...)
return exec.Command(nc.Binary, cmdArgs...)
}
// Test checks if config file is a syntax valid nginx configuration
func (nc NginxCommand) Test(cfg string) ([]byte, error) {
return exec.Command(nc.Binary, "-c", cfg, "-t").CombinedOutput()
}
// getSysctl returns the value for the specified sysctl setting
func getSysctl(sysctl string) (int, error) {
data, err := os.ReadFile(path.Join("/proc/sys", sysctl))
if err != nil {
return -1, err
}
val, err := strconv.Atoi(strings.Trim(string(data), " \n"))
if err != nil {
return -1, err
}
return val, nil
}
| [
"\"NGINX_BINARY\""
]
| []
| [
"NGINX_BINARY"
]
| [] | ["NGINX_BINARY"] | go | 1 | 0 | |
src/effective_go/init_test.go | package effective_go
import (
"flag"
"fmt"
"log"
"os"
"testing"
)
type ByteSize float64
const (
_ = iota
KB ByteSize = 1 << (10 * iota)
MB
GB
TB
PB
EB
ZB
YB
)
func (b ByteSize) String() string {
switch {
case b >= YB:
return fmt.Sprintf("%.2fYB", b/YB)
case b >= ZB:
return fmt.Sprintf("%.2fZB", b/ZB)
case b >= EB:
return fmt.Sprintf("%.2fEB", b/EB)
case b >= PB:
return fmt.Sprintf("%.2fPB", b/PB)
case b >= TB:
return fmt.Sprintf("%.2fTB", b/TB)
case b >= GB:
return fmt.Sprintf("%.2fGB", b/GB)
case b >= MB:
return fmt.Sprintf("%.2fMB", b/ZB)
case b >= KB:
return fmt.Sprintf("%.2fKB", b/KB)
}
return fmt.Sprintf("%.2fB", b)
}
func TestConstant(t *testing.T) {
var b ByteSize = 1e13
fmt.Println(b.String())
}
var (
home = os.Getenv("HOME")
user = os.Getenv("USER")
gopath = os.Getenv("GOPATH")
)
func init() {
if user == "" {
log.Fatal("$USER not set")
}
if home == "" {
home = "/home/" + user
}
if gopath == "" {
gopath = home + "/g"
}
flag.StringVar(&gopath, "gopath", gopath, "override default GoPATH")
}
| [
"\"HOME\"",
"\"USER\"",
"\"GOPATH\""
]
| []
| [
"GOPATH",
"USER",
"HOME"
]
| [] | ["GOPATH", "USER", "HOME"] | go | 3 | 0 | |
pyEX/client.py | import os
from functools import partial
from .common import PyEXception, _getJson, _USAGE_TYPES
from .refdata import symbols, iexSymbols, symbolsDF, iexSymbolsDF, \
symbolsList, iexSymbolsList, corporateActions, corporateActionsDF, dividends as refDividends, dividendsDF as refDividendsDF, nextDayExtDate, nextDayExtDateDF, directory, directoryDF
from .markets import markets, marketsDF
from .stats import stats, statsDF, recent, recentDF, records, recordsDF, summary, summaryDF, daily, dailyDF
from .stocks import balanceSheet, balanceSheetDF, batch, batchDF, bulkBatch, bulkBatchDF, book, bookDF, cashFlow, cashFlowDF, chart, chartDF, \
bulkMinuteBars, bulkMinuteBarsDF, company, companyDF, collections, collectionsDF, crypto, cryptoDF, delayedQuote, delayedQuoteDF, dividends, dividendsDF, \
earnings, earningsDF, earningsToday, earningsTodayDF, estimates, estimatesDF, spread, spreadDF, financials, financialsDF, incomeStatement, incomeStatementDF, ipoToday, ipoTodayDF, \
ipoUpcoming, ipoUpcomingDF, threshold, thresholdDF, shortInterest, shortInterestDF, marketShortInterest, marketShortInterestDF, keyStats, keyStatsDF, \
largestTrades, largestTradesDF, list, listDF, logo, logoPNG, logoNotebook, news, newsDF, marketNews, marketNewsDF, ohlc, ohlcDF, marketOhlc, marketOhlcDF, \
peers, peersDF, yesterday, yesterdayDF, marketYesterday, marketYesterdayDF, price, priceDF, quote, quoteDF, relevant, relevantDF, sectorPerformance, \
sectorPerformanceDF, splits, splitsDF, volumeByVenue, volumeByVenueDF
from .marketdata.sse import topsSSE, lastSSE, deepSSE, tradesSSE
_INCLUDE_FUNCTIONS = [
# Refdata
('symbols', symbols),
('iexSymbols', iexSymbols),
('symbolsDF', symbolsDF),
('iexSymbolsDF', iexSymbolsDF),
('symbolsList', symbolsList),
('iexSymbolsList', iexSymbolsList),
('corporateActions', corporateActions),
('corporateActionsDF', corporateActionsDF),
('refDividends', refDividends),
('refDividendsDF', refDividendsDF),
('nextDayExtDate', nextDayExtDate),
('nextDayExtDateDF', nextDayExtDateDF),
('directory', directory),
('directoryDF', directoryDF),
# Markets
('markets', markets),
('marketsDF', marketsDF),
# Stats
('stats', stats),
('statsDF', statsDF),
('recent', recent),
('recentDF', recentDF),
('records', records),
('recordsDF', recordsDF),
('summary', summary),
('summaryDF', summaryDF),
('daily', daily),
('dailyDF', dailyDF),
# Stocks
('balanceSheet', balanceSheet),
('balanceSheetDF', balanceSheetDF),
('batch', batch),
('batchDF', batchDF),
('bulkBatch', bulkBatch),
('bulkBatchDF', bulkBatchDF),
('book', book),
('bookDF', bookDF),
('cashFlow', cashFlow),
('cashFlowDF', cashFlowDF),
('chart', chart),
('chartDF', chartDF),
('bulkMinuteBars', bulkMinuteBars),
('bulkMinuteBarsDF', bulkMinuteBarsDF),
('company', company),
('companyDF', companyDF),
('collections', collections),
('collectionsDF', collectionsDF),
('crypto', crypto),
('cryptoDF', cryptoDF),
('delayedQuote', delayedQuote),
('delayedQuoteDF', delayedQuoteDF),
('dividends', dividends),
('dividendsDF', dividendsDF),
('earnings', earnings),
('earningsDF', earningsDF),
('earningsToday', earningsToday),
('earningsTodayDF', earningsTodayDF),
('spread', spread),
('spreadDF', spreadDF),
('financials', financials),
('financialsDF', financialsDF),
('incomeStatement', incomeStatement),
('incomeStatementDF', incomeStatementDF),
('ipoToday', ipoToday),
('ipoTodayDF', ipoTodayDF),
('ipoUpcoming', ipoUpcoming),
('ipoUpcomingDF', ipoUpcomingDF),
('threshold', threshold),
('thresholdDF', thresholdDF),
('shortInterest', shortInterest),
('shortInterestDF', shortInterestDF),
('marketShortInterest', marketShortInterest),
('marketShortInterestDF', marketShortInterestDF),
('estimates', estimates),
('estimatesDF', estimatesDF),
('keyStats', keyStats),
('keyStatsDF', keyStatsDF),
('largestTrades', largestTrades),
('largestTradesDF', largestTradesDF),
('list', list),
('listDF', listDF),
('logo', logo),
('logoPNG', logoPNG),
('logoNotebook', logoNotebook),
('news', news),
('newsDF', newsDF),
('marketNews', marketNews),
('marketNewsDF', marketNewsDF),
('ohlc', ohlc),
('ohlcDF', ohlcDF),
('marketOhlc', marketOhlc),
('marketOhlcDF', marketOhlcDF),
('peers', peers),
('peersDF', peersDF),
('yesterday', yesterday),
('yesterdayDF', yesterdayDF),
('marketYesterday', marketYesterday),
('marketYesterdayDF', marketYesterdayDF),
('price', price),
('priceDF', priceDF),
('quote', quote),
('quoteDF', quoteDF),
('relevant', relevant),
('relevantDF', relevantDF),
('sectorPerformance', sectorPerformance),
('sectorPerformanceDF', sectorPerformanceDF),
('splits', splits),
('splitsDF', splitsDF),
('volumeByVenue', volumeByVenue),
('volumeByVenueDF', volumeByVenueDF),
# SSE Streaming
('topsSSE', topsSSE),
('lastSSE', lastSSE),
('deepSSE', deepSSE),
('tradesSSE', tradesSSE),
]
class Client(object):
'''IEX Cloud Client
Client has access to all methods provided as standalone, but in an authenticated way
Args:
api_token (string): api token (can pickup from IEX_TOKEN environment variable)
verson (string): api version to use (defaults to beta)
'''
def __init__(self, api_token=None, version='beta'):
self._token = api_token or os.environ.get('IEX_TOKEN', '')
if not self._token:
raise PyEXception('API Token missing or not in environment (IEX_TOKEN)')
self._version = version
for name, method in _INCLUDE_FUNCTIONS:
setattr(self, name, partial(self.bind, meth=method))
def bind(self, *args, meth=None, **kwargs):
return meth(token=self._token, version=self._version, *args, **kwargs)
def account(self):
return _getJson('account/metadata', self._token, self._version)
def usage(self, type=None):
if type:
if type not in _USAGE_TYPES:
raise PyEXception('type not recognized: {}'.format(type))
return _getJson('account/usage/{type}'.format(type=type), self._token, self._version)
return _getJson('account/usage/messages', self._token, self._version)
| []
| []
| [
"IEX_TOKEN"
]
| [] | ["IEX_TOKEN"] | python | 1 | 0 | |
setup_test.go | package processor
import (
"context"
"fmt"
"net"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/DoNewsCode/core"
"github.com/DoNewsCode/core/otkafka"
"github.com/segmentio/kafka-go"
)
var envDefaultKafkaAddrs []string
var testTopic = "processor-test"
func TestMain(m *testing.M) {
v := os.Getenv("KAFKA_ADDR")
if v != "" {
envDefaultKafkaAddrs = strings.Split(v, ",")
setupTopic()
setupMessage()
time.Sleep(1 * time.Second)
}
os.Exit(m.Run())
}
func setupTopic() {
conn, err := kafka.Dial("tcp", envDefaultKafkaAddrs[0])
if err != nil {
panic(err.Error())
}
defer conn.Close()
controller, err := conn.Controller()
if err != nil {
panic(err.Error())
}
var controllerConn *kafka.Conn
controllerConn, err = kafka.Dial("tcp", net.JoinHostPort(controller.Host, strconv.Itoa(controller.Port)))
if err != nil {
panic(err.Error())
}
defer controllerConn.Close()
topics := []string{testTopic}
topicConfigs := make([]kafka.TopicConfig, len(topics))
for i, topic := range topics {
topicConfigs[i] = kafka.TopicConfig{
Topic: topic,
NumPartitions: 1,
ReplicationFactor: 1,
}
}
err = controllerConn.DeleteTopics(topics...)
if err == nil {
time.Sleep(2 * time.Second)
}
err = controllerConn.CreateTopics(topicConfigs...)
if err != nil {
panic(err.Error())
}
}
func setupMessage() {
c := core.New(
core.WithInline("kafka.writer.default.brokers", envDefaultKafkaAddrs),
core.WithInline("kafka.writer.default.topic", testTopic),
core.WithInline("log.level", "none"),
)
c.ProvideEssentials()
c.Provide(otkafka.Providers())
c.Invoke(func(w *kafka.Writer) {
testMessages := make([]kafka.Message, 4)
for i := 0; i < 4; i++ {
testMessages[i] = kafka.Message{Value: []byte(fmt.Sprintf(`{"id":%d}`, i))}
}
err := w.WriteMessages(context.Background(), testMessages...)
if err != nil {
panic(err)
}
})
}
| [
"\"KAFKA_ADDR\""
]
| []
| [
"KAFKA_ADDR"
]
| [] | ["KAFKA_ADDR"] | go | 1 | 0 | |
ms_test.go | // (C) Philip Schlump, 2014-2015.
package templatestrings
import (
"fmt"
"os"
"testing"
"github.com/pschlump/json" // "encoding/json"
)
//type TestCase struct {
// format string
// expected string
// value float64
//}
//
//var testCases = []TestCase{
// { "##,##0.00", " -123.46", -123.456 }, // round to .47???
// { "##,##0.00", " 123.46", 123.456 }, // 1
// { "##,##0.00", "##,##0.00", 123123.456 }, // 2
//
// // Escape
// // &TestCase{"YYYY/MM/DD hh:mm:ss", "2014/01/10 11:31:32"},
// // &TestCase{"YYYY-MM-DD hh:mm:ss", "2014-01-10 11:31:32"},
// // In a string
// // &TestCase{"/aaaa/YYYY/mm/bbbb", "/aaaa/2014/31/bbbb"},
//
// // No Format - get rid of value
// { "", "", 123.456 }, // 3
// { ".", ".", 123.456 }, // 4
// { "0", "3", 3.456 }, // 5
// { "#", "3", 3.456 }, // 6
//
// { "##,##0.00", " 0.00", 0.0 }, // 7
// { "##,##0.00", " 0.00", -0.0 }, // 1
//}
func TestPictureFormats(t *testing.T) {
//if false {
// fmt.Printf ( "keep compiler happy when we are not using fmt.\n" )
//}
rv := CenterStr(10, "Adm")
ex := " Adm "
if rv != " Adm " {
t.Fatalf("Error CenterStr(10,\"Adm\") results=[%s] expected=[%s]", rv, ex)
}
//for i, v := range testCases {
// // fmt.Printf ( "Running %d\n", i )
// result := Format(v.format, v.value)
// if result != v.expected {
// t.Fatalf("Error for %f at [%d] in table: format=[%s]: results=[%s] expected=[%s]", v.value, i, v.format, result, v.expected)
// }
//}
}
func TestHomeDir(t *testing.T) {
s := HomeDir()
h := os.Getenv("HOME")
if string(os.PathSeparator) == `\` {
fmt.Printf("Windows: s= ->%s<- h= ->%s<-\n", s, h)
if !(s[2:3] == string(os.PathSeparator)) {
t.Fatalf("Error did not get back a home directory. Got %s", s)
}
} else {
if !(s[0:1] == string(os.PathSeparator)) {
t.Fatalf("Error did not get back a home directory. Got %s", s)
}
}
// fmt.Printf ( "h=%s\n", h )
if h != "" {
if !(s == h) {
t.Fatalf("(Unix/Linux/Mac/Specific): Error did not get back a home directory. Got %s, expecting %s", s, h)
}
} else {
fmt.Printf("Warning: HOME environment variable not set\n")
}
}
// func SplitOnWords ( s string ) ( record []string ) {
func TestSplitOnWords(t *testing.T) {
rv := SplitOnWords("a b c")
if len(rv) != 3 {
t.Fatalf("Wrong number of items returned")
}
if rv[0] != "a" {
t.Fatalf("Wrong [0] items returned")
}
rv = SplitOnWords(`a "b c d" e`)
if len(rv) != 3 {
t.Fatalf("Wrong number of items returned")
}
if rv[1] != "b c d" {
t.Fatalf("Wrong [0] items returned")
}
}
func TestNvl(t *testing.T) {
s := Nvl("x", "")
if s != "x" {
t.Fatalf("Nvl failed to see empty string")
}
s = Nvl("x", "y")
if s != "y" {
t.Fatalf("Nvl failed to see non empty string")
}
}
// func PicFloat ( format string, flt float64 ) ( r string ) {
func TestPicFloat(t *testing.T) {
s := PicFloat("##,##0.00", 123.321)
if s != " 123.32" {
t.Fatalf("PicFloat failed to format string, expected \" 123.32\", got ->%s<-", s)
}
}
//func PadOnRight ( n int, s string ) ( r string ) {
func TestPadOnRight(t *testing.T) {
s := PadOnRight(5, "abc")
ex := "abc "
if s != ex {
t.Fatalf("PadOnRight failed to get expected ->%s<-, got ->%s<-", ex, s)
}
s = PadOnRight(5, 12)
ex = "12 "
if s != ex {
t.Fatalf("PadOnRight failed to get expected ->%s<-, got ->%s<-", ex, s)
}
}
func TestPadOnLeft(t *testing.T) {
s := PadOnLeft(5, "abc")
ex := " abc"
if s != ex {
t.Fatalf("PadOnRight failed to get expected ->%s<-, got ->%s<-", ex, s)
}
s = PadOnLeft(5, 12)
ex = " 12"
if s != ex {
t.Fatalf("PadOnRight failed to get expected ->%s<-, got ->%s<-", ex, s)
}
}
// func FixBindParams ( qry string, data ...interface{} ) ( qryFixed string, retData []interface{}, err error ) {
func SVar(v interface{}) string {
s, err := json.Marshal(v)
if err != nil {
return fmt.Sprintf("Error:%s", err)
} else {
return string(s)
}
}
type TBindParams struct {
q string // the query
D int // the data [ index to correct data in func ]
lD int // length of returnd data
hE bool // error found
rv string
ds string
}
var testCasesTBindParams = []TBindParams{
{"select * from test1", 0, 0, false, "select * from test1", "null"},
{`select * from "test1"`, 0, 0, false, "select * from [test1]", "null"},
{`select * from "test1" where "n" = $1`, 1, 1, false, "select * from [test1] where [n] = ?", "[12]"},
{`select * from "test1" where "n" = $1 and M = $2`, 2, 2, false, "select * from [test1] where [n] = ? and M = ?", "[12,\"a\"]"},
{`select * from "test1" where "n" = $2 and M = $1`, 2, 2, false, "select * from [test1] where [n] = ? and M = ?", "[\"a\",12]"},
{`select * from "test1" where "n" = $1 or "n" = $1 or "n" = $3`,
3, 3, false, "select * from [test1] where [n] = ? or [n] = ? or [n] = ?", "[12,12,98.7]"},
{`select * from "test1" where "n" = $3 or "n" = $2 or "n" = $1`,
3, 3, false, "select * from [test1] where [n] = ? or [n] = ? or [n] = ?", "[98.7,\"a\",12]"},
// test with $ in quoted string ' quote, also that you can reduce # of bind values returned.
{`select * from "test1" where "n" = '$3' or "n" = $2 or "n" = $1`,
3, 2, false, "select * from [test1] where [n] = '$3' or [n] = ? or [n] = ?", "[\"a\",12]"},
// test with $ in quoted string " quote, weird column name "$2"
{`select * from "test1" where "n" = $3 or "n" = "$2" or "n" = $1`,
3, 2, false, "select * from [test1] where [n] = ? or [n] = [$2] or [n] = ?", "[98.7,12]"},
// test with " in ' string
{`select * from "test1" where "n" = 'ab"cd' or "n" = $2 or "n" = $1`,
3, 2, false, "select * from [test1] where [n] = 'ab\"cd' or [n] = ? or [n] = ?", "[\"a\",12]"},
// test (2) with " in ' string
{`select * from "test1" where "n" = 'ab"' or "n" = $2 or "n" = $1`,
3, 2, false, "select * from [test1] where [n] = 'ab\"' or [n] = ? or [n] = ?", "[\"a\",12]"},
// test (3) with " in ' string
{`select * from "test1" where "n" = '"' or "n" = $2 or "n" = $1`,
3, 2, false, "select * from [test1] where [n] = '\"' or [n] = ? or [n] = ?", "[\"a\",12]"},
// test with ' in " string
{`select * from "test1" where "n" = $3 or "v'" = $2 or "n" = $1`,
3, 3, false, "select * from [test1] where [n] = ? or [v'] = ? or [n] = ?", "[98.7,\"a\",12]"},
// [13] test with improperly terminated '
{`select * from "test1" where "n" = $3 or "n" = $2 or "n" = 'a`,
3, 2, false, "select * from [test1] where [n] = ? or [n] = ? or [n] = 'a", "[98.7,\"a\"]"},
// [14] test with improperly terminated "
{`select * from "test1" where "n" = $3 or "n" = $2 or "n`,
3, 2, false, "select * from [test1] where [n] = ? or [n] = ? or [n", "[98.7,\"a\"]"},
// [15] test with bad $ bind, "$" at end of string
{`select * from "test1" where "n" = $3 or "n" = $2 or "n" = $`,
3, 2, true, "select * from [test1] where [n] = ? or [n] = ? or [n] = ?", "[98.7,\"a\"]"},
// test 3 input bind and 5 output bind
{`select * from "test1" where "n" = $3 or "n" = $2 or "n" = $1 or "n" = $1 or "n" = $1`,
3, 5, false, "select * from [test1] where [n] = ? or [n] = ? or [n] = ? or [n] = ? or [n] = ?", "[98.7,\"a\",12,12,12]"},
}
func TestFixBindParams01(t *testing.T) {
// qf, dt, err := FixBindParams ( "select * from test1" )
var qf string
var dt []interface{}
var err error
for i, v := range testCasesTBindParams {
_ = i
// fmt.Printf ( "Test %d Start\n", i )
switch v.D {
case 0:
qf, dt, err = FixBindParams(v.q)
case 1:
qf, dt, err = FixBindParams(v.q, 12)
case 2:
qf, dt, err = FixBindParams(v.q, 12, "a")
case 3:
qf, dt, err = FixBindParams(v.q, 12, "a", 98.7)
}
sd := SVar(dt)
if qf != v.rv {
t.Fatalf("Failed to return simple query")
}
if len(dt) != v.lD {
t.Fatalf("Failed to retrun bind set of correct length, expected len=%d/%v, got len=%d/%v", v.lD, v.ds, len(dt), sd)
}
if !v.hE {
if err != nil {
t.Fatalf("Generated error where none is found, err=%s", err)
}
} else {
if err == nil {
t.Fatalf("Generated NO error where one should be found, at test %d", i)
}
}
if sd != v.ds {
t.Fatalf("Incorrect bind params returned, expectd=%s got=%s\n", v.ds, sd)
}
// fmt.Printf ( "Test %d Done\n", i )
}
}
/* vim: set noai ts=4 sw=4: */
| [
"\"HOME\""
]
| []
| [
"HOME"
]
| [] | ["HOME"] | go | 1 | 0 | |
pkg/settings/setting.go | package settings
import (
"encoding/json"
"fmt"
"os"
"regexp"
"strconv"
"strings"
v32 "github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"
authsettings "github.com/rancher/rancher/pkg/auth/settings"
fleetconst "github.com/rancher/rancher/pkg/fleet"
"github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
)
const RancherVersionDev = "2.6.99"
var (
releasePattern = regexp.MustCompile("^v[0-9]")
settings = map[string]Setting{}
provider Provider
InjectDefaults string
AgentImage = NewSetting("agent-image", "rancher/rancher-agent:v2.6-head")
AgentRolloutTimeout = NewSetting("agent-rollout-timeout", "300s")
AgentRolloutWait = NewSetting("agent-rollout-wait", "true")
AuthImage = NewSetting("auth-image", v32.ToolsSystemImages.AuthSystemImages.KubeAPIAuth)
AuthTokenMaxTTLMinutes = NewSetting("auth-token-max-ttl-minutes", "0") // never expire
AuthorizationCacheTTLSeconds = NewSetting("authorization-cache-ttl-seconds", "10")
AuthorizationDenyCacheTTLSeconds = NewSetting("authorization-deny-cache-ttl-seconds", "10")
AzureGroupCacheSize = NewSetting("azure-group-cache-size", "10000")
CACerts = NewSetting("cacerts", "")
CLIURLDarwin = NewSetting("cli-url-darwin", "https://releases.rancher.com/cli/v1.0.0-alpha8/rancher-darwin-amd64-v1.0.0-alpha8.tar.gz")
CLIURLLinux = NewSetting("cli-url-linux", "https://releases.rancher.com/cli/v1.0.0-alpha8/rancher-linux-amd64-v1.0.0-alpha8.tar.gz")
CLIURLWindows = NewSetting("cli-url-windows", "https://releases.rancher.com/cli/v1.0.0-alpha8/rancher-windows-386-v1.0.0-alpha8.zip")
ClusterControllerStartCount = NewSetting("cluster-controller-start-count", "50")
EngineInstallURL = NewSetting("engine-install-url", "https://releases.rancher.com/install-docker/20.10.sh")
EngineISOURL = NewSetting("engine-iso-url", "https://releases.rancher.com/os/latest/rancheros-vmware.iso")
EngineNewestVersion = NewSetting("engine-newest-version", "v17.12.0")
EngineSupportedRange = NewSetting("engine-supported-range", "~v1.11.2 || ~v1.12.0 || ~v1.13.0 || ~v17.03.0 || ~v17.06.0 || ~v17.09.0 || ~v18.06.0 || ~v18.09.0 || ~v19.03.0 || ~v20.10.0 ")
FirstLogin = NewSetting("first-login", "true")
GlobalRegistryEnabled = NewSetting("global-registry-enabled", "false")
GithubProxyAPIURL = NewSetting("github-proxy-api-url", "https://api.github.com")
HelmVersion = NewSetting("helm-version", "dev")
HelmMaxHistory = NewSetting("helm-max-history", "10")
IngressIPDomain = NewSetting("ingress-ip-domain", "sslip.io")
InstallUUID = NewSetting("install-uuid", "")
InternalServerURL = NewSetting("internal-server-url", "")
InternalCACerts = NewSetting("internal-cacerts", "")
IsRKE = NewSetting("is-rke", "")
JailerTimeout = NewSetting("jailer-timeout", "60")
KubeconfigGenerateToken = NewSetting("kubeconfig-generate-token", "true")
KubeconfigTokenTTLMinutes = NewSetting("kubeconfig-token-ttl-minutes", "960") // 16 hours
KubernetesVersion = NewSetting("k8s-version", "")
KubernetesVersionToServiceOptions = NewSetting("k8s-version-to-service-options", "")
KubernetesVersionToSystemImages = NewSetting("k8s-version-to-images", "")
KubernetesVersionsCurrent = NewSetting("k8s-versions-current", "")
KubernetesVersionsDeprecated = NewSetting("k8s-versions-deprecated", "")
KDMBranch = NewSetting("kdm-branch", "dev-v2.6")
MachineVersion = NewSetting("machine-version", "dev")
Namespace = NewSetting("namespace", os.Getenv("CATTLE_NAMESPACE"))
PasswordMinLength = NewSetting("password-min-length", "12")
PeerServices = NewSetting("peer-service", os.Getenv("CATTLE_PEER_SERVICE"))
RDNSServerBaseURL = NewSetting("rdns-base-url", "https://api.lb.rancher.cloud/v1")
RkeVersion = NewSetting("rke-version", "")
RkeMetadataConfig = NewSetting("rke-metadata-config", getMetadataConfig())
ServerImage = NewSetting("server-image", "rancher/rancher")
ServerURL = NewSetting("server-url", "")
ServerVersion = NewSetting("server-version", "dev")
SystemAgentVersion = NewSetting("system-agent-version", "")
WinsAgentVersion = NewSetting("wins-agent-version", "")
CSIProxyAgentVersion = NewSetting("csi-proxy-agent-version", "")
CSIProxyAgentURL = NewSetting("csi-proxy-agent-url", "https://acs-mirror.azureedge.net/csi-proxy/%[1]s/binaries/csi-proxy-%[1]s.tar.gz")
SystemAgentInstallScript = NewSetting("system-agent-install-script", "https://raw.githubusercontent.com/rancher/system-agent/v0.2.6/install.sh")
WinsAgentInstallScript = NewSetting("wins-agent-install-script", "https://raw.githubusercontent.com/rancher/wins/v0.2.6/install.ps1")
SystemAgentInstallerImage = NewSetting("system-agent-installer-image", "rancher/system-agent-installer-")
SystemAgentUpgradeImage = NewSetting("system-agent-upgrade-image", "")
SystemDefaultRegistry = NewSetting("system-default-registry", "")
SystemNamespaces = NewSetting("system-namespaces", "kube-system,kube-public,cattle-system,cattle-alerting,cattle-logging,cattle-pipeline,cattle-prometheus,ingress-nginx,cattle-global-data,cattle-istio,kube-node-lease,cert-manager,cattle-global-nt,security-scan,cattle-fleet-system,cattle-fleet-local-system,calico-system,tigera-operator,cattle-impersonation-system,rancher-operator-system")
SystemUpgradeControllerChartVersion = NewSetting("system-upgrade-controller-chart-version", "")
TelemetryOpt = NewSetting("telemetry-opt", "")
TLSMinVersion = NewSetting("tls-min-version", "1.2")
TLSCiphers = NewSetting("tls-ciphers", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305")
UIBanners = NewSetting("ui-banners", "{}")
UIBrand = NewSetting("ui-brand", "")
UIDefaultLanding = NewSetting("ui-default-landing", "vue")
UIFeedBackForm = NewSetting("ui-feedback-form", "")
UIIndex = NewSetting("ui-index", "https://releases.rancher.com/ui/latest2/index.html")
UIPath = NewSetting("ui-path", "/usr/share/rancher/ui")
UIDashboardIndex = NewSetting("ui-dashboard-index", "https://releases.rancher.com/dashboard/latest/index.html")
UIDashboardPath = NewSetting("ui-dashboard-path", "/usr/share/rancher/ui-dashboard")
UIPreferred = NewSetting("ui-preferred", "vue")
UIOfflinePreferred = NewSetting("ui-offline-preferred", "dynamic")
UIIssues = NewSetting("ui-issues", "")
UIPL = NewSetting("ui-pl", "rancher")
UICommunityLinks = NewSetting("ui-community-links", "true")
UIKubernetesSupportedVersions = NewSetting("ui-k8s-supported-versions-range", ">= 1.11.0 <=1.14.x")
UIKubernetesDefaultVersion = NewSetting("ui-k8s-default-version-range", "<=1.14.x")
WhitelistDomain = NewSetting("whitelist-domain", "forums.rancher.com")
WhitelistEnvironmentVars = NewSetting("whitelist-envvars", "HTTP_PROXY,HTTPS_PROXY,NO_PROXY")
AuthUserInfoResyncCron = NewSetting("auth-user-info-resync-cron", "0 0 * * *")
AuthUserSessionTTLMinutes = NewSetting("auth-user-session-ttl-minutes", "960") // 16 hours
AuthUserInfoMaxAgeSeconds = NewSetting("auth-user-info-max-age-seconds", "3600") // 1 hour
APIUIVersion = NewSetting("api-ui-version", "1.1.6") // Please update the CATTLE_API_UI_VERSION in package/Dockerfile when updating the version here.
RotateCertsIfExpiringInDays = NewSetting("rotate-certs-if-expiring-in-days", "7") // 7 days
ClusterTemplateEnforcement = NewSetting("cluster-template-enforcement", "false")
InitialDockerRootDir = NewSetting("initial-docker-root-dir", "/var/lib/docker")
SystemCatalog = NewSetting("system-catalog", "external") // Options are 'external' or 'bundled'
ChartDefaultBranch = NewSetting("chart-default-branch", "dev-v2.6")
PartnerChartDefaultBranch = NewSetting("partner-chart-default-branch", "main")
RKE2ChartDefaultBranch = NewSetting("rke2-chart-default-branch", "main")
FleetDefaultWorkspaceName = NewSetting("fleet-default-workspace-name", fleetconst.ClustersDefaultNamespace) // fleetWorkspaceName to assign to clusters with none
ShellImage = NewSetting("shell-image", "rancher/shell:v0.1.16")
IgnoreNodeName = NewSetting("ignore-node-name", "") // nodes to ignore when syncing v1.node to v3.node
NoDefaultAdmin = NewSetting("no-default-admin", "")
RestrictedDefaultAdmin = NewSetting("restricted-default-admin", "false") // When bootstrapping the admin for the first time, give them the global role restricted-admin
AKSUpstreamRefresh = NewSetting("aks-refresh", "300")
EKSUpstreamRefreshCron = NewSetting("eks-refresh-cron", "*/5 * * * *") // EKSUpstreamRefreshCron is deprecated and will be replaced by EKSUpstreamRefresh
EKSUpstreamRefresh = NewSetting("eks-refresh", "300")
GKEUpstreamRefresh = NewSetting("gke-refresh", "300")
HideLocalCluster = NewSetting("hide-local-cluster", "false")
MachineProvisionImage = NewSetting("machine-provision-image", "rancher/machine:v0.15.0-rancher85")
SystemFeatureChartRefreshSeconds = NewSetting("system-feature-chart-refresh-seconds", "900")
FleetMinVersion = NewSetting("fleet-min-version", "")
RancherWebhookMinVersion = NewSetting("rancher-webhook-min-version", "")
Rke2DefaultVersion = NewSetting("rke2-default-version", "")
K3sDefaultVersion = NewSetting("k3s-default-version", "")
)
func FullShellImage() string {
return PrefixPrivateRegistry(ShellImage.Get())
}
func PrefixPrivateRegistry(image string) string {
private := SystemDefaultRegistry.Get()
if private == "" {
return image
}
return private + "/" + image
}
func IsRelease() bool {
return !strings.Contains(ServerVersion.Get(), "head") && releasePattern.MatchString(ServerVersion.Get())
}
func init() {
// setup auth setting
authsettings.AuthUserInfoResyncCron = AuthUserInfoResyncCron
authsettings.AuthUserSessionTTLMinutes = AuthUserSessionTTLMinutes
authsettings.AuthUserInfoMaxAgeSeconds = AuthUserInfoMaxAgeSeconds
authsettings.FirstLogin = FirstLogin
if InjectDefaults == "" {
return
}
defaults := map[string]string{}
if err := json.Unmarshal([]byte(InjectDefaults), &defaults); err != nil {
return
}
for name, defaultValue := range defaults {
value, ok := settings[name]
if !ok {
continue
}
value.Default = defaultValue
settings[name] = value
}
}
type Provider interface {
Get(name string) string
Set(name, value string) error
SetIfUnset(name, value string) error
SetAll(settings map[string]Setting) error
}
type Setting struct {
Name string
Default string
ReadOnly bool
}
func (s Setting) SetIfUnset(value string) error {
if provider == nil {
return s.Set(value)
}
return provider.SetIfUnset(s.Name, value)
}
func (s Setting) Set(value string) error {
if provider == nil {
s, ok := settings[s.Name]
if ok {
s.Default = value
settings[s.Name] = s
}
} else {
return provider.Set(s.Name, value)
}
return nil
}
func (s Setting) Get() string {
if provider == nil {
s := settings[s.Name]
return s.Default
}
return provider.Get(s.Name)
}
func (s Setting) GetInt() int {
v := s.Get()
i, err := strconv.Atoi(v)
if err == nil {
return i
}
logrus.Errorf("failed to parse setting %s=%s as int: %v", s.Name, v, err)
i, err = strconv.Atoi(s.Default)
if err != nil {
return 0
}
return i
}
func SetProvider(p Provider) error {
if err := p.SetAll(settings); err != nil {
return err
}
provider = p
return nil
}
func NewSetting(name, def string) Setting {
s := Setting{
Name: name,
Default: def,
}
settings[s.Name] = s
return s
}
func GetEnvKey(key string) string {
return "CATTLE_" + strings.ToUpper(strings.Replace(key, "-", "_", -1))
}
func getMetadataConfig() string {
branch := KDMBranch.Get()
data := map[string]interface{}{
"url": fmt.Sprintf("https://releases.rancher.com/kontainer-driver-metadata/%s/data.json", branch),
"refresh-interval-minutes": "1440",
}
ans, err := json.Marshal(data)
if err != nil {
logrus.Errorf("error getting metadata config %v", err)
return ""
}
return string(ans)
}
// GetSettingByID returns a setting that is stored with the given id
func GetSettingByID(id string) string {
if provider == nil {
s := settings[id]
return s.Default
}
return provider.Get(id)
}
func DefaultAgentSettings() []Setting {
return []Setting{
ServerVersion,
InstallUUID,
IngressIPDomain,
}
}
func DefaultAgentSettingsAsEnvVars() []v1.EnvVar {
defaultAgentSettings := DefaultAgentSettings()
envVars := make([]v1.EnvVar, 0, len(defaultAgentSettings))
for _, s := range defaultAgentSettings {
envVars = append(envVars, v1.EnvVar{
Name: GetEnvKey(s.Name),
Value: s.Get(),
})
}
return envVars
}
func GetRancherVersion() string {
rancherVersion := ServerVersion.Get()
if strings.HasPrefix(rancherVersion, "dev") || strings.HasPrefix(rancherVersion, "master") || strings.HasSuffix(rancherVersion, "-head") {
return RancherVersionDev
}
return strings.TrimPrefix(rancherVersion, "v")
}
| [
"\"CATTLE_NAMESPACE\"",
"\"CATTLE_PEER_SERVICE\""
]
| []
| [
"CATTLE_NAMESPACE",
"CATTLE_PEER_SERVICE"
]
| [] | ["CATTLE_NAMESPACE", "CATTLE_PEER_SERVICE"] | go | 2 | 0 | |
curriculum/experiments/goals/maze/maze_oracle.py | import os
os.environ['THEANO_FLAGS'] = 'floatX=float32,device=cpu'
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import tensorflow as tf
import tflearn
import argparse
import sys
from multiprocessing import cpu_count
from rllab.misc.instrument import run_experiment_lite
from rllab.misc.instrument import VariantGenerator
from rllab import config
from curriculum.experiments.goals.maze.maze_oracle_algo import run_task
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--ec2', '-e', action='store_true', default=False, help="add flag to run in ec2")
parser.add_argument('--clone', '-c', action='store_true', default=False,
help="add flag to copy file and checkout current")
parser.add_argument('--local_docker', '-d', action='store_true', default=False,
help="add flag to run in local dock")
parser.add_argument('--type', '-t', type=str, default='', help='set instance type')
parser.add_argument('--price', '-p', type=str, default='', help='set betting price')
parser.add_argument('--subnet', '-sn', type=str, default='', help='set subnet like us-west-1a')
parser.add_argument('--name', '-n', type=str, default='', help='set exp prefix name and new file name')
parser.add_argument('--debug', action='store_true', default=False, help="run code without multiprocessing")
args = parser.parse_args()
# setup ec2
subnets = [
# 'ap-south-1b', 'ap-northeast-2a', 'us-east-2b', 'us-east-2c', 'ap-northeast-2c', 'us-west-1b', 'us-west-1a',
# 'ap-south-1a', 'ap-northeast-1a', 'us-east-1a', 'us-east-1d', 'us-east-1e', 'us-east-1b'
]
ec2_instance = args.type if args.type else 'c4.8xlarge'
# configure instan
info = config.INSTANCE_TYPE_INFO[ec2_instance]
config.AWS_INSTANCE_TYPE = ec2_instance
config.AWS_SPOT_PRICE = str(info["price"])
n_parallel = int(info["vCPU"] / 2) # make the default 4 if not using ec2
if args.ec2:
mode = 'ec2'
elif args.local_docker:
mode = 'local_docker'
n_parallel = cpu_count() if not args.debug else 1
else:
mode = 'local'
n_parallel = cpu_count() if not args.debug else 1
# n_parallel = multiprocessing.cpu_count()
exp_prefix = 'new-oracle-maze-persist1-L2'
vg = VariantGenerator()
vg.add('goal_size', [2]) # this is the ultimate goal we care about: getting the pendulum upright
vg.add('terminal_eps', [0.3])
vg.add('only_feasible', [True])
vg.add('maze_id', [0, 11]) # default is 0
vg.add('goal_range',
lambda maze_id: [5] if maze_id == 0 else [7]) # this will be used also as bound of the state_space
vg.add('goal_center', lambda maze_id: [(2, 2)] if maze_id == 0 else [(0, 0)])
# goal-algo params
vg.add('min_reward', [0])
vg.add('max_reward', [1])
vg.add('distance_metric', ['L2'])
vg.add('extend_dist_rew', [True, False]) # !!!!
vg.add('persistence', [1])
vg.add('n_traj', [3]) # only for labeling and plotting (for now, later it will have to be equal to persistence!)
vg.add('sampling_res', [2])
vg.add('with_replacement', [False])
# replay buffer
vg.add('replay_buffer', [False])
vg.add('coll_eps', [0.3])
vg.add('num_new_goals', [40, 60])
vg.add('num_old_goals', [0])
# sampling params
vg.add('horizon', lambda maze_id: [200] if maze_id == 0 else [500])
vg.add('outer_iters', lambda maze_id: [200] if maze_id == 0 else [1000])
vg.add('inner_iters', [3]) # again we will have to divide/adjust the
vg.add('pg_batch_size', [20000])
# policy initialization
vg.add('output_gain', [1])
vg.add('policy_init_std', [1])
vg.add('learn_std', [False])
vg.add('adaptive_std', [False])
vg.add('seed', range(100, 150, 10))
# # gan_configs
# vg.add('GAN_batch_size', [128]) # proble with repeated name!!
# vg.add('GAN_generator_activation', ['relu'])
# vg.add('GAN_discriminator_activation', ['relu'])
# vg.add('GAN_generator_optimizer', [tf.train.AdamOptimizer])
# vg.add('GAN_generator_optimizer_stepSize', [0.001])
# vg.add('GAN_discriminator_optimizer', [tf.train.AdamOptimizer])
# vg.add('GAN_discriminator_optimizer_stepSize', [0.001])
# vg.add('GAN_generator_weight_initializer', [tflearn.initializations.truncated_normal])
# vg.add('GAN_generator_weight_initializer_stddev', [0.05])
# vg.add('GAN_discriminator_weight_initializer', [tflearn.initializations.truncated_normal])
# vg.add('GAN_discriminator_weight_initializer_stddev', [0.02])
# vg.add('GAN_discriminator_batch_noise_stddev', [1e-2])
# Launching
print("\n" + "**********" * 10 + "\nexp_prefix: {}\nvariants: {}".format(exp_prefix, vg.size))
print('Running on type {}, with price {}, parallel {} on the subnets: '.format(config.AWS_INSTANCE_TYPE,
config.AWS_SPOT_PRICE, n_parallel),
*subnets)
for vv in vg.variants():
if mode in ['ec2', 'local_docker']:
# # choose subnet
# subnet = random.choice(subnets)
# config.AWS_REGION_NAME = subnet[:-1]
# config.AWS_KEY_NAME = config.ALL_REGION_AWS_KEY_NAMES[
# config.AWS_REGION_NAME]
# config.AWS_IMAGE_ID = config.ALL_REGION_AWS_IMAGE_IDS[
# config.AWS_REGION_NAME]
# config.AWS_SECURITY_GROUP_IDS = \
# config.ALL_REGION_AWS_SECURITY_GROUP_IDS[
# config.AWS_REGION_NAME]
# config.AWS_NETWORK_INTERFACES = [
# dict(
# SubnetId=config.ALL_SUBNET_INFO[subnet]["SubnetID"],
# Groups=config.AWS_SECURITY_GROUP_IDS,
# DeviceIndex=0,
# AssociatePublicIpAddress=True,
# )
# ]
run_experiment_lite(
# use_cloudpickle=False,
stub_method_call=run_task,
variant=vv,
mode=mode,
# Number of parallel workers for sampling
n_parallel=n_parallel,
# Only keep the snapshot parameters for the last iteration
snapshot_mode="last",
seed=vv['seed'],
# plot=True,
exp_prefix=exp_prefix,
# exp_name=exp_name,
# for sync the pkl file also during the training
sync_s3_pkl=True,
# sync_s3_png=True,
sync_s3_html=True,
# # use this ONLY with ec2 or local_docker!!!
pre_commands=[
'export MPLBACKEND=Agg',
'pip install --upgrade pip',
'pip install --upgrade -I tensorflow',
'pip install git+https://github.com/tflearn/tflearn.git',
'pip install dominate',
'pip install multiprocessing_on_dill',
'pip install scikit-image',
'conda install numpy -n rllab3 -y',
],
)
if mode == 'local_docker':
sys.exit()
else:
run_experiment_lite(
# use_cloudpickle=False,
stub_method_call=run_task,
variant=vv,
mode='local',
n_parallel=n_parallel,
# Only keep the snapshot parameters for the last iteration
snapshot_mode="last",
seed=vv['seed'],
exp_prefix=exp_prefix,
# exp_name=exp_name,
)
| []
| []
| [
"THEANO_FLAGS",
"CUDA_VISIBLE_DEVICES"
]
| [] | ["THEANO_FLAGS", "CUDA_VISIBLE_DEVICES"] | python | 2 | 0 | |
server/launch/sample/main_machine/main_instance/experiment_dummy/server_config.py | #!/usr/bin/env python
#-*-*- encoding: utf-8 -*-*-
weblab_xilinx_experiment_xilinx_device = 'FPGA'
weblab_xilinx_experiment_port_number = 1
# This should be something like this:
# import os as _os
# xilinx_home = _os.getenv('XILINX_HOME')
# if xilinx_home == None:
# if _os.name == 'nt':
# xilinx_home = r'C:\Program Files\Xilinx'
# elif _os.name == 'posix':
# xilinx_home = r"/home/nctrun/Xilinx"
#
# if _os.name == 'nt':
# xilinx_impact_full_path = [xilinx_home + r'\bin\nt\impact']
# elif _os.name == 'posix':
# xilinx_impact_full_path = [xilinx_home + r'/bin/lin/impact']
# But for testing we are going to fake it:
xilinx_home = "."
xilinx_impact_full_path = ["python","./test/unit/weblab/experiment/devices/xilinx_impact/fake_impact.py" ]
xilinx_device_to_program = 'XilinxImpact' # 'JTagBlazer', 'DigilentAdept'
xilinx_device_to_send_commands = 'SerialPort' # 'HttpDevice'
digilent_adept_full_path = ["python","./test/unit/weblab/experiment/devices/digilent_adept/fake_digilent_adept.py" ]
digilent_adept_batch_content = """something with the variable $FILE"""
xilinx_http_device_ip_FPGA = "192.168.50.138"
xilinx_http_device_port_FPGA = 80
xilinx_http_device_app_FPGA = ""
xilinx_batch_content_FPGA = """setMode -bs
setCable -port auto
addDevice -position 1 -file $FILE
Program -p 1
exit
"""
# Though it is not really a FPGA, the webcam url var name depends on the device,
# specified above.
fpga_webcam_url = '''https://www.weblab.deusto.es/webcam/fpga0/image.jpg'''
| []
| []
| [
"XILINX_HOME"
]
| [] | ["XILINX_HOME"] | python | 1 | 0 | |
salt/modules/cmdmod.py | """
A module for shelling out.
Keep in mind that this module is insecure, in that it can give whomever has
access to the master root execution access to all salt minions.
"""
# Import python libs
import base64
import fnmatch
import functools
import glob
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import traceback
# Import salt libs
import salt.grains.extra
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.powershell
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.timed_subprocess
import salt.utils.user
import salt.utils.versions
import salt.utils.vt
import salt.utils.win_chcp
import salt.utils.win_dacl
import salt.utils.win_reg
from salt.exceptions import (
CommandExecutionError,
SaltInvocationError,
TimedProcTimeoutError,
)
from salt.ext.six.moves import map, range, zip
from salt.log import LOG_LEVELS
# Only available on POSIX systems, nonfatal on windows
try:
import grp
import pwd
except ImportError:
pass
if salt.utils.platform.is_windows():
from salt.utils.win_functions import escape_argument as _cmd_quote
from salt.utils.win_runas import runas as win_runas
HAS_WIN_RUNAS = True
else:
from salt.ext.six.moves import shlex_quote as _cmd_quote
HAS_WIN_RUNAS = False
__proxyenabled__ = ["*"]
# Define the module's virtual name
__virtualname__ = "cmd"
# Set up logging
log = logging.getLogger(__name__)
DEFAULT_SHELL = salt.grains.extra.shell()["shell"]
# Overwriting the cmd python module makes debugging modules with pdb a bit
# harder so lets do it this way instead.
def __virtual__():
return __virtualname__
def _check_cb(cb_):
"""
If the callback is None or is not callable, return a lambda that returns
the value passed.
"""
if cb_ is not None:
if hasattr(cb_, "__call__"):
return cb_
else:
log.error("log_callback is not callable, ignoring")
return lambda x: x
def _python_shell_default(python_shell, __pub_jid):
"""
Set python_shell default based on remote execution and __opts__['cmd_safe']
"""
try:
# Default to python_shell=True when run directly from remote execution
# system. Cross-module calls won't have a jid.
if __pub_jid and python_shell is None:
return True
elif __opts__.get("cmd_safe", True) is False and python_shell is None:
# Override-switch for python_shell
return True
except NameError:
pass
return python_shell
def _chroot_pids(chroot):
pids = []
for root in glob.glob("/proc/[0-9]*/root"):
try:
link = os.path.realpath(root)
if link.startswith(chroot):
pids.append(int(os.path.basename(os.path.dirname(root))))
except OSError:
pass
return pids
def _render_cmd(
cmd, cwd, template, saltenv="base", pillarenv=None, pillar_override=None
):
"""
If template is a valid template engine, process the cmd and cwd through
that engine.
"""
if not template:
return (cmd, cwd)
# render the path as a template using path_template_engine as the engine
if template not in salt.utils.templates.TEMPLATE_REGISTRY:
raise CommandExecutionError(
"Attempted to render file paths with unavailable engine "
"{}".format(template)
)
kwargs = {}
kwargs["salt"] = __salt__
if pillarenv is not None or pillar_override is not None:
pillarenv = pillarenv or __opts__["pillarenv"]
kwargs["pillar"] = _gather_pillar(pillarenv, pillar_override)
else:
kwargs["pillar"] = __pillar__
kwargs["grains"] = __grains__
kwargs["opts"] = __opts__
kwargs["saltenv"] = saltenv
def _render(contents):
# write out path to temp file
tmp_path_fn = salt.utils.files.mkstemp()
with salt.utils.files.fopen(tmp_path_fn, "w+") as fp_:
fp_.write(salt.utils.stringutils.to_str(contents))
data = salt.utils.templates.TEMPLATE_REGISTRY[template](
tmp_path_fn, to_str=True, **kwargs
)
salt.utils.files.safe_rm(tmp_path_fn)
if not data["result"]:
# Failed to render the template
raise CommandExecutionError(
"Failed to execute cmd with error: {}".format(data["data"])
)
else:
return data["data"]
cmd = _render(cmd)
cwd = _render(cwd)
return (cmd, cwd)
def _check_loglevel(level="info"):
"""
Retrieve the level code for use in logging.Logger.log().
"""
try:
level = level.lower()
if level == "quiet":
return None
else:
return LOG_LEVELS[level]
except (AttributeError, KeyError):
log.error(
"Invalid output_loglevel '%s'. Valid levels are: %s. Falling "
"back to 'info'.",
level,
", ".join(sorted(LOG_LEVELS, reverse=True)),
)
return LOG_LEVELS["info"]
def _parse_env(env):
if not env:
env = {}
if isinstance(env, list):
env = salt.utils.data.repack_dictlist(env)
if not isinstance(env, dict):
env = {}
return env
def _gather_pillar(pillarenv, pillar_override):
"""
Whenever a state run starts, gather the pillar data fresh
"""
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__["id"],
__opts__["saltenv"],
pillar_override=pillar_override,
pillarenv=pillarenv,
)
ret = pillar.compile_pillar()
if pillar_override and isinstance(pillar_override, dict):
ret.update(pillar_override)
return ret
def _check_avail(cmd):
"""
Check to see if the given command can be run
"""
if isinstance(cmd, list):
cmd = " ".join([str(x) if not isinstance(x, str) else x for x in cmd])
bret = True
wret = False
if __salt__["config.get"]("cmd_blacklist_glob"):
blist = __salt__["config.get"]("cmd_blacklist_glob", [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# BAD! you are blacklisted
bret = False
if __salt__["config.get"]("cmd_whitelist_glob", []):
blist = __salt__["config.get"]("cmd_whitelist_glob", [])
for comp in blist:
if fnmatch.fnmatch(cmd, comp):
# GOOD! You are whitelisted
wret = True
break
else:
# If no whitelist set then alls good!
wret = True
return bret and wret
def _run(
cmd,
cwd=None,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
output_encoding=None,
output_loglevel="debug",
log_callback=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
prepend_path=None,
rstrip=True,
template=None,
umask=None,
timeout=None,
with_communicate=True,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
pillarenv=None,
pillar_override=None,
use_vt=False,
password=None,
bg=False,
encoded_cmd=False,
success_retcodes=None,
windows_codepage=65001,
**kwargs
):
"""
Do the DRY thing and only call subprocess.Popen() once
"""
if "pillar" in kwargs and not pillar_override:
pillar_override = kwargs["pillar"]
if output_loglevel != "quiet" and _is_valid_shell(shell) is False:
log.warning(
"Attempt to run a shell command with what may be an invalid shell! "
"Check to ensure that the shell <%s> is valid for this user.",
shell,
)
output_loglevel = _check_loglevel(output_loglevel)
log_callback = _check_cb(log_callback)
use_sudo = False
if runas is None and "__context__" in globals():
runas = __context__.get("runas")
if password is None and "__context__" in globals():
password = __context__.get("runas_password")
# Set the default working directory to the home directory of the user
# salt-minion is running as. Defaults to home directory of user under which
# the minion is running.
if not cwd:
cwd = os.path.expanduser("~{}".format("" if not runas else runas))
# make sure we can access the cwd
# when run from sudo or another environment where the euid is
# changed ~ will expand to the home of the original uid and
# the euid might not have access to it. See issue #1844
if not os.access(cwd, os.R_OK):
cwd = "/"
if salt.utils.platform.is_windows():
cwd = os.path.abspath(os.sep)
else:
# Handle edge cases where numeric/other input is entered, and would be
# yaml-ified into non-string types
cwd = str(cwd)
if bg:
ignore_retcode = True
use_vt = False
if not salt.utils.platform.is_windows():
if not os.path.isfile(shell) or not os.access(shell, os.X_OK):
msg = "The shell {} is not available".format(shell)
raise CommandExecutionError(msg)
elif use_vt: # Memozation so not much overhead
raise CommandExecutionError("VT not available on windows")
elif windows_codepage is not None:
salt.utils.win_chcp.chcp(windows_codepage)
if shell.lower().strip() == "powershell":
# Strip whitespace
if isinstance(cmd, str):
cmd = cmd.strip()
elif isinstance(cmd, list):
cmd = " ".join(cmd).strip()
# If we were called by script(), then fakeout the Windows
# shell to run a Powershell script.
# Else just run a Powershell command.
stack = traceback.extract_stack(limit=2)
# extract_stack() returns a list of tuples.
# The last item in the list [-1] is the current method.
# The third item[2] in each tuple is the name of that method.
if stack[-2][2] == "script":
cmd = "Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass {}".format(
cmd.replace('"', '\\"')
)
elif encoded_cmd:
cmd = "Powershell -NonInteractive -EncodedCommand {}".format(cmd)
else:
cmd = 'Powershell -NonInteractive -NoProfile "{}"'.format(
cmd.replace('"', '\\"')
)
# munge the cmd and cwd through the template
(cmd, cwd) = _render_cmd(cmd, cwd, template, saltenv, pillarenv, pillar_override)
ret = {}
# If the pub jid is here then this is a remote ex or salt call command and needs to be
# checked if blacklisted
if "__pub_jid" in kwargs:
if not _check_avail(cmd):
raise CommandExecutionError(
'The shell command "{}" is not permitted'.format(cmd)
)
env = _parse_env(env)
for bad_env_key in (x for x, y in env.items() if y is None):
log.error(
"Environment variable '%s' passed without a value. "
"Setting value to an empty string",
bad_env_key,
)
env[bad_env_key] = ""
def _get_stripped(cmd):
# Return stripped command string copies to improve logging.
if isinstance(cmd, list):
return [x.strip() if isinstance(x, str) else x for x in cmd]
elif isinstance(cmd, str):
return cmd.strip()
else:
return cmd
if output_loglevel is not None:
# Always log the shell commands at INFO unless quiet logging is
# requested. The command output is what will be controlled by the
# 'loglevel' parameter.
msg = "Executing command {}{}{} {}{}in directory '{}'{}".format(
"'" if not isinstance(cmd, list) else "",
_get_stripped(cmd),
"'" if not isinstance(cmd, list) else "",
"as user '{}' ".format(runas) if runas else "",
"in group '{}' ".format(group) if group else "",
cwd,
". Executing command in the background, no output will be logged."
if bg
else "",
)
log.info(log_callback(msg))
if runas and salt.utils.platform.is_windows():
if not HAS_WIN_RUNAS:
msg = "missing salt/utils/win_runas.py"
raise CommandExecutionError(msg)
if isinstance(cmd, (list, tuple)):
cmd = " ".join(cmd)
return win_runas(cmd, runas, password, cwd)
if runas and salt.utils.platform.is_darwin():
# We need to insert the user simulation into the command itself and not
# just run it from the environment on macOS as that method doesn't work
# properly when run as root for certain commands.
if isinstance(cmd, (list, tuple)):
cmd = " ".join(map(_cmd_quote, cmd))
# Ensure directory is correct before running command
cmd = "cd -- {dir} && {{ {cmd}\n }}".format(dir=_cmd_quote(cwd), cmd=cmd)
# Ensure environment is correct for a newly logged-in user by running
# the command under bash as a login shell
try:
user_shell = __salt__["user.info"](runas)["shell"]
if re.search("bash$", user_shell):
cmd = "{shell} -l -c {cmd}".format(
shell=user_shell, cmd=_cmd_quote(cmd)
)
except KeyError:
pass
# Ensure the login is simulated correctly (note: su runs sh, not bash,
# which causes the environment to be initialised incorrectly, which is
# fixed by the previous line of code)
cmd = "su -l {} -c {}".format(_cmd_quote(runas), _cmd_quote(cmd))
# Set runas to None, because if you try to run `su -l` after changing
# user, su will prompt for the password of the user and cause salt to
# hang.
runas = None
if runas:
# Save the original command before munging it
try:
pwd.getpwnam(runas)
except KeyError:
raise CommandExecutionError("User '{}' is not available".format(runas))
if group:
if salt.utils.platform.is_windows():
msg = "group is not currently available on Windows"
raise SaltInvocationError(msg)
if not which_bin(["sudo"]):
msg = "group argument requires sudo but not found"
raise CommandExecutionError(msg)
try:
grp.getgrnam(group)
except KeyError:
raise CommandExecutionError("Group '{}' is not available".format(runas))
else:
use_sudo = True
if runas or group:
try:
# Getting the environment for the runas user
# Use markers to thwart any stdout noise
# There must be a better way to do this.
import uuid
marker = "<<<" + str(uuid.uuid4()) + ">>>"
marker_b = marker.encode(__salt_system_encoding__)
py_code = (
"import sys, os, itertools; "
'sys.stdout.write("' + marker + '"); '
'sys.stdout.write("\\0".join(itertools.chain(*os.environ.items()))); '
'sys.stdout.write("' + marker + '");'
)
if use_sudo:
env_cmd = ["sudo"]
# runas is optional if use_sudo is set.
if runas:
env_cmd.extend(["-u", runas])
if group:
env_cmd.extend(["-g", group])
if shell != DEFAULT_SHELL:
env_cmd.extend(["-s", "--", shell, "-c"])
else:
env_cmd.extend(["-i", "--"])
env_cmd.extend([sys.executable])
elif __grains__["os"] in ["FreeBSD"]:
env_cmd = (
"su",
"-",
runas,
"-c",
"{} -c {}".format(shell, sys.executable),
)
elif __grains__["os_family"] in ["Solaris"]:
env_cmd = ("su", "-", runas, "-c", sys.executable)
elif __grains__["os_family"] in ["AIX"]:
env_cmd = ("su", "-", runas, "-c", sys.executable)
else:
env_cmd = ("su", "-s", shell, "-", runas, "-c", sys.executable)
msg = "env command: {}".format(env_cmd)
log.debug(log_callback(msg))
env_bytes, env_encoded_err = subprocess.Popen(
env_cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
).communicate(salt.utils.stringutils.to_bytes(py_code))
marker_count = env_bytes.count(marker_b)
if marker_count == 0:
# Possibly PAM prevented the login
log.error(
"Environment could not be retrieved for user '%s': "
"stderr=%r stdout=%r",
runas,
env_encoded_err,
env_bytes,
)
# Ensure that we get an empty env_runas dict below since we
# were not able to get the environment.
env_bytes = b""
elif marker_count != 2:
raise CommandExecutionError(
"Environment could not be retrieved for user '{}'",
info={"stderr": repr(env_encoded_err), "stdout": repr(env_bytes)},
)
else:
# Strip the marker
env_bytes = env_bytes.split(marker_b)[1]
env_runas = dict(list(zip(*[iter(env_bytes.split(b"\0"))] * 2)))
env_runas = {
salt.utils.stringutils.to_str(k): salt.utils.stringutils.to_str(v)
for k, v in env_runas.items()
}
env_runas.update(env)
# Fix platforms like Solaris that don't set a USER env var in the
# user's default environment as obtained above.
if env_runas.get("USER") != runas:
env_runas["USER"] = runas
# Fix some corner cases where shelling out to get the user's
# environment returns the wrong home directory.
runas_home = os.path.expanduser("~{}".format(runas))
if env_runas.get("HOME") != runas_home:
env_runas["HOME"] = runas_home
env = env_runas
except ValueError as exc:
log.exception("Error raised retrieving environment for user %s", runas)
raise CommandExecutionError(
"Environment could not be retrieved for user '{}': {}".format(
runas, exc
)
)
if reset_system_locale is True:
if not salt.utils.platform.is_windows():
# Default to C!
# Salt only knows how to parse English words
# Don't override if the user has passed LC_ALL
env.setdefault("LC_CTYPE", "C")
env.setdefault("LC_NUMERIC", "C")
env.setdefault("LC_TIME", "C")
env.setdefault("LC_COLLATE", "C")
env.setdefault("LC_MONETARY", "C")
env.setdefault("LC_MESSAGES", "C")
env.setdefault("LC_PAPER", "C")
env.setdefault("LC_NAME", "C")
env.setdefault("LC_ADDRESS", "C")
env.setdefault("LC_TELEPHONE", "C")
env.setdefault("LC_MEASUREMENT", "C")
env.setdefault("LC_IDENTIFICATION", "C")
env.setdefault("LANGUAGE", "C")
if clean_env:
run_env = env
else:
if salt.utils.platform.is_windows():
import nt
run_env = nt.environ.copy()
else:
run_env = os.environ.copy()
run_env.update(env)
if prepend_path:
run_env["PATH"] = ":".join((prepend_path, run_env["PATH"]))
if python_shell is None:
python_shell = False
new_kwargs = {
"cwd": cwd,
"shell": python_shell,
"env": run_env,
"stdin": str(stdin) if stdin is not None else stdin,
"stdout": stdout,
"stderr": stderr,
"with_communicate": with_communicate,
"timeout": timeout,
"bg": bg,
}
if "stdin_raw_newlines" in kwargs:
new_kwargs["stdin_raw_newlines"] = kwargs["stdin_raw_newlines"]
if umask is not None:
_umask = str(umask).lstrip("0")
if _umask == "":
msg = "Zero umask is not allowed."
raise CommandExecutionError(msg)
try:
_umask = int(_umask, 8)
except ValueError:
raise CommandExecutionError("Invalid umask: '{}'".format(umask))
else:
_umask = None
if runas or group or umask:
new_kwargs["preexec_fn"] = functools.partial(
salt.utils.user.chugid_and_umask, runas, _umask, group
)
if not salt.utils.platform.is_windows():
# close_fds is not supported on Windows platforms if you redirect
# stdin/stdout/stderr
if new_kwargs["shell"] is True:
new_kwargs["executable"] = shell
new_kwargs["close_fds"] = True
if not os.path.isabs(cwd) or not os.path.isdir(cwd):
raise CommandExecutionError(
"Specified cwd '{}' either not absolute or does not exist".format(cwd)
)
if (
python_shell is not True
and not salt.utils.platform.is_windows()
and not isinstance(cmd, list)
):
cmd = salt.utils.args.shlex_split(cmd)
if success_retcodes is None:
success_retcodes = [0]
else:
try:
success_retcodes = [
int(i) for i in salt.utils.args.split_input(success_retcodes)
]
except ValueError:
raise SaltInvocationError("success_retcodes must be a list of integers")
if not use_vt:
# This is where the magic happens
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **new_kwargs)
except OSError as exc:
msg = "Unable to run command '{}' with the context '{}', reason: {}".format(
cmd if output_loglevel is not None else "REDACTED", new_kwargs, exc
)
raise CommandExecutionError(msg)
try:
proc.run()
except TimedProcTimeoutError as exc:
ret["stdout"] = str(exc)
ret["stderr"] = ""
ret["retcode"] = None
ret["pid"] = proc.process.pid
# ok return code for timeouts?
ret["retcode"] = 1
return ret
if output_loglevel != "quiet" and output_encoding is not None:
log.debug(
"Decoding output from command %s using %s encoding",
cmd,
output_encoding,
)
try:
out = salt.utils.stringutils.to_unicode(
proc.stdout, encoding=output_encoding
)
except TypeError:
# stdout is None
out = ""
except UnicodeDecodeError:
out = salt.utils.stringutils.to_unicode(
proc.stdout, encoding=output_encoding, errors="replace"
)
if output_loglevel != "quiet":
log.error(
"Failed to decode stdout from command %s, non-decodable "
"characters have been replaced",
cmd,
)
try:
err = salt.utils.stringutils.to_unicode(
proc.stderr, encoding=output_encoding
)
except TypeError:
# stderr is None
err = ""
except UnicodeDecodeError:
err = salt.utils.stringutils.to_unicode(
proc.stderr, encoding=output_encoding, errors="replace"
)
if output_loglevel != "quiet":
log.error(
"Failed to decode stderr from command %s, non-decodable "
"characters have been replaced",
cmd,
)
if rstrip:
if out is not None:
out = out.rstrip()
if err is not None:
err = err.rstrip()
ret["pid"] = proc.process.pid
ret["retcode"] = proc.process.returncode
if ret["retcode"] in success_retcodes:
ret["retcode"] = 0
ret["stdout"] = out
ret["stderr"] = err
else:
formatted_timeout = ""
if timeout:
formatted_timeout = " (timeout: {}s)".format(timeout)
if output_loglevel is not None:
msg = "Running {} in VT{}".format(cmd, formatted_timeout)
log.debug(log_callback(msg))
stdout, stderr = "", ""
now = time.time()
if timeout:
will_timeout = now + timeout
else:
will_timeout = -1
try:
proc = salt.utils.vt.Terminal(
cmd,
shell=True,
log_stdout=True,
log_stderr=True,
cwd=cwd,
preexec_fn=new_kwargs.get("preexec_fn", None),
env=run_env,
log_stdin_level=output_loglevel,
log_stdout_level=output_loglevel,
log_stderr_level=output_loglevel,
stream_stdout=True,
stream_stderr=True,
)
ret["pid"] = proc.pid
while proc.has_unread_data:
try:
try:
time.sleep(0.5)
try:
cstdout, cstderr = proc.recv()
except OSError:
cstdout, cstderr = "", ""
if cstdout:
stdout += cstdout
else:
stdout = ""
if cstderr:
stderr += cstderr
else:
stderr = ""
if timeout and (time.time() > will_timeout):
ret["stderr"] = ("SALT: Timeout after {}s\n{}").format(
timeout, stderr
)
ret["retcode"] = None
break
except KeyboardInterrupt:
ret["stderr"] = "SALT: User break\n{}".format(stderr)
ret["retcode"] = 1
break
except salt.utils.vt.TerminalException as exc:
log.error("VT: %s", exc, exc_info_on_loglevel=logging.DEBUG)
ret = {"retcode": 1, "pid": "2"}
break
# only set stdout on success as we already mangled in other
# cases
ret["stdout"] = stdout
if not proc.isalive():
# Process terminated, i.e., not canceled by the user or by
# the timeout
ret["stderr"] = stderr
ret["retcode"] = proc.exitstatus
if ret["retcode"] in success_retcodes:
ret["retcode"] = 0
ret["pid"] = proc.pid
finally:
proc.close(terminate=True, kill=True)
try:
if ignore_retcode:
__context__["retcode"] = 0
else:
__context__["retcode"] = ret["retcode"]
except NameError:
# Ignore the context error during grain generation
pass
# Log the output
if output_loglevel is not None:
if not ignore_retcode and ret["retcode"] != 0:
if output_loglevel < LOG_LEVELS["error"]:
output_loglevel = LOG_LEVELS["error"]
msg = "Command '{}' failed with return code: {}".format(cmd, ret["retcode"])
log.error(log_callback(msg))
if ret["stdout"]:
log.log(output_loglevel, "stdout: %s", log_callback(ret["stdout"]))
if ret["stderr"]:
log.log(output_loglevel, "stderr: %s", log_callback(ret["stderr"]))
if ret["retcode"]:
log.log(output_loglevel, "retcode: %s", ret["retcode"])
return ret
def _run_quiet(
cmd,
cwd=None,
stdin=None,
output_encoding=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv="base",
pillarenv=None,
pillar_override=None,
success_retcodes=None,
):
"""
Helper for running commands quietly for minion startup
"""
return _run(
cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
output_encoding=output_encoding,
output_loglevel="quiet",
log_callback=None,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
)["stdout"]
def _run_all_quiet(
cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
template=None,
umask=None,
timeout=None,
reset_system_locale=True,
saltenv="base",
pillarenv=None,
pillar_override=None,
output_encoding=None,
success_retcodes=None,
):
"""
Helper for running commands quietly for minion startup.
Returns a dict of return data.
output_loglevel argument is ignored. This is here for when we alias
cmd.run_all directly to _run_all_quiet in certain chicken-and-egg
situations where modules need to work both before and after
the __salt__ dictionary is populated (cf dracr.py)
"""
return _run(
cmd,
runas=runas,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
output_encoding=output_encoding,
output_loglevel="quiet",
log_callback=None,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
pillarenv=pillarenv,
pillar_override=pillar_override,
success_retcodes=success_retcodes,
)
def run(
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel="debug",
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
use_vt=False,
bg=False,
password=None,
encoded_cmd=False,
raise_err=False,
prepend_path=None,
success_retcodes=None,
**kwargs
):
r"""
Execute the passed command and return the output as a string
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
on linux while using run, to pass special characters to the
command you need to escape the characters on the shell.
Example:
.. code-block:: bash
cmd.run 'echo '\''h=\"baz\"'\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If ``False``, let python handle the positional
arguments. Set to ``True`` to use shell features, such as pipes or
redirection.
:param bool bg: If ``True``, run command in background and do not await or
deliver its results
.. versionadded:: 2016.3.0
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
:param bool raise_err: If ``True`` and the command has a nonzero exit code,
a CommandExecutionError exception will be raised.
.. warning::
This function does not process commands through a shell
unless the python_shell flag is set to True. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or
have the python_shell=True flag set here.
The use of python_shell=True means that the shell will accept _any_ input
including potentially malicious commands such as 'good_command;rm -rf /'.
Be absolutely certain that you have sanitized your input prior to using
python_shell=True
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:param int windows_codepage: 65001
Only applies to Windows: the minion uses `C:\Windows\System32\chcp.com` to
verify or set the code page before he excutes the command `cmd`.
Code page 65001 corresponds with UTF-8 and allows international localization of Windows.
.. versionadded:: 3002
CLI Example:
.. code-block:: bash
salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run cmd='sed -e s/=/:/g'
"""
python_shell = _python_shell_default(python_shell, kwargs.get("__pub_jid", ""))
ret = _run(
cmd,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
**kwargs
)
log_callback = _check_cb(log_callback)
lvl = _check_loglevel(output_loglevel)
if lvl is not None:
if not ignore_retcode and ret["retcode"] != 0:
if lvl < LOG_LEVELS["error"]:
lvl = LOG_LEVELS["error"]
msg = "Command '{}' failed with return code: {}".format(cmd, ret["retcode"])
log.error(log_callback(msg))
if raise_err:
raise CommandExecutionError(
log_callback(ret["stdout"] if not hide_output else "")
)
log.log(lvl, "output: %s", log_callback(ret["stdout"]))
return ret["stdout"] if not hide_output else ""
def shell(
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel="debug",
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
use_vt=False,
bg=False,
password=None,
prepend_path=None,
success_retcodes=None,
**kwargs
):
"""
Execute the passed command and return the output as a string.
.. versionadded:: 2015.5.0
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.shell 'echo '\\''h=\\"baz\\"'\\''' runas=macuser
:param str group: Group to run command as. Not currently supported
on Windows.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param int shell: Shell to execute under. Defaults to the system default
shell.
:param bool bg: If True, run command in background and do not await or
deliver its results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.shell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
.. warning::
This passes the cmd argument directly to the shell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.shell "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.shell template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.shell "Get-ChildItem C:\\ " shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.shell "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.shell cmd='sed -e s/=/:/g'
"""
if "python_shell" in kwargs:
python_shell = kwargs.pop("python_shell")
else:
python_shell = True
return run(
cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
bg=bg,
password=password,
success_retcodes=success_retcodes,
**kwargs
)
def run_stdout(
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel="debug",
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
**kwargs
):
"""
Execute a command, and only return the standard out
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stdout 'echo '\\''h=\\"baz\\"'\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not necessary)
to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stdout template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stdout "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
"""
python_shell = _python_shell_default(python_shell, kwargs.get("__pub_jid", ""))
ret = _run(
cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
**kwargs
)
return ret["stdout"] if not hide_output else ""
def run_stderr(
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel="debug",
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
use_vt=False,
password=None,
prepend_path=None,
success_retcodes=None,
**kwargs
):
"""
Execute a command and only return the standard error
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_stderr 'echo '\\''h=\\"baz\\"'\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_stderr 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_stderr "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_stderr template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_stderr "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
"""
python_shell = _python_shell_default(python_shell, kwargs.get("__pub_jid", ""))
ret = _run(
cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
**kwargs
)
return ret["stderr"] if not hide_output else ""
def run_all(
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel="debug",
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
use_vt=False,
redirect_stderr=False,
password=None,
encoded_cmd=False,
prepend_path=None,
success_retcodes=None,
**kwargs
):
"""
Execute the passed command and return a dict of return data
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_all 'echo '\\''h=\\"baz\\"'\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool encoded_cmd: Specify if the supplied command is encoded.
Only applies to shell 'powershell'.
.. versionadded:: 2018.3.0
:param bool redirect_stderr: If set to ``True``, then stderr will be
redirected to stdout. This is helpful for cases where obtaining both
the retcode and output is desired, but it is not desired to have the
output separated into both stdout and stderr.
.. versionadded:: 2015.8.2
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param bool bg: If ``True``, run command in background and do not await or
deliver its results
.. versionadded:: 2016.3.6
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_all "ls -l | awk '/foo/{print \\$2}'"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_all template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.run_all "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
"""
python_shell = _python_shell_default(python_shell, kwargs.get("__pub_jid", ""))
stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE
ret = _run(
cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=stderr,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
**kwargs
)
if hide_output:
ret["stdout"] = ret["stderr"] = ""
return ret
def retcode(
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
output_loglevel="debug",
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
use_vt=False,
password=None,
success_retcodes=None,
**kwargs
):
"""
Execute a shell command and return the command's return code.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.retcode 'echo '\\''h=\\"baz\\"'\\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.retcode 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:rtype: int
:rtype: None
:returns: Return Code as an int or None if there was an exception.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.retcode "file /bin/bash"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.retcode template=jinja "file {{grains.pythonpath[0]}}/python"
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.retcode "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
"""
python_shell = _python_shell_default(python_shell, kwargs.get("__pub_jid", ""))
ret = _run(
cmd,
runas=runas,
group=group,
cwd=cwd,
stdin=stdin,
stderr=subprocess.STDOUT,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
**kwargs
)
return ret["retcode"]
def _retcode_quiet(
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=False,
env=None,
clean_env=False,
template=None,
umask=None,
output_encoding=None,
log_callback=None,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
use_vt=False,
password=None,
success_retcodes=None,
**kwargs
):
"""
Helper for running commands quietly for minion startup. Returns same as
the retcode() function.
"""
return retcode(
cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
umask=umask,
output_encoding=output_encoding,
output_loglevel="quiet",
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
**kwargs
)
def script(
source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template=None,
umask=None,
output_encoding=None,
output_loglevel="debug",
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
saltenv="base",
use_vt=False,
bg=False,
password=None,
success_retcodes=None,
**kwargs
):
"""
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
.. code-block:: bash
salt myminion cmd.script salt://foo.sh "arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. note::
For Window's users, specifically Server users, it may be necessary
to specify your runas user using the User Logon Name instead of the
legacy logon name. Traditionally, logons would be in the following
format.
``Domain/user``
In the event this causes issues when executing scripts, use the UPN
format which looks like the following.
``[email protected]``
More information <https://github.com/saltstack/salt/issues/55080>
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param bool bg: If True, run script in background and do not await or
deliver its results
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh
salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
.. code-block:: bash
salt '*' cmd.script salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
"""
python_shell = _python_shell_default(python_shell, kwargs.get("__pub_jid", ""))
def _cleanup_tempfile(path):
try:
__salt__["file.remove"](path)
except (SaltInvocationError, CommandExecutionError) as exc:
log.error(
"cmd.script: Unable to clean tempfile '%s': %s",
path,
exc,
exc_info_on_loglevel=logging.DEBUG,
)
if "__env__" in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop("__env__")
win_cwd = False
if salt.utils.platform.is_windows() and runas and cwd is None:
# Create a temp working directory
cwd = tempfile.mkdtemp(dir=__opts__["cachedir"])
win_cwd = True
salt.utils.win_dacl.set_permissions(
obj_name=cwd, principal=runas, permissions="full_control"
)
path = salt.utils.files.mkstemp(dir=cwd, suffix=os.path.splitext(source)[1])
if template:
if "pillarenv" in kwargs or "pillar" in kwargs:
pillarenv = kwargs.get("pillarenv", __opts__.get("pillarenv"))
kwargs["pillar"] = _gather_pillar(pillarenv, kwargs.get("pillar"))
fn_ = __salt__["cp.get_template"](source, path, template, saltenv, **kwargs)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {
"pid": 0,
"retcode": 1,
"stdout": "",
"stderr": "",
"cache_error": True,
}
else:
fn_ = __salt__["cp.cache_file"](source, saltenv)
if not fn_:
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
return {
"pid": 0,
"retcode": 1,
"stdout": "",
"stderr": "",
"cache_error": True,
}
shutil.copyfile(fn_, path)
if not salt.utils.platform.is_windows():
os.chmod(path, 320)
os.chown(path, __salt__["file.user_to_uid"](runas), -1)
if salt.utils.platform.is_windows() and shell.lower() != "powershell":
cmd_path = _cmd_quote(path, escape=False)
else:
cmd_path = _cmd_quote(path)
ret = _run(
cmd_path + " " + str(args) if args else cmd_path,
cwd=cwd,
stdin=stdin,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
use_vt=use_vt,
bg=bg,
password=password,
success_retcodes=success_retcodes,
**kwargs
)
_cleanup_tempfile(path)
# If a temp working directory was created (Windows), let's remove that
if win_cwd:
_cleanup_tempfile(cwd)
if hide_output:
ret["stdout"] = ret["stderr"] = ""
return ret
def script_retcode(
source,
args=None,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
template="jinja",
umask=None,
timeout=None,
reset_system_locale=True,
saltenv="base",
output_encoding=None,
output_loglevel="debug",
log_callback=None,
use_vt=False,
password=None,
success_retcodes=None,
**kwargs
):
"""
Download a script from a remote location and execute the script locally.
The script can be located on the salt master file server or on an HTTP/FTP
server.
The script will be executed directly, so it can be written in any available
programming language.
The script can also be formatted as a template, the default is jinja.
Only evaluate the script return code and do not block for terminal output
:param str source: The location of the script to download. If the file is
located on the master in the directory named spam, and is called eggs,
the source string is salt://spam/eggs
:param str args: String of command line args to pass to the script. Only
used if no args are specified as part of the `name` argument. To pass a
string containing spaces in YAML, you will need to doubly-quote it:
"arg1 'arg two' arg3"
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str group: Group to run script as. Not currently supported
on Windows.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.script_retcode 'some command' env='{"FOO": "bar"}'
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: If the command has not terminated after timeout
seconds, send the subprocess sigterm, and if sigterm is ignored, follow
up with sigkill
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh
salt '*' cmd.script_retcode salt://scripts/runme.sh 'arg1 arg2 "arg 3"'
salt '*' cmd.script_retcode salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell'
A string of standard input can be specified for the command to be run using
the ``stdin`` parameter. This can be useful in cases where sensitive
information must be read from standard input.
.. code-block:: bash
salt '*' cmd.script_retcode salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n'
"""
if "__env__" in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop("__env__")
return script(
source=source,
args=args,
cwd=cwd,
stdin=stdin,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
env=env,
template=template,
umask=umask,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
use_vt=use_vt,
password=password,
success_retcodes=success_retcodes,
**kwargs
)["retcode"]
def which(cmd):
"""
Returns the path of an executable available on the minion, None otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.which cat
"""
return salt.utils.path.which(cmd)
def which_bin(cmds):
"""
Returns the first command found in a list of commands
CLI Example:
.. code-block:: bash
salt '*' cmd.which_bin '[pip2, pip, pip-python]'
"""
return salt.utils.path.which_bin(cmds)
def has_exec(cmd):
"""
Returns true if the executable is available on the minion, false otherwise
CLI Example:
.. code-block:: bash
salt '*' cmd.has_exec cat
"""
return which(cmd) is not None
def exec_code(lang, code, cwd=None, args=None, **kwargs):
"""
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. The stdout will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code ruby 'puts "cheese"'
salt '*' cmd.exec_code ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
"""
return exec_code_all(lang, code, cwd, args, **kwargs)["stdout"]
def exec_code_all(lang, code, cwd=None, args=None, **kwargs):
"""
Pass in two strings, the first naming the executable language, aka -
python2, python3, ruby, perl, lua, etc. the second string containing
the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid)
will be returned.
All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used.
CLI Example:
.. code-block:: bash
salt '*' cmd.exec_code_all ruby 'puts "cheese"'
salt '*' cmd.exec_code_all ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}'
"""
powershell = lang.lower().startswith("powershell")
if powershell:
codefile = salt.utils.files.mkstemp(suffix=".ps1")
else:
codefile = salt.utils.files.mkstemp()
with salt.utils.files.fopen(codefile, "w+t", binary=False) as fp_:
fp_.write(salt.utils.stringutils.to_str(code))
if powershell:
cmd = [lang, "-File", codefile]
else:
cmd = [lang, codefile]
if isinstance(args, str):
cmd.append(args)
elif isinstance(args, list):
cmd += args
ret = run_all(cmd, cwd=cwd, python_shell=False, **kwargs)
os.remove(codefile)
return ret
def tty(device, echo=""):
"""
Echo a string to a specific tty
CLI Example:
.. code-block:: bash
salt '*' cmd.tty tty0 'This is a test'
salt '*' cmd.tty pts3 'This is a test'
"""
if device.startswith("tty"):
teletype = "/dev/{}".format(device)
elif device.startswith("pts"):
teletype = "/dev/{}".format(device.replace("pts", "pts/"))
else:
return {"Error": "The specified device is not a valid TTY"}
try:
with salt.utils.files.fopen(teletype, "wb") as tty_device:
tty_device.write(salt.utils.stringutils.to_bytes(echo))
return {"Success": "Message was successfully echoed to {}".format(teletype)}
except OSError:
return {"Error": "Echoing to {} returned error".format(teletype)}
def run_chroot(
root,
cmd,
cwd=None,
stdin=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=True,
binds=None,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel="quiet",
log_callback=None,
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
use_vt=False,
bg=False,
success_retcodes=None,
**kwargs
):
"""
.. versionadded:: 2014.7.0
This function runs :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` wrapped
within a chroot, with dev and proc mounted in the chroot
:param str root: Path to the root of the jail to use.
:param str stdin: A string of standard input can be specified for
the command to be run using the ``stdin`` parameter. This can
be useful in cases where sensitive information must be read
from standard input.:
:param str runas: User to run script as.
:param str group: Group to run script as.
:param str shell: Shell to execute under. Defaults to the system
default shell.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:parar str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param list binds: List of directories that will be exported inside
the chroot with the bind option.
.. versionadded:: 3000
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_chroot 'some command' env='{"FOO": "bar"}'
:param dict clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output
before it is returned.
:param str umask: The umask (in octal) to use when running the
command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout:
A timeout in seconds for the executed process to return.
:param bool use_vt:
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs. This is experimental.
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_chroot /var/lib/lxc/container_name/rootfs 'sh /tmp/bootstrap.sh'
"""
__salt__["mount.mount"](os.path.join(root, "dev"), "devtmpfs", fstype="devtmpfs")
__salt__["mount.mount"](os.path.join(root, "proc"), "proc", fstype="proc")
__salt__["mount.mount"](os.path.join(root, "sys"), "sysfs", fstype="sysfs")
binds = binds if binds else []
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__["mount.mount"](bind_exported_to, bind_exported, opts="default,bind")
# Execute chroot routine
sh_ = "/bin/sh"
if os.path.isfile(os.path.join(root, "bin/bash")):
sh_ = "/bin/bash"
if isinstance(cmd, (list, tuple)):
cmd = " ".join([str(i) for i in cmd])
# If runas and group are provided, we expect that the user lives
# inside the chroot, not outside.
if runas:
userspec = "--userspec {}:{}".format(runas, group if group else "")
else:
userspec = ""
cmd = "chroot {} {} {} -c {}".format(userspec, root, sh_, _cmd_quote(cmd))
run_func = __context__.pop("cmd.run_chroot.func", run_all)
ret = run_func(
cmd,
cwd=cwd,
stdin=stdin,
shell=shell,
python_shell=python_shell,
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
pillarenv=kwargs.get("pillarenv"),
pillar=kwargs.get("pillar"),
use_vt=use_vt,
success_retcodes=success_retcodes,
bg=bg,
)
# Kill processes running in the chroot
for i in range(6):
pids = _chroot_pids(root)
if not pids:
break
for pid in pids:
# use sig 15 (TERM) for first 3 attempts, then 9 (KILL)
sig = 15 if i < 3 else 9
os.kill(pid, sig)
if _chroot_pids(root):
log.error(
"Processes running in chroot could not be killed, "
"filesystem will remain mounted"
)
for bind_exported in binds:
bind_exported_to = os.path.relpath(bind_exported, os.path.sep)
bind_exported_to = os.path.join(root, bind_exported_to)
__salt__["mount.umount"](bind_exported_to)
__salt__["mount.umount"](os.path.join(root, "sys"))
__salt__["mount.umount"](os.path.join(root, "proc"))
__salt__["mount.umount"](os.path.join(root, "dev"))
if hide_output:
ret["stdout"] = ret["stderr"] = ""
return ret
def _is_valid_shell(shell):
"""
Attempts to search for valid shells on a system and
see if a given shell is in the list
"""
if salt.utils.platform.is_windows():
return True # Don't even try this for Windows
shells = "/etc/shells"
available_shells = []
if os.path.exists(shells):
try:
with salt.utils.files.fopen(shells, "r") as shell_fp:
lines = [
salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()
]
for line in lines:
if line.startswith("#"):
continue
else:
available_shells.append(line)
except OSError:
return True
else:
# No known method of determining available shells
return None
if shell in available_shells:
return True
else:
return False
def shells():
"""
Lists the valid shells on this system via the /etc/shells file
.. versionadded:: 2015.5.0
CLI Example::
salt '*' cmd.shells
"""
shells_fn = "/etc/shells"
ret = []
if os.path.exists(shells_fn):
try:
with salt.utils.files.fopen(shells_fn, "r") as shell_fp:
lines = [
salt.utils.stringutils.to_unicode(x)
for x in shell_fp.read().splitlines()
]
for line in lines:
line = line.strip()
if line.startswith("#"):
continue
elif not line:
continue
else:
ret.append(line)
except OSError:
log.error("File '%s' was not found", shells_fn)
return ret
def shell_info(shell, list_modules=False):
"""
.. versionadded:: 2016.11.0
Provides information about a shell or script languages which often use
``#!``. The values returned are dependent on the shell or scripting
languages all return the ``installed``, ``path``, ``version``,
``version_raw``
Args:
shell (str): Name of the shell. Support shells/script languages include
bash, cmd, perl, php, powershell, python, ruby and zsh
list_modules (bool): True to list modules available to the shell.
Currently only lists powershell modules.
Returns:
dict: A dictionary of information about the shell
.. code-block:: python
{'version': '<2 or 3 numeric components dot-separated>',
'version_raw': '<full version string>',
'path': '<full path to binary>',
'installed': <True, False or None>,
'<attribute>': '<attribute value>'}
.. note::
- ``installed`` is always returned, if ``None`` or ``False`` also
returns error and may also return ``stdout`` for diagnostics.
- ``version`` is for use in determine if a shell/script language has a
particular feature set, not for package management.
- The shell must be within the executable search path.
CLI Example:
.. code-block:: bash
salt '*' cmd.shell_info bash
salt '*' cmd.shell_info powershell
:codeauthor: Damon Atkins <https://github.com/damon-atkins>
"""
regex_shells = {
"bash": [r"version (\d\S*)", "bash", "--version"],
"bash-test-error": [
r"versioZ ([-\w.]+)",
"bash",
"--version",
], # used to test an error result
"bash-test-env": [
r"(HOME=.*)",
"bash",
"-c",
"declare",
], # used to test an error result
"zsh": [r"^zsh (\d\S*)", "zsh", "--version"],
"tcsh": [r"^tcsh (\d\S*)", "tcsh", "--version"],
"cmd": [r"Version ([\d.]+)", "cmd.exe", "/C", "ver"],
"powershell": [
r"PSVersion\s+(\d\S*)",
"powershell",
"-NonInteractive",
"$PSVersionTable",
],
"perl": [r"^(\d\S*)", "perl", "-e", 'printf "%vd\n", $^V;'],
"python": [r"^Python (\d\S*)", "python", "-V"],
"ruby": [r"^ruby (\d\S*)", "ruby", "-v"],
"php": [r"^PHP (\d\S*)", "php", "-v"],
}
# Ensure ret['installed'] always as a value of True, False or None (not sure)
ret = {"installed": False}
if salt.utils.platform.is_windows() and shell == "powershell":
pw_keys = salt.utils.win_reg.list_keys(
hive="HKEY_LOCAL_MACHINE", key="Software\\Microsoft\\PowerShell"
)
pw_keys.sort(key=int)
if not pw_keys:
return {
"error": "Unable to locate 'powershell' Reason: Cannot be "
"found in registry.",
"installed": False,
}
for reg_ver in pw_keys:
install_data = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="Software\\Microsoft\\PowerShell\\{}".format(reg_ver),
vname="Install",
)
if (
install_data.get("vtype") == "REG_DWORD"
and install_data.get("vdata") == 1
):
details = salt.utils.win_reg.list_values(
hive="HKEY_LOCAL_MACHINE",
key="Software\\Microsoft\\PowerShell\\{}\\"
"PowerShellEngine".format(reg_ver),
)
# reset data, want the newest version details only as powershell
# is backwards compatible
ret = {}
# if all goes well this will become True
ret["installed"] = None
ret["path"] = which("powershell.exe")
for attribute in details:
if attribute["vname"].lower() == "(default)":
continue
elif attribute["vname"].lower() == "powershellversion":
ret["psversion"] = attribute["vdata"]
ret["version_raw"] = attribute["vdata"]
elif attribute["vname"].lower() == "runtimeversion":
ret["crlversion"] = attribute["vdata"]
if ret["crlversion"][0].lower() == "v":
ret["crlversion"] = ret["crlversion"][1::]
elif attribute["vname"].lower() == "pscompatibleversion":
# reg attribute does not end in s, the powershell
# attribute does
ret["pscompatibleversions"] = (
attribute["vdata"].replace(" ", "").split(",")
)
else:
# keys are lower case as python is case sensitive the
# registry is not
ret[attribute["vname"].lower()] = attribute["vdata"]
else:
if shell not in regex_shells:
return {
"error": "Salt does not know how to get the version number for "
"{}".format(shell),
"installed": None,
}
shell_data = regex_shells[shell]
pattern = shell_data.pop(0)
# We need to make sure HOME set, so shells work correctly
# salt-call will general have home set, the salt-minion service may not
# We need to assume ports of unix shells to windows will look after
# themselves in setting HOME as they do it in many different ways
if salt.utils.platform.is_windows():
import nt
newenv = nt.environ
else:
newenv = os.environ
if ("HOME" not in newenv) and (not salt.utils.platform.is_windows()):
newenv["HOME"] = os.path.expanduser("~")
log.debug("HOME environment set to %s", newenv["HOME"])
try:
proc = salt.utils.timed_subprocess.TimedProc(
shell_data,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=10,
env=newenv,
)
except OSError as exc:
return {
"error": "Unable to run command '{}' Reason: {}".format(
" ".join(shell_data), exc
),
"installed": False,
}
try:
proc.run()
except TimedProcTimeoutError as exc:
return {
"error": "Unable to run command '{}' Reason: Timed out.".format(
" ".join(shell_data)
),
"installed": False,
}
ret["path"] = which(shell_data[0])
pattern_result = re.search(pattern, proc.stdout, flags=re.IGNORECASE)
# only set version if we find it, so code later on can deal with it
if pattern_result:
ret["version_raw"] = pattern_result.group(1)
if "version_raw" in ret:
version_results = re.match(r"(\d[\d.]*)", ret["version_raw"])
if version_results:
ret["installed"] = True
ver_list = version_results.group(1).split(".")[:3]
if len(ver_list) == 1:
ver_list.append("0")
ret["version"] = ".".join(ver_list[:3])
else:
ret["installed"] = None # Have an unexpected result
# Get a list of the PowerShell modules which are potentially available
# to be imported
if shell == "powershell" and ret["installed"] and list_modules:
ret["modules"] = salt.utils.powershell.get_modules()
if "version" not in ret:
ret["error"] = (
"The version regex pattern for shell {}, could not "
"find the version string".format(shell)
)
ret["stdout"] = proc.stdout # include stdout so they can see the issue
log.error(ret["error"])
return ret
def powershell(
cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel="debug",
hide_output=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
success_retcodes=None,
**kwargs
):
"""
Execute the passed PowerShell command and return the output as a dictionary.
Other ``cmd.*`` functions (besides ``cmd.powershell_all``)
return the raw text output of the command. This
function appends ``| ConvertTo-JSON`` to the command and then parses the
JSON into a Python dictionary. If you want the raw textual result of your
PowerShell command you should use ``cmd.run`` with the ``shell=powershell``
option.
For example:
.. code-block:: bash
salt '*' cmd.run '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2016.3.0
.. warning::
This passes the cmd argument directly to PowerShell
without any further processing! Be absolutely sure that you
have properly sanitized the command passed to this function
and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in cases
where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param bool hide_output: If ``True``, suppress stdout and stderr in the
return data.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
:param int timeout: A timeout in seconds for the executed process to return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
.. versionadded:: 2016.3.4
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:returns:
:dict: A dictionary of data returned by the powershell command.
CLI Example:
.. code-block:: powershell
salt '*' cmd.powershell "$PSVersionTable.CLRVersion"
"""
if "python_shell" in kwargs:
python_shell = kwargs.pop("python_shell")
else:
python_shell = True
# Append PowerShell Object formatting
# ConvertTo-JSON is only available on PowerShell 3.0 and later
psversion = shell_info("powershell")["psversion"]
if salt.utils.versions.version_cmp(psversion, "2.0") == 1:
cmd += " | ConvertTo-JSON"
if depth is not None:
cmd += " -Depth {}".format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug("Encoding PowerShell command '%s'", cmd)
cmd_utf16 = cmd.decode("utf-8").encode("utf-16le")
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Put the whole command inside a try / catch block
# Some errors in PowerShell are not "Terminating Errors" and will not be
# caught in a try/catch block. For example, the `Get-WmiObject` command will
# often return a "Non Terminating Error". To fix this, make sure
# `-ErrorAction Stop` is set in the powershell command
cmd = "try {" + cmd + '} catch { "{}" }'
# Retrieve the response, while overriding shell with 'powershell'
response = run(
cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell="powershell",
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
hide_output=hide_output,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
**kwargs
)
# Sometimes Powershell returns an empty string, which isn't valid JSON
if response == "":
response = "{}"
try:
return salt.utils.json.loads(response)
except Exception: # pylint: disable=broad-except
log.error("Error converting PowerShell JSON return", exc_info=True)
return {}
def powershell_all(
cmd,
cwd=None,
stdin=None,
runas=None,
shell=DEFAULT_SHELL,
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel="debug",
quiet=False,
timeout=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
use_vt=False,
password=None,
depth=None,
encode_cmd=False,
force_list=False,
success_retcodes=None,
**kwargs
):
"""
Execute the passed PowerShell command and return a dictionary with a result
field representing the output of the command, as well as other fields
showing us what the PowerShell invocation wrote to ``stderr``, the process
id, and the exit code of the invocation.
This function appends ``| ConvertTo-JSON`` to the command before actually
invoking powershell.
An unquoted empty string is not valid JSON, but it's very normal for the
Powershell output to be exactly that. Therefore, we do not attempt to parse
empty Powershell output (which would result in an exception). Instead we
treat this as a special case and one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field of the return dictionary will be an empty list.
- If the value of the ``force_list`` parameter is ``False``, then the
return dictionary **will not have a result key added to it**. We aren't
setting ``result`` to ``None`` in this case, because ``None`` is the
Python representation of "null" in JSON. (We likewise can't use ``False``
for the equivalent reason.)
If Powershell's output is not an empty string and Python cannot parse its
content, then a ``CommandExecutionError`` exception will be raised.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is other than ``list``
then one of two things will happen:
- If the value of the ``force_list`` parameter is ``True``, then the
``result`` field will be a singleton list with the Python object as its
sole member.
- If the value of the ``force_list`` parameter is ``False``, then the value
of ``result`` will be the unmodified Python object.
If Powershell's output is not an empty string, Python is able to parse its
content, and the type of the resulting Python object is ``list``, then the
value of ``result`` will be the unmodified Python object. The
``force_list`` parameter has no effect in this case.
.. note::
An example of why the ``force_list`` parameter is useful is as
follows: The Powershell command ``dir x | Convert-ToJson`` results in
- no output when x is an empty directory.
- a dictionary object when x contains just one item.
- a list of dictionary objects when x contains multiple items.
By setting ``force_list`` to ``True`` we will always end up with a
list of dictionary items, representing files, no matter how many files
x contains. Conversely, if ``force_list`` is ``False``, we will end
up with no ``result`` key in our return dictionary when x is an empty
directory, and a dictionary object when x contains just one file.
If you want a similar function but with a raw textual result instead of a
Python dictionary, you should use ``cmd.run_all`` in combination with
``shell=powershell``.
The remaining fields in the return dictionary are described in more detail
in the ``Returns`` section.
Example:
.. code-block:: bash
salt '*' cmd.run_all '$PSVersionTable.CLRVersion' shell=powershell
salt '*' cmd.run_all 'Get-NetTCPConnection' shell=powershell
.. versionadded:: 2018.3.0
.. warning::
This passes the cmd argument directly to PowerShell without any further
processing! Be absolutely sure that you have properly sanitized the
command passed to this function and do not use untrusted inputs.
In addition to the normal ``cmd.run`` parameters, this command offers the
``depth`` parameter to change the Windows default depth for the
``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need
more depth, set that here.
.. note::
For some commands, setting the depth to a value greater than 4 greatly
increases the time it takes for the command to return and in many cases
returns useless data.
:param str cmd: The powershell command to run.
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str stdin: A string of standard input can be specified for the
command to be run using the ``stdin`` parameter. This can be useful in
cases where sensitive information must be read from standard input.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.powershell_all 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param bool rstrip: Strip all whitespace off the end of output before it is
returned.
:param str umask: The umask (in octal) to use when running the command.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param int timeout: A timeout in seconds for the executed process to
return.
:param bool use_vt: Use VT utils (saltstack) to stream the command output
more interactively to the console and the logs. This is experimental.
:param bool reset_system_locale: Resets the system locale
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str saltenv: The salt environment to use. Default is 'base'
:param int depth: The number of levels of contained objects to be included.
Default is 2. Values greater than 4 seem to greatly increase the time
it takes for the command to complete for some commands. eg: ``dir``
:param bool encode_cmd: Encode the command before executing. Use in cases
where characters may be dropped or incorrectly converted when executed.
Default is False.
:param bool force_list: The purpose of this parameter is described in the
preamble of this function's documentation. Default value is False.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
:return: A dictionary with the following entries:
result
For a complete description of this field, please refer to this
function's preamble. **This key will not be added to the dictionary
when force_list is False and Powershell's output is the empty
string.**
stderr
What the PowerShell invocation wrote to ``stderr``.
pid
The process id of the PowerShell invocation
retcode
This is the exit code of the invocation of PowerShell.
If the final execution status (in PowerShell) of our command
(with ``| ConvertTo-JSON`` appended) is ``False`` this should be non-0.
Likewise if PowerShell exited with ``$LASTEXITCODE`` set to some
non-0 value, then ``retcode`` will end up with this value.
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "$PSVersionTable.CLRVersion"
CLI Example:
.. code-block:: bash
salt '*' cmd.powershell_all "dir mydirectory" force_list=True
"""
if "python_shell" in kwargs:
python_shell = kwargs.pop("python_shell")
else:
python_shell = True
# Append PowerShell Object formatting
cmd += " | ConvertTo-JSON"
if depth is not None:
cmd += " -Depth {}".format(depth)
if encode_cmd:
# Convert the cmd to UTF-16LE without a BOM and base64 encode.
# Just base64 encoding UTF-8 or including a BOM is not valid.
log.debug("Encoding PowerShell command '%s'", cmd)
cmd_utf16 = cmd.decode("utf-8").encode("utf-16le")
cmd = base64.standard_b64encode(cmd_utf16)
encoded_cmd = True
else:
encoded_cmd = False
# Retrieve the response, while overriding shell with 'powershell'
response = run_all(
cmd,
cwd=cwd,
stdin=stdin,
runas=runas,
shell="powershell",
env=env,
clean_env=clean_env,
template=template,
rstrip=rstrip,
umask=umask,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
quiet=quiet,
timeout=timeout,
reset_system_locale=reset_system_locale,
ignore_retcode=ignore_retcode,
saltenv=saltenv,
use_vt=use_vt,
python_shell=python_shell,
password=password,
encoded_cmd=encoded_cmd,
success_retcodes=success_retcodes,
**kwargs
)
stdoutput = response["stdout"]
# if stdoutput is the empty string and force_list is True we return an empty list
# Otherwise we return response with no result key
if not stdoutput:
response.pop("stdout")
if force_list:
response["result"] = []
return response
# If we fail to parse stdoutput we will raise an exception
try:
result = salt.utils.json.loads(stdoutput)
except Exception: # pylint: disable=broad-except
err_msg = "cmd.powershell_all " + "cannot parse the Powershell output."
response["cmd"] = cmd
raise CommandExecutionError(message=err_msg, info=response)
response.pop("stdout")
if type(result) is not list:
if force_list:
response["result"] = [result]
else:
response["result"] = result
else:
# result type is list so the force_list param has no effect
response["result"] = result
return response
def run_bg(
cmd,
cwd=None,
runas=None,
group=None,
shell=DEFAULT_SHELL,
python_shell=None,
env=None,
clean_env=False,
template=None,
umask=None,
timeout=None,
output_encoding=None,
output_loglevel="debug",
log_callback=None,
reset_system_locale=True,
ignore_retcode=False,
saltenv="base",
password=None,
prepend_path=None,
success_retcodes=None,
**kwargs
):
r"""
.. versionadded: 2016.3.0
Execute the passed command in the background and return its PID
.. note::
If the init system is systemd and the backgrounded task should run even
if the salt-minion process is restarted, prepend ``systemd-run
--scope`` to the command. This will reparent the process in its own
scope separate from salt-minion, and will not be affected by restarting
the minion service.
:param str cmd: The command to run. ex: ``ls -lart /home``
:param str cwd: The directory from which to execute the command. Defaults
to the home directory of the user specified by ``runas`` (or the user
under which Salt is running if ``runas`` is not specified).
:param str group: Group to run command as. Not currently supported
on Windows.
:param str shell: Shell to execute under. Defaults to the system default
shell.
:param str output_encoding: Control the encoding used to decode the
command's output.
.. note::
This should not need to be used in most cases. By default, Salt
will try to use the encoding detected from the system locale, and
will fall back to UTF-8 if this fails. This should only need to be
used in cases where the output of the command is encoded in
something other than the system locale or UTF-8.
To see the encoding Salt has detected from the system locale, check
the `locale` line in the output of :py:func:`test.versions_report
<salt.modules.test.versions_report>`.
.. versionadded:: 2018.3.0
:param str output_loglevel: Control the loglevel at which the output from
the command is logged to the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
:param bool ignore_retcode: If the exit code of the command is nonzero,
this is treated as an error condition, and the output from the command
will be logged to the minion log. However, there are some cases where
programs use the return code for signaling and a nonzero exit code
doesn't necessarily mean failure. Pass this argument as ``True`` to
skip logging the output if the command has a nonzero exit code.
:param str runas: Specify an alternate user to run the command. The default
behavior is to run as the user under which Salt is running. If running
on a Windows minion you must also use the ``password`` argument, and
the target user account must be in the Administrators group.
.. warning::
For versions 2018.3.3 and above on macosx while using runas,
to pass special characters to the command you need to escape
the characters on the shell.
Example:
.. code-block:: bash
cmd.run_bg 'echo '\''h=\"baz\"'\''' runas=macuser
:param str password: Windows only. Required when specifying ``runas``. This
parameter will be ignored on non-Windows platforms.
.. versionadded:: 2016.3.0
:param str shell: Specify an alternate shell. Defaults to the system's
default shell.
:param bool python_shell: If False, let python handle the positional
arguments. Set to True to use shell features, such as pipes or
redirection.
:param dict env: Environment variables to be set prior to execution.
.. note::
When passing environment variables on the CLI, they should be
passed as the string representation of a dictionary.
.. code-block:: bash
salt myminion cmd.run_bg 'some command' env='{"FOO": "bar"}'
:param bool clean_env: Attempt to clean out all other shell environment
variables and set only those provided in the 'env' argument to this
function.
:param str prepend_path: $PATH segment to prepend (trailing ':' not
necessary) to $PATH
.. versionadded:: 2018.3.0
:param str template: If this setting is applied then the named templating
engine will be used to render the downloaded file. Currently jinja,
mako, and wempy are supported.
:param str umask: The umask (in octal) to use when running the command.
:param int timeout: A timeout in seconds for the executed process to return.
.. warning::
This function does not process commands through a shell unless the
``python_shell`` argument is set to ``True``. This means that any
shell-specific functionality such as 'echo' or the use of pipes,
redirection or &&, should either be migrated to cmd.shell or have the
python_shell=True flag set here.
The use of ``python_shell=True`` means that the shell will accept _any_
input including potentially malicious commands such as 'good_command;rm
-rf /'. Be absolutely certain that you have sanitized your input prior
to using ``python_shell=True``.
:param list success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
:param bool stdin_raw_newlines: False
If ``True``, Salt will not automatically convert the characters ``\\n``
present in the ``stdin`` value to newlines.
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' cmd.run_bg "fstrim-all"
The template arg can be set to 'jinja' or another supported template
engine to render the command arguments before execution.
For example:
.. code-block:: bash
salt '*' cmd.run_bg template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'"
Specify an alternate shell with the shell parameter:
.. code-block:: bash
salt '*' cmd.run_bg "Get-ChildItem C:\\ " shell='powershell'
If an equal sign (``=``) appears in an argument to a Salt command it is
interpreted as a keyword argument in the format ``key=val``. That
processing can be bypassed in order to pass an equal sign through to the
remote shell command by manually specifying the kwarg:
.. code-block:: bash
salt '*' cmd.run_bg cmd='ls -lR / | sed -e s/=/:/g > /tmp/dontwait'
"""
python_shell = _python_shell_default(python_shell, kwargs.get("__pub_jid", ""))
res = _run(
cmd,
stdin=None,
stderr=None,
stdout=None,
output_encoding=output_encoding,
output_loglevel=output_loglevel,
use_vt=None,
bg=True,
with_communicate=False,
rstrip=False,
runas=runas,
group=group,
shell=shell,
python_shell=python_shell,
cwd=cwd,
env=env,
clean_env=clean_env,
prepend_path=prepend_path,
template=template,
umask=umask,
log_callback=log_callback,
timeout=timeout,
reset_system_locale=reset_system_locale,
saltenv=saltenv,
password=password,
success_retcodes=success_retcodes,
**kwargs
)
return {"pid": res["pid"]}
| []
| []
| []
| [] | [] | python | 0 | 0 | |
proyectointegrador1/wsgi.py | """
WSGI config for proyectointegrador1 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proyectointegrador1.settings')
application = get_wsgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
pkg/kube/kube.go | package kube
import (
"encoding/json"
"os"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
// GetClient returns a k8s clientset to the request from inside of cluster
func GetClient() kubernetes.Interface {
config, err := rest.InClusterConfig()
if err != nil {
logrus.Fatalf("Can not get kubernetes config: %v", err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
logrus.Fatalf("Can not create kubernetes client: %v", err)
}
return clientset
}
// GetClientOutOfCluster returns a k8s clientset to the request from outside of cluster
func GetClientOutOfCluster() kubernetes.Interface {
config, err := buildOutOfClusterConfig()
if err != nil {
logrus.Fatalf("Can not get kubernetes config: %v", err)
}
clientset, err := kubernetes.NewForConfig(config)
return clientset
}
func buildOutOfClusterConfig() (*rest.Config, error) {
kubeconfigPath := os.Getenv("KUBECONFIG")
if kubeconfigPath == "" {
kubeconfigPath = os.Getenv("HOME") + "/.kube/config"
}
return clientcmd.BuildConfigFromFlags("", kubeconfigPath)
}
// IsOpenShift returns true if cluster is openshift based
func IsOpenShift(c *kubernetes.Clientset) bool {
res, err := c.RESTClient().Get().AbsPath("").DoRaw()
if err != nil {
return false
}
var rp v1.RootPaths
err = json.Unmarshal(res, &rp)
if err != nil {
return false
}
for _, p := range rp.Paths {
if p == "/oapi" {
return true
}
}
return false
}
| [
"\"KUBECONFIG\"",
"\"HOME\""
]
| []
| [
"HOME",
"KUBECONFIG"
]
| [] | ["HOME", "KUBECONFIG"] | go | 2 | 0 | |
hourglass/settings_utils.py | import os
import sys
import json
from typing import List, Optional
Environ = os._Environ
def load_cups_from_vcap_services(name: str='calc-env',
env: Environ=os.environ) -> None:
'''
Detects if VCAP_SERVICES exists in the environment; if so, parses
it and imports all the credentials from the given custom
user-provided service (CUPS) as strings into the environment.
For more details on CUPS, see:
https://docs.cloudfoundry.org/devguide/services/user-provided.html
'''
if 'VCAP_SERVICES' not in env:
return
vcap = json.loads(env['VCAP_SERVICES'])
for entry in vcap.get('user-provided', []):
if entry['name'] == name:
for key, value in entry['credentials'].items():
env[key] = value
def get_whitelisted_ips(env: Environ=os.environ) -> Optional[List[str]]:
'''
Detects if WHITELISTED_IPS is in the environment; if not,
returns None. if so, parses WHITELISTED_IPS as a comma-separated
string and returns a list of values.
'''
if 'WHITELISTED_IPS' not in env:
return None
return [s.strip() for s in env['WHITELISTED_IPS'].split(',')]
def load_redis_url_from_vcap_services(name: str,
env: Environ=os.environ) -> None:
'''
Detects if a redis28 service instance with the given name
is present in VCAP_SERVICES.
If it is, then it creates a URL for the instance and sets env['REDIS_URL']
to that URL. If not, it just returns and does nothing.
'''
if 'VCAP_SERVICES' not in env:
return
vcap = json.loads(env['VCAP_SERVICES'])
for entry in vcap.get('redis28', []):
if entry['name'] == name:
creds = entry['credentials']
url = 'redis://:{password}@{hostname}:{port}'.format(
password=creds['password'],
hostname=creds['hostname'],
port=creds['port']
)
env['REDIS_URL'] = url
return
def is_running_tests(argv: List[str]=sys.argv) -> bool:
'''
Returns whether or not we're running tests.
'''
basename = os.path.basename(argv[0])
first_arg = argv[1] if len(argv) > 1 else None
if basename == 'manage.py' and first_arg == 'test':
return True
if basename == 'py.test':
return True
return False
| []
| []
| []
| [] | [] | python | 0 | 0 | |
pkg/archive/archive_test.go | package archive
import (
"archive/tar"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
var tmp string
func init() {
tmp = "/tmp/"
if runtime.GOOS == "windows" {
tmp = os.Getenv("TEMP") + `\`
}
}
func TestIsArchiveNilHeader(t *testing.T) {
out := IsArchive(nil)
if out {
t.Fatalf("isArchive should return false as nil is not a valid archive header")
}
}
func TestIsArchiveInvalidHeader(t *testing.T) {
header := []byte{0x00, 0x01, 0x02}
out := IsArchive(header)
if out {
t.Fatalf("isArchive should return false as %s is not a valid archive header", header)
}
}
func TestIsArchiveBzip2(t *testing.T) {
header := []byte{0x42, 0x5A, 0x68}
out := IsArchive(header)
if !out {
t.Fatalf("isArchive should return true as %s is a bz2 header", header)
}
}
func TestIsArchive7zip(t *testing.T) {
header := []byte{0x50, 0x4b, 0x03, 0x04}
out := IsArchive(header)
if out {
t.Fatalf("isArchive should return false as %s is a 7z header and it is not supported", header)
}
}
func TestIsArchivePathDir(t *testing.T) {
cmd := exec.Command("sh", "-c", "mkdir -p /tmp/archivedir")
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
if IsArchivePath(tmp + "archivedir") {
t.Fatalf("Incorrectly recognised directory as an archive")
}
}
func TestIsArchivePathInvalidFile(t *testing.T) {
cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1K count=1 of=/tmp/archive && gzip --stdout /tmp/archive > /tmp/archive.gz")
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
if IsArchivePath(tmp + "archive") {
t.Fatalf("Incorrectly recognised invalid tar path as archive")
}
if IsArchivePath(tmp + "archive.gz") {
t.Fatalf("Incorrectly recognised invalid compressed tar path as archive")
}
}
func TestIsArchivePathTar(t *testing.T) {
cmd := exec.Command("sh", "-c", "touch /tmp/archivedata && tar -cf /tmp/archive /tmp/archivedata && gzip --stdout /tmp/archive > /tmp/archive.gz")
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
if !IsArchivePath(tmp + "/archive") {
t.Fatalf("Did not recognise valid tar path as archive")
}
if !IsArchivePath(tmp + "archive.gz") {
t.Fatalf("Did not recognise valid compressed tar path as archive")
}
}
func TestDecompressStreamGzip(t *testing.T) {
cmd := exec.Command("sh", "-c", "touch /tmp/archive && gzip -f /tmp/archive")
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
archive, err := os.Open(tmp + "archive.gz")
_, err = DecompressStream(archive)
if err != nil {
t.Fatalf("Failed to decompress a gzip file.")
}
}
func TestDecompressStreamBzip2(t *testing.T) {
cmd := exec.Command("sh", "-c", "touch /tmp/archive && bzip2 -f /tmp/archive")
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
archive, err := os.Open(tmp + "archive.bz2")
_, err = DecompressStream(archive)
if err != nil {
t.Fatalf("Failed to decompress a bzip2 file.")
}
}
func TestDecompressStreamXz(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Xz not present in msys2")
}
cmd := exec.Command("sh", "-c", "touch /tmp/archive && xz -f /tmp/archive")
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Fail to create an archive file for test : %s.", output)
}
archive, err := os.Open(tmp + "archive.xz")
_, err = DecompressStream(archive)
if err != nil {
t.Fatalf("Failed to decompress a xz file.")
}
}
func TestCompressStreamXzUnsuported(t *testing.T) {
dest, err := os.Create(tmp + "dest")
if err != nil {
t.Fatalf("Fail to create the destination file")
}
_, err = CompressStream(dest, Xz)
if err == nil {
t.Fatalf("Should fail as xz is unsupported for compression format.")
}
}
func TestCompressStreamBzip2Unsupported(t *testing.T) {
dest, err := os.Create(tmp + "dest")
if err != nil {
t.Fatalf("Fail to create the destination file")
}
_, err = CompressStream(dest, Xz)
if err == nil {
t.Fatalf("Should fail as xz is unsupported for compression format.")
}
}
func TestCompressStreamInvalid(t *testing.T) {
dest, err := os.Create(tmp + "dest")
if err != nil {
t.Fatalf("Fail to create the destination file")
}
_, err = CompressStream(dest, -1)
if err == nil {
t.Fatalf("Should fail as xz is unsupported for compression format.")
}
}
func TestExtensionInvalid(t *testing.T) {
compression := Compression(-1)
output := compression.Extension()
if output != "" {
t.Fatalf("The extension of an invalid compression should be an empty string.")
}
}
func TestExtensionUncompressed(t *testing.T) {
compression := Uncompressed
output := compression.Extension()
if output != "tar" {
t.Fatalf("The extension of a uncompressed archive should be 'tar'.")
}
}
func TestExtensionBzip2(t *testing.T) {
compression := Bzip2
output := compression.Extension()
if output != "tar.bz2" {
t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'")
}
}
func TestExtensionGzip(t *testing.T) {
compression := Gzip
output := compression.Extension()
if output != "tar.gz" {
t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'")
}
}
func TestExtensionXz(t *testing.T) {
compression := Xz
output := compression.Extension()
if output != "tar.xz" {
t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'")
}
}
func TestCmdStreamLargeStderr(t *testing.T) {
cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello")
out, _, err := cmdStream(cmd, nil)
if err != nil {
t.Fatalf("Failed to start command: %s", err)
}
errCh := make(chan error)
go func() {
_, err := io.Copy(ioutil.Discard, out)
errCh <- err
}()
select {
case err := <-errCh:
if err != nil {
t.Fatalf("Command should not have failed (err=%.100s...)", err)
}
case <-time.After(5 * time.Second):
t.Fatalf("Command did not complete in 5 seconds; probable deadlock")
}
}
func TestCmdStreamBad(t *testing.T) {
badCmd := exec.Command("sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1")
out, _, err := cmdStream(badCmd, nil)
if err != nil {
t.Fatalf("Failed to start command: %s", err)
}
if output, err := ioutil.ReadAll(out); err == nil {
t.Fatalf("Command should have failed")
} else if err.Error() != "exit status 1: error couldn't reverse the phase pulser\n" {
t.Fatalf("Wrong error value (%s)", err)
} else if s := string(output); s != "hello\n" {
t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
}
}
func TestCmdStreamGood(t *testing.T) {
cmd := exec.Command("sh", "-c", "echo hello; exit 0")
out, _, err := cmdStream(cmd, nil)
if err != nil {
t.Fatal(err)
}
if output, err := ioutil.ReadAll(out); err != nil {
t.Fatalf("Command should not have failed (err=%s)", err)
} else if s := string(output); s != "hello\n" {
t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
}
}
func TestUntarPathWithInvalidDest(t *testing.T) {
tempFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempFolder)
invalidDestFolder := filepath.Join(tempFolder, "invalidDest")
// Create a src file
srcFile := filepath.Join(tempFolder, "src")
tarFile := filepath.Join(tempFolder, "src.tar")
os.Create(srcFile)
os.Create(invalidDestFolder) // being a file (not dir) should cause an error
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := srcFile
tarFileU := tarFile
if runtime.GOOS == "windows" {
tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
}
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
_, err = cmd.CombinedOutput()
if err != nil {
t.Fatal(err)
}
err = UntarPath(tarFile, invalidDestFolder)
if err == nil {
t.Fatalf("UntarPath with invalid destination path should throw an error.")
}
}
func TestUntarPathWithInvalidSrc(t *testing.T) {
dest, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatalf("Fail to create the destination file")
}
defer os.RemoveAll(dest)
err = UntarPath("/invalid/path", dest)
if err == nil {
t.Fatalf("UntarPath with invalid src path should throw an error.")
}
}
func TestUntarPath(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpFolder)
srcFile := filepath.Join(tmpFolder, "src")
tarFile := filepath.Join(tmpFolder, "src.tar")
os.Create(filepath.Join(tmpFolder, "src"))
destFolder := filepath.Join(tmpFolder, "dest")
err = os.MkdirAll(destFolder, 0740)
if err != nil {
t.Fatalf("Fail to create the destination file")
}
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := srcFile
tarFileU := tarFile
if runtime.GOOS == "windows" {
tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
}
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
_, err = cmd.CombinedOutput()
if err != nil {
t.Fatal(err)
}
err = UntarPath(tarFile, destFolder)
if err != nil {
t.Fatalf("UntarPath shouldn't throw an error, %s.", err)
}
expectedFile := filepath.Join(destFolder, srcFileU)
_, err = os.Stat(expectedFile)
if err != nil {
t.Fatalf("Destination folder should contain the source file but did not.")
}
}
// Do the same test as above but with the destination as file, it should fail
func TestUntarPathWithDestinationFile(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpFolder)
srcFile := filepath.Join(tmpFolder, "src")
tarFile := filepath.Join(tmpFolder, "src.tar")
os.Create(filepath.Join(tmpFolder, "src"))
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := srcFile
tarFileU := tarFile
if runtime.GOOS == "windows" {
tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
}
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
_, err = cmd.CombinedOutput()
if err != nil {
t.Fatal(err)
}
destFile := filepath.Join(tmpFolder, "dest")
_, err = os.Create(destFile)
if err != nil {
t.Fatalf("Fail to create the destination file")
}
err = UntarPath(tarFile, destFile)
if err == nil {
t.Fatalf("UntarPath should throw an error if the destination if a file")
}
}
// Do the same test as above but with the destination folder already exists
// and the destination file is a directory
// It's working, see https://github.com/docker/docker/issues/10040
func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) {
tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpFolder)
srcFile := filepath.Join(tmpFolder, "src")
tarFile := filepath.Join(tmpFolder, "src.tar")
os.Create(srcFile)
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := srcFile
tarFileU := tarFile
if runtime.GOOS == "windows" {
tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
}
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
_, err = cmd.CombinedOutput()
if err != nil {
t.Fatal(err)
}
destFolder := filepath.Join(tmpFolder, "dest")
err = os.MkdirAll(destFolder, 0740)
if err != nil {
t.Fatalf("Fail to create the destination folder")
}
// Let's create a folder that will has the same path as the extracted file (from tar)
destSrcFileAsFolder := filepath.Join(destFolder, srcFileU)
err = os.MkdirAll(destSrcFileAsFolder, 0740)
if err != nil {
t.Fatal(err)
}
err = UntarPath(tarFile, destFolder)
if err != nil {
t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder")
}
}
func TestCopyWithTarInvalidSrc(t *testing.T) {
tempFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(nil)
}
destFolder := filepath.Join(tempFolder, "dest")
invalidSrc := filepath.Join(tempFolder, "doesnotexists")
err = os.MkdirAll(destFolder, 0740)
if err != nil {
t.Fatal(err)
}
err = CopyWithTar(invalidSrc, destFolder)
if err == nil {
t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
}
}
func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) {
tempFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(nil)
}
srcFolder := filepath.Join(tempFolder, "src")
inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
err = os.MkdirAll(srcFolder, 0740)
if err != nil {
t.Fatal(err)
}
err = CopyWithTar(srcFolder, inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
}
_, err = os.Stat(inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder should create it.")
}
}
// Test CopyWithTar with a file as src
func TestCopyWithTarSrcFile(t *testing.T) {
folder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(folder)
dest := filepath.Join(folder, "dest")
srcFolder := filepath.Join(folder, "src")
src := filepath.Join(folder, filepath.Join("src", "src"))
err = os.MkdirAll(srcFolder, 0740)
if err != nil {
t.Fatal(err)
}
err = os.MkdirAll(dest, 0740)
if err != nil {
t.Fatal(err)
}
ioutil.WriteFile(src, []byte("content"), 0777)
err = CopyWithTar(src, dest)
if err != nil {
t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
}
_, err = os.Stat(dest)
// FIXME Check the content
if err != nil {
t.Fatalf("Destination file should be the same as the source.")
}
}
// Test CopyWithTar with a folder as src
func TestCopyWithTarSrcFolder(t *testing.T) {
folder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(folder)
dest := filepath.Join(folder, "dest")
src := filepath.Join(folder, filepath.Join("src", "folder"))
err = os.MkdirAll(src, 0740)
if err != nil {
t.Fatal(err)
}
err = os.MkdirAll(dest, 0740)
if err != nil {
t.Fatal(err)
}
ioutil.WriteFile(filepath.Join(src, "file"), []byte("content"), 0777)
err = CopyWithTar(src, dest)
if err != nil {
t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
}
_, err = os.Stat(dest)
// FIXME Check the content (the file inside)
if err != nil {
t.Fatalf("Destination folder should contain the source file but did not.")
}
}
func TestCopyFileWithTarInvalidSrc(t *testing.T) {
tempFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempFolder)
destFolder := filepath.Join(tempFolder, "dest")
err = os.MkdirAll(destFolder, 0740)
if err != nil {
t.Fatal(err)
}
invalidFile := filepath.Join(tempFolder, "doesnotexists")
err = CopyFileWithTar(invalidFile, destFolder)
if err == nil {
t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
}
}
func TestCopyFileWithTarInexistentDestWillCreateIt(t *testing.T) {
tempFolder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(nil)
}
defer os.RemoveAll(tempFolder)
srcFile := filepath.Join(tempFolder, "src")
inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
_, err = os.Create(srcFile)
if err != nil {
t.Fatal(err)
}
err = CopyFileWithTar(srcFile, inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
}
_, err = os.Stat(inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder should create it.")
}
// FIXME Test the src file and content
}
func TestCopyFileWithTarSrcFolder(t *testing.T) {
folder, err := ioutil.TempDir("", "docker-archive-copyfilewithtar-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(folder)
dest := filepath.Join(folder, "dest")
src := filepath.Join(folder, "srcfolder")
err = os.MkdirAll(src, 0740)
if err != nil {
t.Fatal(err)
}
err = os.MkdirAll(dest, 0740)
if err != nil {
t.Fatal(err)
}
err = CopyFileWithTar(src, dest)
if err == nil {
t.Fatalf("CopyFileWithTar should throw an error with a folder.")
}
}
func TestCopyFileWithTarSrcFile(t *testing.T) {
folder, err := ioutil.TempDir("", "docker-archive-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(folder)
dest := filepath.Join(folder, "dest")
srcFolder := filepath.Join(folder, "src")
src := filepath.Join(folder, filepath.Join("src", "src"))
err = os.MkdirAll(srcFolder, 0740)
if err != nil {
t.Fatal(err)
}
err = os.MkdirAll(dest, 0740)
if err != nil {
t.Fatal(err)
}
ioutil.WriteFile(src, []byte("content"), 0777)
err = CopyWithTar(src, dest+"/")
if err != nil {
t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err)
}
_, err = os.Stat(dest)
if err != nil {
t.Fatalf("Destination folder should contain the source file but did not.")
}
}
func TestTarFiles(t *testing.T) {
// TODO Windows: Figure out how to port this test.
if runtime.GOOS == "windows" {
t.Skip("Failing on Windows")
}
// try without hardlinks
if err := checkNoChanges(1000, false); err != nil {
t.Fatal(err)
}
// try with hardlinks
if err := checkNoChanges(1000, true); err != nil {
t.Fatal(err)
}
}
func checkNoChanges(fileNum int, hardlinks bool) error {
srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
if err != nil {
return err
}
defer os.RemoveAll(srcDir)
destDir, err := ioutil.TempDir("", "docker-test-destDir")
if err != nil {
return err
}
defer os.RemoveAll(destDir)
_, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks)
if err != nil {
return err
}
err = TarUntar(srcDir, destDir)
if err != nil {
return err
}
changes, err := ChangesDirs(destDir, srcDir)
if err != nil {
return err
}
if len(changes) > 0 {
return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes))
}
return nil
}
func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) {
archive, err := TarWithOptions(origin, options)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
buf := make([]byte, 10)
if _, err := archive.Read(buf); err != nil {
return nil, err
}
wrap := io.MultiReader(bytes.NewReader(buf), archive)
detectedCompression := DetectCompression(buf)
compression := options.Compression
if detectedCompression.Extension() != compression.Extension() {
return nil, fmt.Errorf("Wrong compression detected. Actual compression: %s, found %s", compression.Extension(), detectedCompression.Extension())
}
tmp, err := ioutil.TempDir("", "docker-test-untar")
if err != nil {
return nil, err
}
defer os.RemoveAll(tmp)
if err := Untar(wrap, tmp, nil); err != nil {
return nil, err
}
if _, err := os.Stat(tmp); err != nil {
return nil, err
}
return ChangesDirs(origin, tmp)
}
func TestTarUntar(t *testing.T) {
// TODO Windows: Figure out how to fix this test.
if runtime.GOOS == "windows" {
t.Skip("Failing on Windows")
}
origin, err := ioutil.TempDir("", "docker-test-untar-origin")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(origin)
if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil {
t.Fatal(err)
}
for _, c := range []Compression{
Uncompressed,
Gzip,
} {
changes, err := tarUntar(t, origin, &TarOptions{
Compression: c,
ExcludePatterns: []string{"3"},
})
if err != nil {
t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err)
}
if len(changes) != 1 || changes[0].Path != "/3" {
t.Fatalf("Unexpected differences after tarUntar: %v", changes)
}
}
}
func TestTarWithOptions(t *testing.T) {
// TODO Windows: Figure out how to fix this test.
if runtime.GOOS == "windows" {
t.Skip("Failing on Windows")
}
origin, err := ioutil.TempDir("", "docker-test-untar-origin")
if err != nil {
t.Fatal(err)
}
if _, err := ioutil.TempDir(origin, "folder"); err != nil {
t.Fatal(err)
}
defer os.RemoveAll(origin)
if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
t.Fatal(err)
}
cases := []struct {
opts *TarOptions
numChanges int
}{
{&TarOptions{IncludeFiles: []string{"1"}}, 2},
{&TarOptions{ExcludePatterns: []string{"2"}}, 1},
{&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2},
{&TarOptions{IncludeFiles: []string{"1", "1"}}, 2},
{&TarOptions{IncludeFiles: []string{"1"}, RebaseNames: map[string]string{"1": "test"}}, 4},
}
for _, testCase := range cases {
changes, err := tarUntar(t, origin, testCase.opts)
if err != nil {
t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err)
}
if len(changes) != testCase.numChanges {
t.Errorf("Expected %d changes, got %d for %+v:",
testCase.numChanges, len(changes), testCase.opts)
}
}
}
// Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz
// use PAX Global Extended Headers.
// Failing prevents the archives from being uncompressed during ADD
func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) {
hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader}
tmpDir, err := ioutil.TempDir("", "docker-test-archive-pax-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
err = createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, true, nil)
if err != nil {
t.Fatal(err)
}
}
// Some tar have both GNU specific (huge uid) and Ustar specific (long name) things.
// Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work.
func TestUntarUstarGnuConflict(t *testing.T) {
f, err := os.Open("testdata/broken.tar")
if err != nil {
t.Fatal(err)
}
found := false
tr := tar.NewReader(f)
// Iterate through the files in the archive.
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
if err != nil {
t.Fatal(err)
}
if hdr.Name == "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm" {
found = true
break
}
}
if !found {
t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm")
}
}
func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) {
fileData := []byte("fooo")
for n := 0; n < numberOfFiles; n++ {
fileName := fmt.Sprintf("file-%d", n)
if err := ioutil.WriteFile(filepath.Join(targetPath, fileName), fileData, 0700); err != nil {
return 0, err
}
if makeLinks {
if err := os.Link(filepath.Join(targetPath, fileName), filepath.Join(targetPath, fileName+"-link")); err != nil {
return 0, err
}
}
}
totalSize := numberOfFiles * len(fileData)
return totalSize, nil
}
func BenchmarkTarUntar(b *testing.B) {
origin, err := ioutil.TempDir("", "docker-test-untar-origin")
if err != nil {
b.Fatal(err)
}
tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
if err != nil {
b.Fatal(err)
}
target := filepath.Join(tempDir, "dest")
n, err := prepareUntarSourceDirectory(100, origin, false)
if err != nil {
b.Fatal(err)
}
defer os.RemoveAll(origin)
defer os.RemoveAll(tempDir)
b.ResetTimer()
b.SetBytes(int64(n))
for n := 0; n < b.N; n++ {
err := TarUntar(origin, target)
if err != nil {
b.Fatal(err)
}
os.RemoveAll(target)
}
}
func BenchmarkTarUntarWithLinks(b *testing.B) {
origin, err := ioutil.TempDir("", "docker-test-untar-origin")
if err != nil {
b.Fatal(err)
}
tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
if err != nil {
b.Fatal(err)
}
target := filepath.Join(tempDir, "dest")
n, err := prepareUntarSourceDirectory(100, origin, true)
if err != nil {
b.Fatal(err)
}
defer os.RemoveAll(origin)
defer os.RemoveAll(tempDir)
b.ResetTimer()
b.SetBytes(int64(n))
for n := 0; n < b.N; n++ {
err := TarUntar(origin, target)
if err != nil {
b.Fatal(err)
}
os.RemoveAll(target)
}
}
func TestUntarInvalidFilenames(t *testing.T) {
// TODO Windows: Figure out how to fix this test.
if runtime.GOOS == "windows" {
t.Skip("Passes but hits breakoutError: platform and architecture is not supported")
}
for i, headers := range [][]*tar.Header{
{
{
Name: "../victim/dotdot",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
{
{
// Note the leading slash
Name: "/../victim/slash-dotdot",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarInvalidFilenames", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestUntarHardlinkToSymlink(t *testing.T) {
// TODO Windows. There may be a way of running this, but turning off for now
if runtime.GOOS == "windows" {
t.Skip("hardlinks on Windows")
}
for i, headers := range [][]*tar.Header{
{
{
Name: "symlink1",
Typeflag: tar.TypeSymlink,
Linkname: "regfile",
Mode: 0644,
},
{
Name: "symlink2",
Typeflag: tar.TypeLink,
Linkname: "symlink1",
Mode: 0644,
},
{
Name: "regfile",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarHardlinkToSymlink", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestUntarInvalidHardlink(t *testing.T) {
// TODO Windows. There may be a way of running this, but turning off for now
if runtime.GOOS == "windows" {
t.Skip("hardlinks on Windows")
}
for i, headers := range [][]*tar.Header{
{ // try reading victim/hello (../)
{
Name: "dotdot",
Typeflag: tar.TypeLink,
Linkname: "../victim/hello",
Mode: 0644,
},
},
{ // try reading victim/hello (/../)
{
Name: "slash-dotdot",
Typeflag: tar.TypeLink,
// Note the leading slash
Linkname: "/../victim/hello",
Mode: 0644,
},
},
{ // try writing victim/file
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "loophole-victim/file",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
{ // try reading victim/hello (hardlink, symlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "symlink",
Typeflag: tar.TypeSymlink,
Linkname: "loophole-victim/hello",
Mode: 0644,
},
},
{ // Try reading victim/hello (hardlink, hardlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "hardlink",
Typeflag: tar.TypeLink,
Linkname: "loophole-victim/hello",
Mode: 0644,
},
},
{ // Try removing victim directory (hardlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "loophole-victim",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarInvalidHardlink", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestUntarInvalidSymlink(t *testing.T) {
// TODO Windows. There may be a way of running this, but turning off for now
if runtime.GOOS == "windows" {
t.Skip("hardlinks on Windows")
}
for i, headers := range [][]*tar.Header{
{ // try reading victim/hello (../)
{
Name: "dotdot",
Typeflag: tar.TypeSymlink,
Linkname: "../victim/hello",
Mode: 0644,
},
},
{ // try reading victim/hello (/../)
{
Name: "slash-dotdot",
Typeflag: tar.TypeSymlink,
// Note the leading slash
Linkname: "/../victim/hello",
Mode: 0644,
},
},
{ // try writing victim/file
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "loophole-victim/file",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
{ // try reading victim/hello (symlink, symlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "symlink",
Typeflag: tar.TypeSymlink,
Linkname: "loophole-victim/hello",
Mode: 0644,
},
},
{ // try reading victim/hello (symlink, hardlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "hardlink",
Typeflag: tar.TypeLink,
Linkname: "loophole-victim/hello",
Mode: 0644,
},
},
{ // try removing victim directory (symlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0755,
},
{
Name: "loophole-victim",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
{ // try writing to victim/newdir/newfile with a symlink in the path
{
// this header needs to be before the next one, or else there is an error
Name: "dir/loophole",
Typeflag: tar.TypeSymlink,
Linkname: "../../victim",
Mode: 0755,
},
{
Name: "dir/loophole/newdir/newfile",
Typeflag: tar.TypeReg,
Mode: 0644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarInvalidSymlink", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestTempArchiveCloseMultipleTimes(t *testing.T) {
reader := ioutil.NopCloser(strings.NewReader("hello"))
tempArchive, err := NewTempArchive(reader, "")
buf := make([]byte, 10)
n, err := tempArchive.Read(buf)
if n != 5 {
t.Fatalf("Expected to read 5 bytes. Read %d instead", n)
}
for i := 0; i < 3; i++ {
if err = tempArchive.Close(); err != nil {
t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err)
}
}
}
| [
"\"TEMP\""
]
| []
| [
"TEMP"
]
| [] | ["TEMP"] | go | 1 | 0 | |
tool/pkg/common.go | package pkg
import (
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
// Source source
type Source struct {
Fset *token.FileSet
Src string
F *ast.File
}
// NewSource new source
func NewSource(src string) *Source {
s := &Source{
Fset: token.NewFileSet(),
Src: src,
}
f, err := parser.ParseFile(s.Fset, "", src, 0)
if err != nil {
log.Fatal("无法解析源文件")
}
s.F = f
return s
}
// ExprString expr string
func (s *Source) ExprString(typ ast.Expr) string {
fset := s.Fset
s1 := fset.Position(typ.Pos()).Offset
s2 := fset.Position(typ.End()).Offset
return s.Src[s1:s2]
}
// pkgPath package path
func (s *Source) pkgPath(name string) (res string) {
for _, im := range s.F.Imports {
if im.Name != nil && im.Name.Name == name {
return im.Path.Value
}
}
for _, im := range s.F.Imports {
if strings.HasSuffix(im.Path.Value, name+"\"") {
return im.Path.Value
}
}
return
}
// GetDef get define code
func (s *Source) GetDef(name string) string {
c := s.F.Scope.Lookup(name).Decl.(*ast.TypeSpec).Type.(*ast.InterfaceType)
s1 := s.Fset.Position(c.Pos()).Offset
s2 := s.Fset.Position(c.End()).Offset
line := s.Fset.Position(c.Pos()).Line
lines := []string{strings.Split(s.Src, "\n")[line-1]}
for _, l := range strings.Split(s.Src[s1:s2], "\n")[1:] {
lines = append(lines, "\t"+l)
}
return strings.Join(lines, "\n")
}
// RegexpReplace replace regexp
func RegexpReplace(reg, src, temp string) string {
result := []byte{}
pattern := regexp.MustCompile(reg)
for _, submatches := range pattern.FindAllStringSubmatchIndex(src, -1) {
result = pattern.ExpandString(result, temp, src, submatches)
}
return string(result)
}
// formatPackage format package
func formatPackage(name, path string) (res string) {
if path != "" {
if strings.HasSuffix(path, name+"\"") {
res = path
return
}
res = fmt.Sprintf("%s %s", name, path)
}
return
}
// SourceText get source file text
func SourceText() string {
file := os.Getenv("GOFILE")
data, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal("请使用go generate执行", file)
}
return string(data)
}
// FormatCode format code
func FormatCode(source string) string {
src, err := format.Source([]byte(source))
if err != nil {
// Should never happen, but can arise when developing this code.
// The user can compile the output to see the error.
log.Printf("warning: 输出文件不合法: %s", err)
log.Printf("warning: 详细错误请编译查看")
return source
}
return string(src)
}
// Packages get import packages
func (s *Source) Packages(f *ast.Field) (res []string) {
fs := f.Type.(*ast.FuncType).Params.List
fs = append(fs, f.Type.(*ast.FuncType).Results.List...)
var types []string
resMap := make(map[string]bool)
for _, field := range fs {
if p, ok := field.Type.(*ast.MapType); ok {
types = append(types, s.ExprString(p.Key))
types = append(types, s.ExprString(p.Value))
} else if p, ok := field.Type.(*ast.ArrayType); ok {
types = append(types, s.ExprString(p.Elt))
} else {
types = append(types, s.ExprString(field.Type))
}
}
for _, t := range types {
name := RegexpReplace(`(?P<pkg>\w+)\.\w+`, t, "$pkg")
if name == "" {
continue
}
pkg := formatPackage(name, s.pkgPath(name))
if !resMap[pkg] {
resMap[pkg] = true
}
}
for pkg := range resMap {
res = append(res, pkg)
}
return
}
| [
"\"GOFILE\""
]
| []
| [
"GOFILE"
]
| [] | ["GOFILE"] | go | 1 | 0 | |
test/test_dataset.py | import os
import unittest
from datetime import datetime
from collections import OrderedDict
from sqlalchemy import TEXT, BIGINT
from sqlalchemy.exc import IntegrityError, SQLAlchemyError, ArgumentError
from dataset import connect, chunked
from .sample_data import TEST_DATA, TEST_CITY_1
class DatabaseTestCase(unittest.TestCase):
def setUp(self):
self.db = connect()
self.tbl = self.db["weather"]
self.tbl.insert_many(TEST_DATA)
def tearDown(self):
for table in self.db.tables:
self.db[table].drop()
def test_valid_database_url(self):
assert self.db.url, os.environ["DATABASE_URL"]
def test_database_url_query_string(self):
db = connect("sqlite:///:memory:/?cached_statements=1")
assert "cached_statements" in db.url, db.url
def test_tables(self):
assert self.db.tables == ["weather"], self.db.tables
def test_contains(self):
assert "weather" in self.db, self.db.tables
def test_create_table(self):
table = self.db["foo"]
assert self.db.has_table(table.table.name)
assert len(table.table.columns) == 1, table.table.columns
assert "id" in table.table.c, table.table.c
def test_create_table_no_ids(self):
if "mysql" in self.db.engine.dialect.dbapi.__name__:
return
if "sqlite" in self.db.engine.dialect.dbapi.__name__:
return
table = self.db.create_table("foo_no_id", primary_id=False)
assert table.table.exists()
assert len(table.table.columns) == 0, table.table.columns
def test_create_table_custom_id1(self):
pid = "string_id"
table = self.db.create_table("foo2", pid, self.db.types.string(255))
assert self.db.has_table(table.table.name)
assert len(table.table.columns) == 1, table.table.columns
assert pid in table.table.c, table.table.c
table.insert({pid: "foobar"})
assert table.find_one(string_id="foobar")[pid] == "foobar"
def test_create_table_custom_id2(self):
pid = "string_id"
table = self.db.create_table("foo3", pid, self.db.types.string(50))
assert self.db.has_table(table.table.name)
assert len(table.table.columns) == 1, table.table.columns
assert pid in table.table.c, table.table.c
table.insert({pid: "foobar"})
assert table.find_one(string_id="foobar")[pid] == "foobar"
def test_create_table_custom_id3(self):
pid = "int_id"
table = self.db.create_table("foo4", primary_id=pid)
assert self.db.has_table(table.table.name)
assert len(table.table.columns) == 1, table.table.columns
assert pid in table.table.c, table.table.c
table.insert({pid: 123})
table.insert({pid: 124})
assert table.find_one(int_id=123)[pid] == 123
assert table.find_one(int_id=124)[pid] == 124
self.assertRaises(IntegrityError, lambda: table.insert({pid: 123}))
def test_create_table_shorthand1(self):
pid = "int_id"
table = self.db.get_table("foo5", pid)
assert table.table.exists
assert len(table.table.columns) == 1, table.table.columns
assert pid in table.table.c, table.table.c
table.insert({"int_id": 123})
table.insert({"int_id": 124})
assert table.find_one(int_id=123)["int_id"] == 123
assert table.find_one(int_id=124)["int_id"] == 124
self.assertRaises(IntegrityError, lambda: table.insert({"int_id": 123}))
def test_create_table_shorthand2(self):
pid = "string_id"
table = self.db.get_table(
"foo6", primary_id=pid, primary_type=self.db.types.string(255)
)
assert table.table.exists
assert len(table.table.columns) == 1, table.table.columns
assert pid in table.table.c, table.table.c
table.insert({"string_id": "foobar"})
assert table.find_one(string_id="foobar")["string_id"] == "foobar"
def test_with(self):
init_length = len(self.db["weather"])
with self.assertRaises(ValueError):
with self.db as tx:
tx["weather"].insert(
{
"date": datetime(2011, 1, 1),
"temperature": 1,
"place": "tmp_place",
}
)
raise ValueError()
assert len(self.db["weather"]) == init_length
def test_invalid_values(self):
if "mysql" in self.db.engine.dialect.dbapi.__name__:
# WARNING: mysql seems to be doing some weird type casting
# upon insert. The mysql-python driver is not affected but
# it isn't compatible with Python 3
# Conclusion: use postgresql.
return
with self.assertRaises(SQLAlchemyError):
tbl = self.db["weather"]
tbl.insert(
{"date": True, "temperature": "wrong_value", "place": "tmp_place"}
)
def test_load_table(self):
tbl = self.db.load_table("weather")
assert tbl.table.name == self.tbl.table.name
def test_query(self):
r = self.db.query("SELECT COUNT(*) AS num FROM weather").next()
assert r["num"] == len(TEST_DATA), r
def test_table_cache_updates(self):
tbl1 = self.db.get_table("people")
data = OrderedDict([("first_name", "John"), ("last_name", "Smith")])
tbl1.insert(data)
data["id"] = 1
tbl2 = self.db.get_table("people")
assert dict(tbl2.all().next()) == dict(data), (tbl2.all().next(), data)
class TableTestCase(unittest.TestCase):
def setUp(self):
self.db = connect()
self.tbl = self.db["weather"]
for row in TEST_DATA:
self.tbl.insert(row)
def tearDown(self):
self.tbl.drop()
def test_insert(self):
assert len(self.tbl) == len(TEST_DATA), len(self.tbl)
last_id = self.tbl.insert(
{"date": datetime(2011, 1, 2), "temperature": -10, "place": "Berlin"}
)
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
assert self.tbl.find_one(id=last_id)["place"] == "Berlin"
def test_insert_ignore(self):
self.tbl.insert_ignore(
{"date": datetime(2011, 1, 2), "temperature": -10, "place": "Berlin"},
["place"],
)
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
self.tbl.insert_ignore(
{"date": datetime(2011, 1, 2), "temperature": -10, "place": "Berlin"},
["place"],
)
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
def test_insert_ignore_all_key(self):
for i in range(0, 4):
self.tbl.insert_ignore(
{"date": datetime(2011, 1, 2), "temperature": -10, "place": "Berlin"},
["date", "temperature", "place"],
)
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
def test_insert_json(self):
last_id = self.tbl.insert(
{
"date": datetime(2011, 1, 2),
"temperature": -10,
"place": "Berlin",
"info": {
"currency": "EUR",
"language": "German",
"population": 3292365,
},
}
)
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
assert self.tbl.find_one(id=last_id)["place"] == "Berlin"
def test_upsert(self):
self.tbl.upsert(
{"date": datetime(2011, 1, 2), "temperature": -10, "place": "Berlin"},
["place"],
)
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
self.tbl.upsert(
{"date": datetime(2011, 1, 2), "temperature": -10, "place": "Berlin"},
["place"],
)
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
def test_upsert_single_column(self):
table = self.db["banana_single_col"]
table.upsert({"color": "Yellow"}, ["color"])
assert len(table) == 1, len(table)
table.upsert({"color": "Yellow"}, ["color"])
assert len(table) == 1, len(table)
def test_upsert_all_key(self):
assert len(self.tbl) == len(TEST_DATA), len(self.tbl)
for i in range(0, 2):
self.tbl.upsert(
{"date": datetime(2011, 1, 2), "temperature": -10, "place": "Berlin"},
["date", "temperature", "place"],
)
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
def test_upsert_id(self):
table = self.db["banana_with_id"]
data = dict(id=10, title="I am a banana!")
table.upsert(data, ["id"])
assert len(table) == 1, len(table)
def test_update_while_iter(self):
for row in self.tbl:
row["foo"] = "bar"
self.tbl.update(row, ["place", "date"])
assert len(self.tbl) == len(TEST_DATA), len(self.tbl)
def test_weird_column_names(self):
with self.assertRaises(ValueError):
self.tbl.insert(
{
"date": datetime(2011, 1, 2),
"temperature": -10,
"foo.bar": "Berlin",
"qux.bar": "Huhu",
}
)
def test_cased_column_names(self):
tbl = self.db["cased_column_names"]
tbl.insert({"place": "Berlin"})
tbl.insert({"Place": "Berlin"})
tbl.insert({"PLACE ": "Berlin"})
assert len(tbl.columns) == 2, tbl.columns
assert len(list(tbl.find(Place="Berlin"))) == 3
assert len(list(tbl.find(place="Berlin"))) == 3
assert len(list(tbl.find(PLACE="Berlin"))) == 3
def test_invalid_column_names(self):
tbl = self.db["weather"]
with self.assertRaises(ValueError):
tbl.insert({None: "banana"})
with self.assertRaises(ValueError):
tbl.insert({"": "banana"})
with self.assertRaises(ValueError):
tbl.insert({"-": "banana"})
def test_delete(self):
self.tbl.insert(
{"date": datetime(2011, 1, 2), "temperature": -10, "place": "Berlin"}
)
original_count = len(self.tbl)
assert len(self.tbl) == len(TEST_DATA) + 1, len(self.tbl)
# Test bad use of API
with self.assertRaises(ArgumentError):
self.tbl.delete({"place": "Berlin"})
assert len(self.tbl) == original_count, len(self.tbl)
assert self.tbl.delete(place="Berlin") is True, "should return 1"
assert len(self.tbl) == len(TEST_DATA), len(self.tbl)
assert self.tbl.delete() is True, "should return non zero"
assert len(self.tbl) == 0, len(self.tbl)
def test_repr(self):
assert (
repr(self.tbl) == "<Table(weather)>"
), "the representation should be <Table(weather)>"
def test_delete_nonexist_entry(self):
assert (
self.tbl.delete(place="Berlin") is False
), "entry not exist, should fail to delete"
def test_find_one(self):
self.tbl.insert(
{"date": datetime(2011, 1, 2), "temperature": -10, "place": "Berlin"}
)
d = self.tbl.find_one(place="Berlin")
assert d["temperature"] == -10, d
d = self.tbl.find_one(place="Atlantis")
assert d is None, d
def test_count(self):
assert len(self.tbl) == 6, len(self.tbl)
length = self.tbl.count(place=TEST_CITY_1)
assert length == 3, length
def test_find(self):
ds = list(self.tbl.find(place=TEST_CITY_1))
assert len(ds) == 3, ds
ds = list(self.tbl.find(place=TEST_CITY_1, _limit=2))
assert len(ds) == 2, ds
ds = list(self.tbl.find(place=TEST_CITY_1, _limit=2, _step=1))
assert len(ds) == 2, ds
ds = list(self.tbl.find(place=TEST_CITY_1, _limit=1, _step=2))
assert len(ds) == 1, ds
ds = list(self.tbl.find(_step=2))
assert len(ds) == len(TEST_DATA), ds
ds = list(self.tbl.find(order_by=["temperature"]))
assert ds[0]["temperature"] == -1, ds
ds = list(self.tbl.find(order_by=["-temperature"]))
assert ds[0]["temperature"] == 8, ds
ds = list(self.tbl.find(self.tbl.table.columns.temperature > 4))
assert len(ds) == 3, ds
def test_find_dsl(self):
ds = list(self.tbl.find(place={"like": "%lw%"}))
assert len(ds) == 3, ds
ds = list(self.tbl.find(temperature={">": 5}))
assert len(ds) == 2, ds
ds = list(self.tbl.find(temperature={">=": 5}))
assert len(ds) == 3, ds
ds = list(self.tbl.find(temperature={"<": 0}))
assert len(ds) == 1, ds
ds = list(self.tbl.find(temperature={"<=": 0}))
assert len(ds) == 2, ds
ds = list(self.tbl.find(temperature={"!=": -1}))
assert len(ds) == 5, ds
ds = list(self.tbl.find(temperature={"between": [5, 8]}))
assert len(ds) == 3, ds
ds = list(self.tbl.find(place={"=": "G€lway"}))
assert len(ds) == 3, ds
ds = list(self.tbl.find(place={"ilike": "%LwAy"}))
assert len(ds) == 3, ds
def test_offset(self):
ds = list(self.tbl.find(place=TEST_CITY_1, _offset=1))
assert len(ds) == 2, ds
ds = list(self.tbl.find(place=TEST_CITY_1, _limit=2, _offset=2))
assert len(ds) == 1, ds
def test_streamed(self):
ds = list(self.tbl.find(place=TEST_CITY_1, _streamed=True, _step=1))
assert len(ds) == 3, len(ds)
for row in self.tbl.find(place=TEST_CITY_1, _streamed=True, _step=1):
row["temperature"] = -1
self.tbl.update(row, ["id"])
def test_distinct(self):
x = list(self.tbl.distinct("place"))
assert len(x) == 2, x
x = list(self.tbl.distinct("place", "date"))
assert len(x) == 6, x
x = list(
self.tbl.distinct(
"place",
"date",
self.tbl.table.columns.date >= datetime(2011, 1, 2, 0, 0),
)
)
assert len(x) == 4, x
x = list(self.tbl.distinct("temperature", place="B€rkeley"))
assert len(x) == 3, x
x = list(self.tbl.distinct("temperature", place=["B€rkeley", "G€lway"]))
assert len(x) == 6, x
def test_insert_many(self):
data = TEST_DATA * 100
self.tbl.insert_many(data, chunk_size=13)
assert len(self.tbl) == len(data) + 6, (len(self.tbl), len(data))
def test_chunked_insert(self):
data = TEST_DATA * 100
with chunked.ChunkedInsert(self.tbl) as chunk_tbl:
for item in data:
chunk_tbl.insert(item)
assert len(self.tbl) == len(data) + 6, (len(self.tbl), len(data))
def test_chunked_insert_callback(self):
data = TEST_DATA * 100
N = 0
def callback(queue):
nonlocal N
N += len(queue)
with chunked.ChunkedInsert(self.tbl, callback=callback) as chunk_tbl:
for item in data:
chunk_tbl.insert(item)
assert len(data) == N
assert len(self.tbl) == len(data) + 6
def test_update_many(self):
tbl = self.db["update_many_test"]
tbl.insert_many([dict(temp=10), dict(temp=20), dict(temp=30)])
tbl.update_many([dict(id=1, temp=50), dict(id=3, temp=50)], "id")
# Ensure data has been updated.
assert tbl.find_one(id=1)["temp"] == tbl.find_one(id=3)["temp"]
def test_chunked_update(self):
tbl = self.db["update_many_test"]
tbl.insert_many(
[
dict(temp=10, location="asdf"),
dict(temp=20, location="qwer"),
dict(temp=30, location="asdf"),
]
)
chunked_tbl = chunked.ChunkedUpdate(tbl, "id")
chunked_tbl.update(dict(id=1, temp=50))
chunked_tbl.update(dict(id=2, location="asdf"))
chunked_tbl.update(dict(id=3, temp=50))
chunked_tbl.flush()
# Ensure data has been updated.
assert tbl.find_one(id=1)["temp"] == tbl.find_one(id=3)["temp"] == 50
assert (
tbl.find_one(id=2)["location"] == tbl.find_one(id=3)["location"] == "asdf"
) # noqa
def test_upsert_many(self):
# Also tests updating on records with different attributes
tbl = self.db["upsert_many_test"]
W = 100
tbl.upsert_many([dict(age=10), dict(weight=W)], "id")
assert tbl.find_one(id=1)["age"] == 10
tbl.upsert_many([dict(id=1, age=70), dict(id=2, weight=W / 2)], "id")
assert tbl.find_one(id=2)["weight"] == W / 2
def test_drop_operations(self):
assert self.tbl._table is not None, "table shouldn't be dropped yet"
self.tbl.drop()
assert self.tbl._table is None, "table should be dropped now"
assert list(self.tbl.all()) == [], self.tbl.all()
assert self.tbl.count() == 0, self.tbl.count()
def test_table_drop(self):
assert "weather" in self.db
self.db["weather"].drop()
assert "weather" not in self.db
def test_table_drop_then_create(self):
assert "weather" in self.db
self.db["weather"].drop()
assert "weather" not in self.db
self.db["weather"].insert({"foo": "bar"})
def test_columns(self):
cols = self.tbl.columns
assert len(list(cols)) == 4, "column count mismatch"
assert "date" in cols and "temperature" in cols and "place" in cols
def test_drop_column(self):
try:
self.tbl.drop_column("date")
assert "date" not in self.tbl.columns
except RuntimeError:
pass
def test_iter(self):
c = 0
for row in self.tbl:
c += 1
assert c == len(self.tbl)
def test_update(self):
date = datetime(2011, 1, 2)
res = self.tbl.update(
{"date": date, "temperature": -10, "place": TEST_CITY_1}, ["place", "date"]
)
assert res, "update should return True"
m = self.tbl.find_one(place=TEST_CITY_1, date=date)
assert m["temperature"] == -10, (
"new temp. should be -10 but is %d" % m["temperature"]
)
def test_create_column(self):
tbl = self.tbl
flt = self.db.types.float
tbl.create_column("foo", flt)
assert "foo" in tbl.table.c, tbl.table.c
assert isinstance(tbl.table.c["foo"].type, flt), tbl.table.c["foo"].type
assert "foo" in tbl.columns, tbl.columns
def test_ensure_column(self):
tbl = self.tbl
flt = self.db.types.float
tbl.create_column_by_example("foo", 0.1)
assert "foo" in tbl.table.c, tbl.table.c
assert isinstance(tbl.table.c["foo"].type, flt), tbl.table.c["bar"].type
tbl.create_column_by_example("bar", 1)
assert "bar" in tbl.table.c, tbl.table.c
assert isinstance(tbl.table.c["bar"].type, BIGINT), tbl.table.c["bar"].type
tbl.create_column_by_example("pippo", "test")
assert "pippo" in tbl.table.c, tbl.table.c
assert isinstance(tbl.table.c["pippo"].type, TEXT), tbl.table.c["pippo"].type
tbl.create_column_by_example("bigbar", 11111111111)
assert "bigbar" in tbl.table.c, tbl.table.c
assert isinstance(tbl.table.c["bigbar"].type, BIGINT), tbl.table.c[
"bigbar"
].type
tbl.create_column_by_example("littlebar", -11111111111)
assert "littlebar" in tbl.table.c, tbl.table.c
assert isinstance(tbl.table.c["littlebar"].type, BIGINT), tbl.table.c[
"littlebar"
].type
def test_key_order(self):
res = self.db.query("SELECT temperature, place FROM weather LIMIT 1")
keys = list(res.next().keys())
assert keys[0] == "temperature"
assert keys[1] == "place"
def test_empty_query(self):
empty = list(self.tbl.find(place="not in data"))
assert len(empty) == 0, empty
class Constructor(dict):
"""Very simple low-functionality extension to ``dict`` to
provide attribute access to dictionary contents"""
def __getattr__(self, name):
return self[name]
class RowTypeTestCase(unittest.TestCase):
def setUp(self):
self.db = connect(row_type=Constructor)
self.tbl = self.db["weather"]
for row in TEST_DATA:
self.tbl.insert(row)
def tearDown(self):
for table in self.db.tables:
self.db[table].drop()
def test_find_one(self):
self.tbl.insert(
{"date": datetime(2011, 1, 2), "temperature": -10, "place": "Berlin"}
)
d = self.tbl.find_one(place="Berlin")
assert d["temperature"] == -10, d
assert d.temperature == -10, d
d = self.tbl.find_one(place="Atlantis")
assert d is None, d
def test_find(self):
ds = list(self.tbl.find(place=TEST_CITY_1))
assert len(ds) == 3, ds
for item in ds:
assert isinstance(item, Constructor), item
ds = list(self.tbl.find(place=TEST_CITY_1, _limit=2))
assert len(ds) == 2, ds
for item in ds:
assert isinstance(item, Constructor), item
def test_distinct(self):
x = list(self.tbl.distinct("place"))
assert len(x) == 2, x
for item in x:
assert isinstance(item, Constructor), item
x = list(self.tbl.distinct("place", "date"))
assert len(x) == 6, x
for item in x:
assert isinstance(item, Constructor), item
def test_iter(self):
c = 0
for row in self.tbl:
c += 1
assert isinstance(row, Constructor), row
assert c == len(self.tbl)
if __name__ == "__main__":
unittest.main()
| []
| []
| [
"DATABASE_URL"
]
| [] | ["DATABASE_URL"] | python | 1 | 0 | |
tests/unit/modules/test_cloudProvisioning.py | import json
import os
import re
import shutil
import tempfile
import time
import yaml
from bzt import TaurusConfigError, TaurusException, NormalShutdown, AutomatedShutdown
from bzt.bza import Master, Test, MultiTest
from bzt.engine import ScenarioExecutor, Service, EXEC
from bzt.modules import FunctionalAggregator
from bzt.modules.aggregator import ConsolidatingAggregator, DataPoint, KPISet, AggregatorListener
from bzt.modules.blazemeter import CloudProvisioning, ResultsFromBZA, ServiceStubCaptureHAR, FunctionalBZAReader
from bzt.modules.blazemeter import CloudTaurusTest, CloudCollectionTest, BlazeMeterUploader
from bzt.modules.blazemeter import FUNC_API_TEST_TYPE, FUNC_GUI_TEST_TYPE
from bzt.modules.reporting import FinalStatus
from bzt.modules.selenium import SeleniumExecutor
from bzt.modules.apiritif import ApiritifTester
from bzt.utils import get_full_path, BetterDict
from tests.unit import BZTestCase, BZT_DIR, RESOURCES_DIR, BASE_CONFIG, ROOT_LOGGER, EngineEmul
from tests.unit.mocks import ModuleMock, BZMock
class TestCloudProvisioning(BZTestCase):
@staticmethod
def __get_user_info():
with open(RESOURCES_DIR + "json/blazemeter-api-user.json") as fhd:
return json.loads(fhd.read())
def setUp(self):
super(TestCloudProvisioning, self).setUp()
engine = EngineEmul()
engine.aggregator = ConsolidatingAggregator()
engine.aggregator.engine = engine
self.obj = CloudProvisioning()
self.obj.settings.merge({'delete-test-files': False})
self.obj.engine = engine
self.obj.browser_open = False
self.mock = BZMock(self.obj.user)
self.mock.mock_get.update({
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {"result": []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Cloud+Test': {"result": []},
})
self.mock.mock_post.update({
'https://a.blazemeter.com/api/v4/projects': {"result": {"id": 1, 'workspaceId': 1, 'limit': 1000}},
'https://a.blazemeter.com/api/v4/tests': {"result": {"id": 1, "configuration": {"type": "taurus"}}},
'https://a.blazemeter.com/api/v4/tests/1/files': {"result": {"id": 1}},
'https://a.blazemeter.com/api/v4/tests/1/start': {"result": {"id": 1}},
'https://a.blazemeter.com/api/v4/masters/1/stop': {"result": True},
})
def configure(self, engine_cfg=None, get=None, post=None, patch=None, add_config=True, add_settings=True):
if engine_cfg is None:
engine_cfg = {}
self.obj.engine.config.merge(engine_cfg)
if add_settings:
self.obj.settings["token"] = "FakeToken"
self.obj.settings["browser-open"] = False
self.obj.settings['default-location'] = "us-east-1"
if add_config:
self.obj.engine.config.merge({
"modules": {"mock": ModuleMock.__module__ + "." + ModuleMock.__name__},
"provisioning": "mock"})
self.obj.engine.unify_config()
self.mock.mock_get.update(get if get else {})
self.mock.mock_post.update(post if post else {})
self.mock.mock_patch.update(patch if patch else {})
self.mock.mock_patch.update({'https://a.blazemeter.com/api/v4/tests/1': {"result": {}}})
def test_old(self):
self.configure(
engine_cfg={
EXEC: [{
"executor": "mock",
"locations": {
"aws": 1},
"files": ModuleMock().get_resource_files()}]},
get={
'https://a.blazemeter.com/api/v4/masters/1/multi-tests': {"result": []},
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": {"sessions": []}},
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {"sessions": []}},
'https://a.blazemeter.com/api/v4/masters/1': {"result": {"note": "message"}},
'https://a.blazemeter.com/api/v4/masters/1/status': [
{"result": {"id": 1, "status": "CREATE"}},
{"result": {"id": 1, "status": "ENDED", "progress": 101}}]
},
post={
'https://a.blazemeter.com/api/v4/masters/1/public-token': {"result": {"publicToken": "token"}}
}
)
self.obj.public_report = True
self.obj.user.token = "test"
self.mock.apply(self.obj.user)
self.obj.prepare()
self.obj.startup()
self.obj.check()
self.obj._last_check_time = 0
self.obj.check()
self.obj.shutdown()
self.obj.post_process()
def test_simple(self):
self.configure(
engine_cfg={
EXEC: {
"executor": "mock",
"concurrency": 5500,
"locations": {
"us-east-1": 1,
"us-west": 2}}},
get={
'https://a.blazemeter.com/api/v4/masters/1/status': {"result": {"id": 1, "progress": 100}},
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": []},
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {}},
},
post={
}
) # terminate
self.obj.prepare()
self.assertEquals(1, self.obj.executors[0].execution['locations']['us-east-1'])
self.assertEquals(2, self.obj.executors[0].execution['locations']['us-west'])
self.obj.startup()
self.obj.check()
self.obj.shutdown()
self.obj.post_process()
def test_no_results(self):
self.configure(
engine_cfg={
EXEC: {
"executor": "mock",
"concurrency": 5500,
"locations": {
"us-east-1": 1,
"us-west": 2}}},
get={
'https://a.blazemeter.com/api/v4/masters/1/status': {"result": {"id": 1, "progress": 90}},
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": []},
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {"sessions": [{
"errors": [
{
"code": 70404,
"message": "Session ended without load report data",
"details": None
}
],
}]}},
},
post={
'https://a.blazemeter.com/api/v4/masters/1/terminate': {"result": []},
}
) # terminate
self.obj.prepare()
self.assertEquals(1, self.obj.executors[0].execution['locations']['us-east-1'])
self.assertEquals(2, self.obj.executors[0].execution['locations']['us-west'])
self.obj.startup()
self.obj.check()
self.obj.shutdown()
self.assertRaises(TaurusException, self.obj.post_process)
def test_detach(self):
self.configure(
engine_cfg={
EXEC: {
"executor": "mock",
"concurrency": 55,
"locations": {
"us-east-1": 1,
"us-west": 2}}},
get={
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {}},
}
)
self.obj.settings["detach"] = True
self.obj.prepare()
self.assertEqual(17, len(self.mock.requests))
self.obj.startup()
self.assertEqual(18, len(self.mock.requests))
self.obj.check()
self.obj.shutdown()
self.obj.post_process()
def test_no_settings(self):
self.configure(engine_cfg={EXEC: {"executor": "mock"}}, )
self.obj.prepare()
self.assertEquals(1, self.obj.executors[0].execution['locations']['us-east-1'])
def test_skip_reporting(self):
self.configure(
engine_cfg={
EXEC: {
"executor": "mock",
},
"modules": {
"blazemeter": ModuleMock.__module__ + "." + ModuleMock.__name__,
"second_reporter": ModuleMock.__module__ + "." + ModuleMock.__name__,
"third_reporter": ModuleMock.__module__ + "." + ModuleMock.__name__,
},
"reporting": ["blazemeter",
{"module": "blazemeter", "option": "value"},
"second_reporter",
{"module": "third_reporter"}]
},
)
self.obj.prepare()
modules = [reporter['module'] for reporter in self.obj.engine.config['reporting']]
self.assertEquals(modules, ['second_reporter', 'third_reporter'])
def test_widget_cloud_test(self):
test = Test(self.obj.user, {"id": 1, 'name': 'testname'})
self.obj.router = CloudTaurusTest(self.obj.user, test, None, None, None, False, self.obj.log)
self.configure(get={
'https://a.blazemeter.com/api/v4/masters/1/sessions': [
{"result": {"sessions": []}},
{"result": {"sessions": [{
"name": "executor/scenario/location",
"configuration": {
"location": "loc-name",
"serversCount": "10"}}]}}
]
})
self.obj.startup()
widget = self.obj.get_widget()
widget.update()
widget.update()
self.assertEqual("testname #1\n executor scenario:\n Agents in loc-name: 10\n", widget.text.get_text()[0])
def test_widget_cloud_collection(self):
test = MultiTest(self.obj.user, {"id": 1, 'name': 'testname'})
self.obj.router = CloudCollectionTest(self.obj.user, test, None, None, None, False, self.obj.log)
self.configure(post={
'https://a.blazemeter.com/api/v4/multi-tests/1/start?delayedStart=true': {"result": {
"id": 1,
"sessions": [{
"id": "session-id",
"locationId": "loc-name",
"readyStatus": {"servers": ["server" for _ in range(10)]}}]}}
}, get={
'https://a.blazemeter.com/api/v4/masters/1/status': {"result": {"status": "CREATED", "sessions": [{
"id": "session-id",
"locationId": "loc-name",
"readyStatus": {"servers": ["server" for _ in range(10)]},
"name": "loc-name/scenario",
"configuration": {}}]}},
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": {
"sessions": [{
"id": "session-id",
"name": "loc-name/scenario",
"configuration": {}}]}}
})
self.obj.startup()
self.obj.router.get_master_status()
widget = self.obj.get_widget()
widget.update()
self.assertEqual("testname #1\n scenario:\n Agents in loc-name: 10\n", widget.text.get_text()[0])
def test_delete_test_files(self):
self.configure(
engine_cfg={EXEC: {"executor": "mock"}},
get={
'https://a.blazemeter.com/api/v4/web/elfinder/1?cmd=open&target=s1_Lw': {"files": [
{
"hash": "hash1",
"name": "file1"
}, {
"hash": "hash1",
"name": "file2"}]
},
'https://a.blazemeter.com/api/v4/web/elfinder/1?target=s1_Lw&cmd=open': {"files": [
{
"hash": "hash1",
"name": "file1"
}, {
"hash": "hash1",
"name": "file2"}]
},
# deleting files with GET - ...!
'https://a.blazemeter.com/api/v4/web/elfinder/1?cmd=rm&targets[]=hash1&targets[]=hash1': {
"removed": ["hash1", "hash2"]
}
}
)
self.obj.settings.merge({'delete-test-files': True})
self.obj.prepare()
self.obj.log.info("Made requests: %s", self.mock.requests)
self.assertEquals('https://a.blazemeter.com/api/v4/web/elfinder/1?cmd=rm&targets[]=hash1&targets[]=hash1',
self.mock.requests[13]['url'])
def test_cloud_config_cleanup_simple(self):
self.configure(
engine_cfg={
EXEC: {
"concurrency": {
"local": 1,
"cloud": 10},
"locations": {
"us-east-1": 1,
"us-west": 2}},
"modules": {
"jmeter": {
"class": ModuleMock.__module__ + "." + ModuleMock.__name__,
"version": "some_value"},
"blazemeter": {
"class": ModuleMock.__module__ + "." + ModuleMock.__name__,
"strange_param": False,
},
"cloud": {
"class": ModuleMock.__module__ + "." + ModuleMock.__name__,
"name": "value",
"token": "secret_key"
}},
"provisioning": "cloud",
"settings": {
"default-executor": "jmeter"
}
})
self.obj.engine.config["provisioning"] = "cloud"
self.obj.router = CloudTaurusTest(self.obj.user, None, None, "name", None, False, self.obj.log)
super(CloudProvisioning, self.obj).prepare() # init executors
cloud_config = self.obj.prepare_cloud_config()
cloud_jmeter = cloud_config.get("modules").get("jmeter")
self.assertNotIn("class", cloud_jmeter)
self.assertIn("version", cloud_jmeter)
self.assertNotIn("token", cloud_config.get("modules").get("cloud"))
def test_cloud_config_cleanup_short_execution(self):
self.configure(
engine_cfg={
EXEC: {
"concurrency": 33,
"scenario": "sc1"},
"scenarios": {
"sc1": {
"requests": [
"http://blazedemo.com"]}},
"modules": {
"jmeter": {
"class": ModuleMock.__module__ + "." + ModuleMock.__name__,
"just_option": "just_value"},
"other": {
"class": ModuleMock.__module__ + "." + ModuleMock.__name__}},
"settings": {
"default-executor": "jmeter"},
"cli": {"remove": "me"},
"cli-aliases": {"remove": "me"},
}
)
self.obj.router = CloudTaurusTest(self.obj.user, None, None, "name", None, False, self.obj.log)
super(CloudProvisioning, self.obj).prepare() # init executors
self.obj.get_rfiles()
# let's check empty files list filtration..
self.obj.engine.config.get(EXEC)[0]["files"] = []
cloud_config = self.obj.prepare_cloud_config()
self.assertIsNone(cloud_config.get("cli", None), None)
self.assertIsNone(cloud_config.get("cli-aliases", None), None)
cloud_execution = cloud_config.get(EXEC)[0]
cloud_modules = cloud_config.get("modules")
target_execution = {ScenarioExecutor.CONCURR: 33, "scenario": "sc1", "executor": "jmeter"}
target_modules = {"jmeter": {"just_option": "just_value"}}
self.assertEqual(cloud_execution, BetterDict.from_dict(target_execution))
self.assertEqual(cloud_modules, BetterDict.from_dict(target_modules))
def test_cloud_config_cleanup_empty_class(self):
strange_module = "bla_ze_me_ter"
self.configure(
engine_cfg={
EXEC: {
"concurrency": {
"local": 1,
"cloud": 10}},
"modules": {
"jmeter": {
"class": ModuleMock.__module__ + "." + ModuleMock.__name__,
"version": "some_value"},
strange_module: {
# "class": ModuleMock.__module__ + "." + ModuleMock.__name__,
"strange_param": False}
},
"settings": {
"default-executor": "jmeter"
}
}
)
self.obj.router = CloudTaurusTest(self.obj.user, None, None, "name", None, False, self.obj.log)
super(CloudProvisioning, self.obj).prepare() # init executors
self.obj.get_rfiles() # create runners
cloud_config = self.obj.prepare_cloud_config()
self.assertNotIn(strange_module, cloud_config.get("modules"))
def test_cloud_config_cleanup_selenium(self):
self.configure(
engine_cfg={
EXEC: [{
"executor": "selenium",
"concurrency": {
"local": 1,
"cloud": 10},
"locations": {
"us-east-1": 1,
"us-west": 2},
"scenario": {"requests": ["http://blazedemo.com"]}},
{
"executor": "selenium",
"runner": "apiritif",
"concurrency": {
"local": 1,
"cloud": 10},
"locations": {
"us-east-1": 1,
"us-west": 2},
"scenario": {"requests": ["http://blazedemo.com"]}}
],
"modules": {
"selenium": {
"class": SeleniumExecutor.__module__ + "." + SeleniumExecutor.__name__,
"virtual-display": False},
"apiritif": {
"class": ApiritifTester.__module__ + "." + ApiritifTester.__name__,
"verbose": False
},
"blazemeter": {
"class": BlazeMeterUploader.__module__ + "." + BlazeMeterUploader.__name__,
"strange_param": False
},
"unused_module": ModuleMock.__module__ + "." + ModuleMock.__name__,
"private_mod": {
"class": ModuleMock.__module__ + "." + ModuleMock.__name__,
"send-to-blazemeter": True
}
},
"settings": {
"default-executor": "jmeter",
"aggregator": "consolidator"
}
},
)
self.obj.router = CloudTaurusTest(self.obj.user, None, None, "name", None, False, self.obj.log)
super(CloudProvisioning, self.obj).prepare() # init executors
self.obj.get_rfiles() # create runners
cloud_config = self.obj.prepare_cloud_config()
target = BetterDict.from_dict({
'blazemeter': {'strange_param': False},
'selenium': {'virtual-display': False},
'apiritif': {'verbose': False},
'private_mod': {'class': 'tests.unit.mocks.ModuleMock', 'send-to-blazemeter': True}
})
self.assertEqual(target, cloud_config.get("modules"))
def test_merge_settings(self):
target_selenium_class = SeleniumExecutor.__module__ + "." + SeleniumExecutor.__name__
target_apiritif_class = ApiritifTester.__module__ + "." + ApiritifTester.__name__
self.configure(
engine_cfg={
EXEC: [{
"executor": "selenium",
"runner": "apiritif",
"scenario": {"requests": ["http://blazedemo.com"]}}],
"modules": {
"selenium": {"class": target_selenium_class},
"apiritif": {"class": target_apiritif_class}}})
self.obj.router = CloudTaurusTest(self.obj.user, None, None, "name", None, False, self.obj.log)
super(CloudProvisioning, self.obj).prepare() # init executors
self.obj.get_rfiles() # create runners
selenium_class = self.obj.engine.config.get("modules").get("selenium").get("class")
apiritif_class = self.obj.engine.config.get("modules").get("apiritif").get("class")
self.assertNotEqual(selenium_class, apiritif_class)
self.assertEqual(selenium_class, target_selenium_class)
self.assertEqual(apiritif_class, target_apiritif_class)
def test_default_test_type_cloud(self):
self.configure(engine_cfg={EXEC: {"executor": "mock"}}, )
self.obj.prepare()
self.assertIsInstance(self.obj.router, CloudTaurusTest)
def test_type_forced(self):
self.obj.user.token = object()
self.configure(
add_settings=False,
engine_cfg={EXEC: {"executor": "mock"}},
get={
'https://a.blazemeter.com/api/v4/projects?projectId=1': {'result': [{'id': 1,
'workspaceId': 1}]},
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {"result": [{
"id": 1,
"projectId": 1,
"name": "Taurus Cloud Test",
"configuration": {"type": "taurus"}}]}
},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
},
patch={
'https://a.blazemeter.com/api/v4/multi-tests/1': {}
}
)
self.obj.prepare()
self.assertIsInstance(self.obj.router, CloudCollectionTest)
def test_detect_test_type_collection(self):
self.obj.user.token = object()
self.configure(
add_settings=False,
engine_cfg={EXEC: {"executor": "mock"}},
get={
'https://a.blazemeter.com/api/v4/projects?workspaceId=1': {'result': [{'id': 1,
'workspaceId': 1}]},
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {"result": [{
"id": 1,
"projectId": 1,
"name": "Taurus Cloud Test",
"configuration": {"type": "taurus"}}]}
},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
},
patch={
'https://a.blazemeter.com/api/v4/multi-tests/1': {}
}
)
self.obj.prepare()
self.assertIsInstance(self.obj.router, CloudCollectionTest)
def test_detect_test_type_cloud(self):
self.configure(engine_cfg={EXEC: {"executor": "mock"}}, )
self.obj.prepare()
self.assertIsInstance(self.obj.router, CloudTaurusTest)
def test_full_collection(self):
self.obj.user.token = object()
self.configure(
add_settings=False,
engine_cfg={
EXEC: {
"executor": "mock",
"concurrency": 5500,
"locations": {
"us-east-1": 1,
"us-west": 2}}
},
get={
'https://a.blazemeter.com/api/v4/masters/1/status': {"result": {"status": "CREATED"}},
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": {"sessions": []}},
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {}},
},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
'https://a.blazemeter.com/api/v4/multi-tests': {"result": {"id": 1}},
'https://a.blazemeter.com/api/v4/multi-tests/1/start?delayedStart=true': {"result": {"id": 1}}
}
)
self.obj.settings["use-deprecated-api"] = False
self.obj.prepare()
self.assertEquals(1, self.obj.executors[0].execution['locations']['us-east-1'])
self.assertEquals(2, self.obj.executors[0].execution['locations']['us-west'])
self.obj.startup()
self.obj.check()
self.obj.shutdown()
self.obj.post_process()
def test_create_project(self):
self.configure(engine_cfg={EXEC: {"executor": "mock"}}, )
self.obj.settings.merge({"delete-test-files": False, "project": "myproject"})
self.obj.prepare()
self.assertEquals('https://a.blazemeter.com/api/v4/projects', self.mock.requests[6]['url'])
self.assertEquals('POST', self.mock.requests[6]['method'])
def test_create_project_test_exists(self):
self.configure(engine_cfg={EXEC: {"executor": "mock"}}, get={
'https://a.blazemeter.com/api/v4/tests?workspaceId=1&name=Taurus+Cloud+Test': {"result": [
{"id": 1, 'projectId': 1, 'name': 'Taurus Cloud Test', 'configuration': {'type': 'taurus'}}
]},
'https://a.blazemeter.com/api/v4/projects?workspaceId=1': [
{'result': []},
{'result': [{'id': 1}]}
],
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
})
self.obj.settings.merge({"delete-test-files": False, "project": "myproject"})
self.obj.prepare()
self.assertEquals('https://a.blazemeter.com/api/v4/projects', self.mock.requests[6]['url'])
self.assertEquals('POST', self.mock.requests[6]['method'])
self.assertEquals('https://a.blazemeter.com/api/v4/tests', self.mock.requests[10]['url'])
self.assertEquals('POST', self.mock.requests[10]['method'])
def test_reuse_project(self):
self.obj.user.token = object()
self.configure(
add_settings=False,
engine_cfg={EXEC: {"executor": "mock"}},
get={
"https://a.blazemeter.com/api/v4/projects?workspaceId=1": {
"result": [{"id": 1, "name": "myproject"}]},
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {"result": [{
"id": 1,
"projectId": 1,
"name": "Taurus Cloud Test",
"configuration": {"type": "taurus"}}]}
},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
},
patch={
'https://a.blazemeter.com/api/v4/multi-tests/1': {}
}
)
self.obj.settings.merge({"delete-test-files": False, "project": "myproject"})
self.obj.prepare()
self.assertEquals('https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test',
self.mock.requests[7]['url'])
def test_reuse_project_id(self):
self.obj.user.token = object()
self.configure(
add_settings=False,
engine_cfg={EXEC: {"executor": "mock"}},
get={
"https://a.blazemeter.com/api/v4/projects?workspaceId=1&limit=1000": {
"result": [{"id": 1, "name": "myproject"}]},
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {
"result": [{"id": 1, "name": "Taurus Cloud Test"}]
}
},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
},
patch={
'https://a.blazemeter.com/api/v4/multi-tests/1': {}
}
)
self.obj.settings.merge({"delete-test-files": False, "project": 1})
self.obj.prepare()
for request in self.mock.requests:
self.assertFalse(
request['url'] == 'https://a.blazemeter.com/api/v4/projects' and request['method'] == 'POST')
def test_create_collection(self):
self.obj.user.token = object()
self.configure(
add_settings=False,
engine_cfg={EXEC: {"executor": "mock"}},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
'https://a.blazemeter.com/api/v4/multi-tests/1': {},
'https://a.blazemeter.com/api/v4/multi-tests': {"result": {}}
}
)
self.obj.settings.merge({"delete-test-files": False, "use-deprecated-api": False, 'dedicated-ips': True})
self.obj.prepare()
self.assertIsInstance(self.obj.router, CloudCollectionTest)
def test_toplevel_locations(self):
self.obj.user.token = object()
self.configure(
add_settings=False,
engine_cfg={
EXEC: {
"executor": "mock",
"concurrency": 5500},
"locations": {
"us-east-1": 1,
"us-west": 2},
"locations-weighted": True},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
'https://a.blazemeter.com/api/v4/multi-tests/1': {},
'https://a.blazemeter.com/api/v4/multi-tests': {"result": {}}
}
)
self.obj.settings["use-deprecated-api"] = False
self.obj.prepare()
conf = yaml.full_load(open(os.path.join(self.obj.engine.artifacts_dir, "cloud.yml")))
self.assertIn('locations', conf)
self.assertIn('locations-weighted', conf)
self.assertEqual(conf['locations']['us-east-1'], 1)
self.assertEqual(conf['locations']['us-west'], 2)
self.assertNotIn('locations', conf['execution'][0])
def test_nonexistent_location(self):
self.configure(
engine_cfg={EXEC: {"executor": "mock", }, "locations": {"us-not-found": 1}},
)
self.obj.settings["use-deprecated-api"] = False
self.assertRaises(TaurusConfigError, self.obj.prepare)
def test_sandbox_default_location(self):
self.configure(
add_settings=False,
engine_cfg={EXEC: {"executor": "mock"}},
)
self.obj.user.token = "key"
self.obj.prepare()
exec_locations = self.obj.executors[0].execution['locations']
self.assertEquals(1, exec_locations['harbor-sandbox'])
def test_nosandbox_default_location(self):
locs = [{'id': 'loc1', 'sandbox': False, 'title': 'L1'}, {'id': 'loc2', 'sandbox': False, 'title': 'L2'}, ]
self.configure(
add_settings=False,
engine_cfg={EXEC: {"executor": "mock"}},
get={
'https://a.blazemeter.com/api/v4/workspaces/1': {"result": {"locations": locs}},
}
)
self.obj.user.token = "key"
self.obj.settings['default-location'] = "some-nonavailable"
self.obj.prepare()
exec_locations = self.obj.executors[0].execution['locations']
self.assertEquals(1, exec_locations['loc1'])
def test_collection_defloc_sandbox(self):
self.obj.user.token = object()
self.configure(
add_settings=False,
engine_cfg={EXEC: {"executor": "mock", }},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
'https://a.blazemeter.com/api/v4/multi-tests/1': {},
'https://a.blazemeter.com/api/v4/multi-tests': {"result": {}}
}
)
self.obj.settings["use-deprecated-api"] = False
self.obj.prepare()
exec_locations = self.obj.executors[0].execution['locations']
expected_location = 'harbor-sandbox'
self.assertIn(expected_location, exec_locations)
self.assertEquals(1, exec_locations[expected_location])
def test_locations_on_both_levels(self):
self.obj.user.token = object()
self.configure(
add_settings=False,
engine_cfg={
EXEC: [{
"executor": "mock",
"concurrency": 5500,
"locations": {"us-east-1": 1}}],
"locations": {"aws": 1}},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
'https://a.blazemeter.com/api/v4/multi-tests/1': {},
'https://a.blazemeter.com/api/v4/multi-tests': {"result": {}}
}
)
self.sniff_log(self.obj.log)
self.obj.settings["use-deprecated-api"] = False
self.obj.prepare()
cloud_config = yaml.full_load(open(os.path.join(self.obj.engine.artifacts_dir, "cloud.yml")))
self.assertNotIn("locations", cloud_config)
for execution in cloud_config["execution"]:
self.assertIn("locations", execution)
log_buff = self.log_recorder.warn_buff.getvalue()
self.assertIn("Each execution has locations specified, global locations won't have any effect", log_buff)
def test_locations_global(self):
self.obj.user.token = object()
self.configure(
add_settings=False,
engine_cfg={
EXEC: [{
"executor": "mock",
"concurrency": 5500,
}],
"locations": {"aws": 1}},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
'https://a.blazemeter.com/api/v4/multi-tests/1': {},
'https://a.blazemeter.com/api/v4/multi-tests': {"result": {}}
}
)
self.sniff_log(self.obj.log)
self.obj.settings["use-deprecated-api"] = True
self.obj.settings["cloud-mode"] = "taurusCloud"
self.obj.prepare()
self.assertIsInstance(self.obj.router, CloudTaurusTest)
cloud_config = yaml.full_load(open(os.path.join(self.obj.engine.artifacts_dir, "cloud.yml")))
self.assertIn("locations", cloud_config)
for execution in cloud_config["execution"]:
self.assertNotIn("locations", execution)
def test_collection_simultaneous_start(self):
self.obj.user.token = object()
self.configure(
add_settings=False,
engine_cfg={
EXEC: {
"executor": "mock",
"concurrency": 5500,
"locations": {
"us-east-1": 1,
"us-west": 1}}},
get={
'https://a.blazemeter.com/api/v4/masters/1/status': [
{"result": {
"id": id(self.obj),
"sessions": [
{"id": "s1", "status": "JMETER_CONSOLE_INIT"},
{"id": "s2", "status": "INIT_SCRIPT"}]}},
{"result": {
"id": id(self.obj),
"sessions": [
{"id": "s1", "status": "JMETER_CONSOLE_INIT"},
{"id": "s2", "status": "JMETER_CONSOLE_INIT"}]}},
{"result": {
"id": id(self.obj),
"sessions": [
{"id": "s1", "status": "JMETER_CONSOLE_INIT"},
{"id": "s2", "status": "JMETER_CONSOLE_INIT"}]}},
{"result": {
"id": id(self.obj),
"status": "ENDED",
"sessions": [
{"id": "s1", "status": "JMETER_CONSOLE_INIT"},
{"id": "s2", "status": "JMETER_CONSOLE_INIT"}]}},
],
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": {"sessions": []}},
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {"sessions": []}},
},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
'https://a.blazemeter.com/api/v4/multi-tests/1': {},
'https://a.blazemeter.com/api/v4/multi-tests': {"result": {"id": 1}},
'https://a.blazemeter.com/api/v4/multi-tests/1/start?delayedStart=true': {"result": {"id": 1}},
'https://a.blazemeter.com/api/v4/masters/1/force-start': {"result": {"id": 1}},
'https://a.blazemeter.com/api/v4/multi-tests/1/stop': {"result": {"id": 1}}
}
)
self.obj.settings["check-interval"] = "0ms" # do not skip checks
self.obj.settings["use-deprecated-api"] = False
self.obj.prepare()
self.obj.startup()
self.obj.check()
self.obj.check() # this one should trigger force start
self.obj.check()
self.obj.shutdown()
self.obj.post_process()
self.assertIn('masters/1/force-start', ''.join([x['url'] for x in self.mock.requests]))
def test_terminate_only(self):
""" test is terminated only when it was started and didn't finished """
self.obj.user.token = object()
cls = ServiceStubCaptureHAR.__module__ + "." + ServiceStubCaptureHAR.__name__
self.configure(
add_settings=False,
engine_cfg={
EXEC: {
"executor": "mock",
"concurrency": 5500,
"locations": {
"us-east-1": 1,
"us-west": 1}},
Service.SERV: ["capturehar"],
"modules": {"capturehar": {"class": cls}}},
get={
'https://a.blazemeter.com/api/v4/masters/1/status': [
{"result": {
"id": id(self.obj),
"sessions": [
{"id": "s1", "status": "JMETER_CONSOLE_INIT", "locationId": "some"},
{"id": "s2", "status": "JMETER_CONSOLE_INIT"}]}},
{"result": {"progress": 140, "status": "ENDED"}}, # status should trigger shutdown
],
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": {"sessions": [{'id': "s1"}]}},
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {
"note": "msg",
"sessions": [{'id': "s1"}]}
},
'https://a.blazemeter.com/api/v4/masters/1': {"result": {"id": 1, "note": "msg"}},
'https://a.blazemeter.com/api/v4/sessions/s1/reports/logs': {"result": {"data": [
{
'filename': "artifacts.zip",
'dataUrl': "file://" + RESOURCES_DIR + 'artifacts-1.zip'
}
]}}
},
post={
'https://a.blazemeter.com/api/v4/web/elfinder/taurus_%s' % id(self.obj.user.token): {},
'https://a.blazemeter.com/api/v4/multi-tests/taurus-import': {"result": {
"name": "Taurus Collection", "items": []
}},
'https://a.blazemeter.com/api/v4/multi-tests/1': {},
'https://a.blazemeter.com/api/v4/multi-tests': {"result": {'id': 1, 'name': 'testname'}},
'https://a.blazemeter.com/api/v4/multi-tests/1/start?delayedStart=true': {"result": {"id": 1}},
'https://a.blazemeter.com/api/v4/masters/1/force-start': {"result": {"id": 1}},
'https://a.blazemeter.com/api/v4/multi-tests/1/stop': {"result": {"id": 1}}
}
)
self.obj.settings["check-interval"] = "0ms" # do not skip checks
self.obj.settings["use-deprecated-api"] = False
self.sniff_log(self.obj.log)
self.obj.prepare()
self.obj.startup()
self.obj.check() # this one should trigger force start
self.assertTrue(self.obj.check())
self.obj.shutdown()
self.obj.post_process()
self.assertEqual(22, len(self.mock.requests))
self.assertIn("Cloud test has probably failed with message: msg", self.log_recorder.warn_buff.getvalue())
def test_cloud_paths(self):
"""
Test different executor/path combinations for correct return values of get_resources_files
"""
self.configure(
add_config=False, add_settings=False,
) # upload files
# FIXME: refactor this method!
self.sniff_log(self.obj.log)
self.obj.engine.configure([BASE_CONFIG, RESOURCES_DIR + 'yaml/resource_files.yml'], read_config_files=False)
self.obj.engine.unify_config()
self.obj.settings = self.obj.engine.config['modules']['cloud']
self.obj.settings.merge({'delete-test-files': False})
# list of existing files in $HOME
pref = 'file-in-home-'
files_in_home = ['00.jmx', '01.csv', '02.res', '03.java', '04.scala', '05.jar', '06.py',
'07.properties', '08.py', '09.siege', '10.xml', '11.ds', '12.xml',
'13.src', '14.java', '15.xml', '16.java', '17.js', '18.rb', '19.jar', '20.jar']
files_in_home = [pref + _file for _file in files_in_home]
back_home = os.environ.get('HOME', '')
temp_home = tempfile.mkdtemp()
try:
os.environ['HOME'] = temp_home
files_in_home = [{'shortname': os.path.join('~', _file),
'fullname': get_full_path(os.path.join('~', _file))}
for _file in files_in_home]
shutil.copyfile(RESOURCES_DIR + 'jmeter/jmx/dummy.jmx', files_in_home[0]['fullname'])
dir_path = get_full_path(os.path.join('~', 'example-of-directory'))
os.mkdir(dir_path)
for _file in files_in_home[1:]:
open(_file['fullname'], 'a').close()
self.obj.engine.file_search_paths = ['tests', os.path.join('tests', 'unit')] # config not in cwd
# 'files' are treated similar in all executors so check only one
self.obj.engine.config[EXEC][0]['files'] = [
os.path.join(BZT_DIR, 'tests', 'unit', 'test_CLI.py'), # full path
files_in_home[2]['shortname'], # path from ~
os.path.join('resources', 'jmeter', 'jmeter-loader.bat'), # relative path
'mocks.py', # only basename (look at file_search_paths)
'~/example-of-directory'] # dir
self.obj.prepare()
debug = self.log_recorder.debug_buff.getvalue().split('\n')
str_files = [line for line in debug if 'Replace file names in config' in line]
self.assertEqual(1, len(str_files))
res_files = [_file for _file in str_files[0].split('\'')[1::2]]
half = int(len(res_files) / 2)
old_names = res_files[:half]
new_names = res_files[half:]
names = list(zip(old_names, new_names))
with open(self.obj.engine.artifacts_dir + '/cloud.yml') as cl_file:
str_cfg = cl_file.read()
archive_found = False
for old_name, new_name in names:
if new_name.endswith('.zip'):
archive_found = True
# all resources on the disk, dir has been packed
path_to_file = get_full_path(self.obj.engine.find_file(old_name))
msg = 'File %s (%s) not found on disk' % (old_name, path_to_file)
self.assertTrue(os.path.exists(path_to_file), msg)
msg = 'Short name %s not found in modified config' % new_name
self.assertIn(new_name, str_cfg, msg) # all short names in config
if new_name != old_name:
msg = 'Long name %s found in config' % old_name
self.assertNotIn(old_name, str_cfg, msg) # no one long name in config
self.assertTrue(archive_found)
target_names = { # source:
'dummy.jmx', # execution 0 (script)
'test_CLI.py', 'file-in-home-02.res', # 0 (files)
'jmeter-loader.bat', 'mocks.py', # 0 (files)
'example-of-directory.zip', # 0 (files)
'files_paths.jmx', # 1 (script)
'file-in-home-01.csv', 'body-file.dat', # 1 (from jmx)
'BlazeDemo.java', # 2 (script)
'file-in-home-05.jar', 'dummy.jar', # 2 (additional-classpath)
'not-jmx.xml', # 2 (testng-xml)
'file-in-home-03.java', # 3 (script)
'file-in-home-12.xml', # 3 (testng-xml)
'BasicSimulation.scala', # 4 (script)
'file-in-home-04.scala', # 5 (script)
'helloworld.py', # 6 (script)
'grinder.base.properties', # 6 (properties-file)
'file-in-home-06.py', # 7 (script)
'file-in-home-07.properties', # 7 (properties-file)
'simple.py', # 8 (script)
'file-in-home-08.py', # 9 (script)
'jmeter-loader.bat', # 10 (data-sources)
'file-in-home-11.ds', # 10 (data-sources)
'url-file', # 11 (script)
'file-in-home-09.siege', # 12 (script)
'http_simple.xml', # 13 (script)
'file-in-home-10.xml', # 14 (script)
'file-in-home-00.jmx', # 17 (script)
'TestBlazemeterFail.java', # 18 (script)
'file-in-home-20.jar', # 18 (additional-classpath)
'file-in-home-14.java', # 19 (script)
'TestNGSuite.java', # 20 (script)
'testng.xml', # 20 (detected testng-xml from 'files')
'file-in-home-15.xml', # 21 (testng-xml)
'file-in-home-16.java', # 21 (script)
'bd_scenarios.js', # 22 (script)
'file-in-home-17.js', # 23 (sript)
'example_spec.rb', # 24 (script)
'file-in-home-18.rb', # 25 (sript)
'file-in-home-19.jar', # global testng settings (additional-classpath)
'variable_file_upload.jmx',
}
self.assertEqual(set(new_names), target_names)
finally:
os.environ['HOME'] = back_home
shutil.rmtree(temp_home)
def test_check_interval(self):
self.configure(
engine_cfg={
EXEC: {"executor": "mock", }},
get={
'https://a.blazemeter.com/api/v4/masters/1/status': [
{"result": {"id": id(self.obj)}},
{"result": {"id": id(self.obj), 'progress': 100}},
{"result": {"id": id(self.obj), 'progress': 140}},
],
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": []},
'https://a.blazemeter.com/api/v4/data/labels?master_id=1': {"result": [
{"id": "ALL", "name": "ALL"},
{"id": "e843ff89a5737891a10251cbb0db08e5", "name": "http://blazedemo.com/"}
]},
'https://a.blazemeter.com/api/v4/data/kpis?interval=1&from=0&master_ids%5B%5D=1&kpis%5B%5D=t&kpis%5B%5D=lt&kpis%5B%5D=by&kpis%5B%5D=n&kpis%5B%5D=ec&kpis%5B%5D=ts&kpis%5B%5D=na&labels%5B%5D=ALL&labels%5B%5D=e843ff89a5737891a10251cbb0db08e5': {
"api_version": 2,
"error": None,
"result": [
{
"labelId": "ALL",
"labelName": "ALL",
"label": "ALL",
"kpis": [
{
"n": 15,
"na": 2,
"ec": 0,
"ts": 1,
"t_avg": 558,
"lt_avg": 25.7,
"by_avg": 0,
"n_avg": 15,
"ec_avg": 0
}, {
"n": 7,
"na": 4,
"ec": 0,
"ts": 1,
"t_avg": 88.1,
"lt_avg": 11.9,
"by_avg": 0,
"n_avg": 7,
"ec_avg": 0
}]
}, {
"labelId": "e843ff89a5737891a10251cbb0db08e5",
"labelName": "http://blazedemo.com/",
"label": "http://blazedemo.com/",
"kpis": [
{
"n": 15,
"na": 2,
"ec": 0,
"ts": 2,
"t_avg": 558,
"lt_avg": 25.7,
"by_avg": 0,
"n_avg": 15,
"ec_avg": 0
}, {
"n": 7,
"na": 4,
"ec": 0,
"ts": 2,
"t_avg": 88.1,
"lt_avg": 11.9,
"by_avg": 0,
"n_avg": 7,
"ec_avg": 0
}]}]},
'https://a.blazemeter.com/api/v4/data/kpis?interval=1&from=2&master_ids%5B%5D=1&kpis%5B%5D=t&kpis%5B%5D=lt&kpis%5B%5D=by&kpis%5B%5D=n&kpis%5B%5D=ec&kpis%5B%5D=ts&kpis%5B%5D=na&labels%5B%5D=ALL&labels%5B%5D=e843ff89a5737891a10251cbb0db08e5': {
"result": []},
'https://a.blazemeter.com/api/v4/masters/1/reports/aggregatereport/data': {
"api_version": 2,
"error": None,
"result": [
{
"labelId": "ALL",
"labelName": "ALL",
"samples": 152,
"avgResponseTime": 786,
"90line": 836,
"95line": 912,
"99line": 1050,
"minResponseTime": 531,
"maxResponseTime": 1148,
"avgLatency": 81,
"geoMeanResponseTime": None,
"stDev": 108,
"duration": 119,
"avgBytes": 0,
"avgThroughput": 1.2773109243697,
"medianResponseTime": 0,
"errorsCount": 0,
"errorsRate": 0,
"hasLabelPassedThresholds": None
}, {
"labelId": "e843ff89a5737891a10251cbb0db08e5",
"labelName": "http://blazedemo.com/",
"samples": 152,
"avgResponseTime": 786,
"90line": 836,
"95line": 912,
"99line": 1050,
"minResponseTime": 531,
"maxResponseTime": 1148,
"avgLatency": 81,
"geoMeanResponseTime": None,
"stDev": 108,
"duration": 119,
"avgBytes": 0,
"avgThroughput": 1.2773109243697,
"medianResponseTime": 0,
"errorsCount": 0,
"errorsRate": 0,
"hasLabelPassedThresholds": None
}]},
'https://a.blazemeter.com/api/v4/masters/1/reports/errorsreport/data?noDataError=false': {
'result': []}})
self.obj.settings["check-interval"] = "1s"
self.obj.prepare()
self.obj.startup()
self.obj.log.info("Check 1")
self.obj.check() # this one should work
self.obj.engine.aggregator.check()
self.obj.log.info("Check 2")
self.obj.check() # this one should be skipped
self.obj.engine.aggregator.check()
time.sleep(1.5)
self.obj.log.info("Check 3")
self.obj.check() # this one should work
self.obj.engine.aggregator.check()
self.obj.log.info("Check 4")
self.obj.check() # this one should skip
self.obj.engine.aggregator.check()
self.assertEqual(32, len(self.mock.requests))
def test_dump_locations(self):
self.configure()
self.sniff_log(self.obj.log)
self.obj.settings["dump-locations"] = True
self.obj.settings["use-deprecated-api"] = True
try:
self.assertRaises(NormalShutdown, self.obj.prepare)
except KeyboardInterrupt as exc:
raise AssertionError(type(exc))
warnings = self.log_recorder.warn_buff.getvalue()
self.assertIn("Dumping available locations instead of running the test", warnings)
self.assertIn("us-west", warnings)
self.assertIn("us-east-1", warnings)
self.assertIn("harbor-sandbox", warnings)
self.obj.post_process()
def test_dump_locations_new_style(self):
self.sniff_log(self.obj.log)
self.configure()
self.obj.settings["dump-locations"] = True
self.obj.settings["use-deprecated-api"] = False
try:
self.assertRaises(NormalShutdown, self.obj.prepare)
except KeyboardInterrupt as exc:
raise AssertionError(type(exc))
warnings = self.log_recorder.warn_buff.getvalue()
self.assertIn("Dumping available locations instead of running the test", warnings)
self.assertIn("us-west", warnings)
self.assertIn("us-east-1", warnings)
self.assertIn("harbor-sandbox", warnings)
self.obj.post_process()
def test_settings_from_blazemeter_mod(self):
self.configure(
add_settings=False,
engine_cfg={
EXEC: {
"executor": "mock",
"concurrency": 5500,
"locations": {
"us-east-1": 1,
"us-west": 1}},
"modules": {
"blazemeter": {
"class": ModuleMock.__module__ + "." + ModuleMock.__name__,
"token": "bmtoken",
"detach": True,
"browser-open": None,
"check-interval": 10.0}}},
) # upload files
# these should override 'blazemeter' settings
self.obj.settings["check-interval"] = 20.0
self.obj.settings["browser-open"] = "both"
self.obj.prepare()
self.assertEqual(self.obj.detach, True)
self.assertEqual(self.obj.browser_open, "both")
self.assertEqual(self.obj.user.token, "bmtoken")
self.assertEqual(self.obj.check_interval, 20.0)
self.assertEqual(17, len(self.mock.requests))
def test_public_report(self):
self.configure(
engine_cfg={
EXEC: {
"executor": "mock",
"concurrency": 1,
"locations": {
"us-west": 2
}}},
post={
'https://a.blazemeter.com/api/v4/masters/1/public-token': {"result": {"publicToken": "publicToken"}}
},
get={
'https://a.blazemeter.com/api/v4/masters/1/status': {"result": {"status": "CREATED", "progress": 100}},
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": {"sessions": []}},
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {}},
}
)
self.sniff_log(self.obj.log)
self.obj.settings['public-report'] = True
self.obj.prepare()
self.obj.startup()
self.obj.check()
self.obj.shutdown()
self.obj.post_process()
log_buff = self.log_recorder.info_buff.getvalue()
log_line = "Public report link: https://a.blazemeter.com/app/?public-token=publicToken#/masters/1/summary"
self.assertIn(log_line, log_buff)
def test_functional_test_creation(self):
self.obj.engine.aggregator = FunctionalAggregator()
self.configure(engine_cfg={EXEC: {"executor": "mock"}}, get={
'https://a.blazemeter.com/api/v4/tests?workspaceId=1&name=Taurus+Cloud+Test': {"result": [
{"id": 1, 'projectId': 1, 'name': 'Taurus Cloud Test', 'configuration': {'type': 'taurus'}}
]},
'https://a.blazemeter.com/api/v4/projects?workspaceId=1': [
{'result': []},
{'result': [{'id': 1}]}
],
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
}, post={
'https://a.blazemeter.com/api/v4/tests/1/start?functionalExecution=true': {'result': {'id': 'mid'}}
})
self.obj.settings.merge({"delete-test-files": False, "project": "myproject"})
self.obj.prepare()
self.obj.startup()
reqs = self.mock.requests
self.assertEqual(reqs[10]['url'], 'https://a.blazemeter.com/api/v4/tests')
self.assertEqual(reqs[10]['method'], 'POST')
data = json.loads(reqs[10]['data'])
self.assertEqual(data['configuration']['type'], FUNC_API_TEST_TYPE)
def test_functional_gui_test_creation(self):
self.obj.engine.aggregator = FunctionalAggregator()
self.configure(
engine_cfg={
EXEC: {"executor": "selenium", "scenario": {"requests": ["http://blazedemo.com"]}},
"modules": {
"selenium": {
"class": SeleniumExecutor.__module__ + "." + SeleniumExecutor.__name__,
"virtual-display": False},
"apiritif": {
"class": ApiritifTester.__module__ + "." + ApiritifTester.__name__,
"verbose": False
}
}},
get={
'https://a.blazemeter.com/api/v4/tests?workspaceId=1&name=Taurus+Cloud+Test': {"result": [
{"id": 1, 'projectId': 1, 'name': 'Taurus Cloud Test', 'configuration': {'type': 'taurus'}}
]},
'https://a.blazemeter.com/api/v4/projects?workspaceId=1': [
{'result': []},
{'result': [{'id': 1}]}
],
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
}, post={
'https://a.blazemeter.com/api/v4/tests/1/start?functionalExecution=true': {'result': {'id': 'mid'}}
})
self.obj.settings.merge({"delete-test-files": False, "project": "myproject"})
self.obj.prepare()
self.obj.startup()
reqs = self.mock.requests
self.assertEqual(reqs[10]['url'], 'https://a.blazemeter.com/api/v4/tests')
self.assertEqual(reqs[10]['method'], 'POST')
data = json.loads(reqs[10]['data'])
self.assertEqual(data['configuration']['type'], FUNC_GUI_TEST_TYPE)
def test_user_type_test_creation(self):
self.obj.engine.aggregator = FunctionalAggregator()
user_test_type = "appiumForExampe"
self.configure(
engine_cfg={
EXEC: {"executor": "selenium", "scenario": {"requests": ["http://blazedemo.com"]}},
"modules": {
"selenium": {
"class": SeleniumExecutor.__module__ + "." + SeleniumExecutor.__name__,
"virtual-display": False},
"apiritif": {
"class": ApiritifTester.__module__ + "." + ApiritifTester.__name__,
"verbose": False},
}},
get={
'https://a.blazemeter.com/api/v4/tests?workspaceId=1&name=Taurus+Cloud+Test': {"result": [
{"id": 1, 'projectId': 1, 'name': 'Taurus Cloud Test', 'configuration': {'type': 'taurus'}}
]},
'https://a.blazemeter.com/api/v4/projects?workspaceId=1': [
{'result': []},
{'result': [{'id': 1}]}
],
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
}, post={
'https://a.blazemeter.com/api/v4/tests/1/start?functionalExecution=true': {'result': {'id': 'mid'}}
})
self.obj.settings.merge({"delete-test-files": False, "project": "myproject", "test-type": user_test_type})
self.obj.prepare()
self.obj.startup()
reqs = self.mock.requests
self.assertEqual(reqs[10]['url'], 'https://a.blazemeter.com/api/v4/tests')
self.assertEqual(reqs[10]['method'], 'POST')
data = json.loads(reqs[10]['data'])
self.assertEqual(data['configuration']['type'], user_test_type)
def test_functional_cloud_failed_shutdown(self):
self.obj.engine.aggregator = FunctionalAggregator()
func_summary = {"isFailed": True}
self.configure(engine_cfg={EXEC: {"executor": "mock"}}, get={
'https://a.blazemeter.com/api/v4/tests?workspaceId=1&name=Taurus+Cloud+Test': {"result": [
{"id": 1, 'projectId': 1, 'name': 'Taurus Cloud Test', 'configuration': {'type': 'taurus'}}
]},
'https://a.blazemeter.com/api/v4/projects?workspaceId=1': [
{'result': []},
{'result': [{'id': 1}]}
],
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
'https://a.blazemeter.com/api/v4/masters/1/status': {"result": {"id": 1, "progress": 100}},
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": []},
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {"functionalSummary": func_summary}},
}, post={
'https://a.blazemeter.com/api/v4/tests/1/start?functionalExecution=true': {'result': {'id': 1}}
})
self.obj.settings.merge({"delete-test-files": False, "project": "myproject"})
self.obj.prepare()
self.obj.startup()
self.obj.check()
self.obj.shutdown()
with self.assertRaises(AutomatedShutdown):
self.obj.post_process()
def test_launch_existing_test(self):
self.configure(
get={
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=foo': {"result": []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=foo': {"result": [
{"id": 1, "name": "foo", "configuration": {"type": "taurus"}}
]},
}
)
self.obj.settings["test"] = "foo"
self.obj.settings["launch-existing-test"] = True
self.obj.prepare()
self.assertEqual(12, len(self.mock.requests))
self.obj.startup()
self.assertEqual(13, len(self.mock.requests))
def test_launch_existing_test_by_id(self):
self.configure(
get={
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&id=1': {"result": []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&id=1': {"result": [
{"id": 1, "name": "foo", "configuration": {"type": "taurus"}}
]},
}
)
self.obj.settings["test"] = 1
self.obj.settings["launch-existing-test"] = True
self.obj.prepare()
self.assertEqual(12, len(self.mock.requests))
self.obj.startup()
self.assertEqual(13, len(self.mock.requests))
def test_launch_existing_test_not_found_by_id(self):
self.configure(
get={
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&id=1': {"result": []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&id=1': {"result": []},
}
)
self.obj.settings["test"] = 1
self.obj.settings["launch-existing-test"] = True
self.assertRaises(TaurusConfigError, self.obj.prepare)
def test_launch_existing_test_not_found(self):
self.configure(
get={
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=foo': {"result": []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=foo': {"result": []},
}
)
self.obj.settings["test"] = "foo"
self.obj.settings["launch-existing-test"] = True
self.assertRaises(TaurusConfigError, self.obj.prepare)
def test_launch_existing_multi_test(self):
self.configure(
get={
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&id=1': {"result": [
{"id": 1, "name": 1}
]}
},
post={
'https://a.blazemeter.com/api/v4/multi-tests/1/start?delayedStart=true': {"result": {"id": 1}}
}
)
self.obj.settings["test"] = 1
self.obj.settings["launch-existing-test"] = True
self.obj.prepare()
self.assertEqual(9, len(self.mock.requests))
self.obj.startup()
self.assertEqual(10, len(self.mock.requests))
def test_launch_existing_test_non_taurus(self):
self.configure(
get={
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=foo': {"result": []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=foo': {"result": [
{"id": 1, "name": "foo", "configuration": {"type": "jmeter"}}
]},
}
)
self.obj.settings["test"] = "foo"
self.obj.prepare()
self.assertEqual(12, len(self.mock.requests))
self.obj.startup()
self.assertEqual(13, len(self.mock.requests))
def test_launch_test_by_link(self):
self.configure(
get={
'https://a.blazemeter.com/api/v4/accounts': {"result": [{"id": 1, "name": "Acc name"}]},
'https://a.blazemeter.com/api/v4/workspaces?accountId=1&enabled=true&limit=100': {
"result": [{"id": 2, "name": "Wksp name", "enabled": True, "accountId": 1}]
},
'https://a.blazemeter.com/api/v4/projects?workspaceId=2&limit=1000': {
"result": [{"id": 3, "name": "Project name", "workspaceId": 2}]
},
'https://a.blazemeter.com/api/v4/multi-tests?projectId=3&id=4': {"result": []},
'https://a.blazemeter.com/api/v4/tests?projectId=3&id=4': {"result": [
{"id": 4, "name": "foo", "configuration": {"type": "taurus"}}
]},
},
post={
'https://a.blazemeter.com/api/v4/tests/4/start': {"result": {"id": 5}},
},
patch={
'https://a.blazemeter.com/api/v4/tests/4': {"result": {}}
}
)
self.obj.settings["test"] = "https://a.blazemeter.com/app/#/accounts/1/workspaces/2/projects/3/tests/4"
self.obj.settings["launch-existing-test"] = True
self.obj.prepare()
self.assertIsInstance(self.obj.router, CloudTaurusTest)
self.assertEqual(9, len(self.mock.requests))
self.obj.startup()
self.assertEqual(10, len(self.mock.requests))
def test_update_test_by_link(self):
self.configure(
engine_cfg={
"execution": [
{"executor": "mock",
"iterations": 1,
"locations": {"eu-west-1": 1},
"scenario": {"requests": ["http://blazedemo.com/"]}}
]
},
get={
'https://a.blazemeter.com/api/v4/accounts': {"result": [{"id": 1, "name": "Acc name"}]},
'https://a.blazemeter.com/api/v4/workspaces?accountId=1&enabled=true&limit=100': {
"result": [{"id": 2, "name": "Wksp name", "enabled": True, "accountId": 1,
"locations": [{"id": "eu-west-1"}]}]
},
'https://a.blazemeter.com/api/v4/workspaces/2': {
"result": {"id": 2, "name": "Wksp name", "enabled": True, "accountId": 1,
"locations": [{"id": "eu-west-1"}]}
},
'https://a.blazemeter.com/api/v4/projects?workspaceId=2&limit=1000': {
"result": [{"id": 3, "name": "Project name", "workspaceId": 2}]
},
'https://a.blazemeter.com/api/v4/multi-tests?projectId=3&id=4': {"result": []},
'https://a.blazemeter.com/api/v4/tests?projectId=3&id=4': {"result": [
{"id": 4, "name": "foo", "configuration": {"type": "taurus"}}
]},
},
post={
'https://a.blazemeter.com/api/v4/tests/4/files': {"result": {}},
'https://a.blazemeter.com/api/v4/tests/4/start': {"result": {"id": 5}},
},
patch={
'https://a.blazemeter.com/api/v4/tests/4': {"result": {}},
}
)
self.obj.settings["test"] = "https://a.blazemeter.com/app/#/accounts/1/workspaces/2/projects/3/tests/4"
self.obj.prepare()
self.assertEqual(13, len(self.mock.requests))
self.obj.startup()
self.assertEqual(14, len(self.mock.requests))
self.assertEqual(self.obj.router.master['id'], 5)
def test_lookup_account_workspace(self):
self.configure(
get={
'https://a.blazemeter.com/api/v4/accounts': {"result": [{"id": 1, "name": "Acc name"}]},
'https://a.blazemeter.com/api/v4/workspaces?accountId=1&enabled=true&limit=100': {
"result": [{"id": 2, "name": "Wksp name", "enabled": True, "accountId": 1}]
},
'https://a.blazemeter.com/api/v4/projects?workspaceId=2&name=Project+name': {
"result": [{"id": 3, "name": "Project name", "workspaceId": 2}]
},
'https://a.blazemeter.com/api/v4/multi-tests?projectId=3&name=Test+name': {"result": []},
'https://a.blazemeter.com/api/v4/tests?projectId=3&name=Test+name': {"result": [
{"id": 4, "name": "Test name", "configuration": {"type": "taurus"}}
]}},
post={
'https://a.blazemeter.com/api/v4/tests/4/start': {"result": {"id": 5}},
},
patch={
'https://a.blazemeter.com/api/v4/tests/4': {"result": []}
}
)
self.obj.settings["account"] = "Acc name"
self.obj.settings["workspace"] = "Wksp name"
self.obj.settings["project"] = "Project name"
self.obj.settings["test"] = "Test name"
self.obj.settings["launch-existing-test"] = True
self.obj.prepare()
self.assertIsInstance(self.obj.router, CloudTaurusTest)
self.assertEqual(9, len(self.mock.requests))
self.obj.startup()
self.assertEqual(10, len(self.mock.requests))
def test_lookup_test_ids(self):
self.configure(
get={
'https://a.blazemeter.com/api/v4/accounts': {"result": [{"id": 1, "name": "Acc name"}]},
'https://a.blazemeter.com/api/v4/workspaces?accountId=1&enabled=true&limit=100': {
"result": [{"id": 2, "name": "Wksp name", "enabled": True, "accountId": 1}]
},
'https://a.blazemeter.com/api/v4/projects?workspaceId=2&limit=1000': {
"result": [{"id": 3, "name": "Project name", "workspaceId": 2}]
},
'https://a.blazemeter.com/api/v4/multi-tests?projectId=3&id=4': {"result": []},
'https://a.blazemeter.com/api/v4/tests?projectId=3&id=4': {"result": [
{"id": 4, "name": "Test name", "configuration": {"type": "taurus"}}
]},
},
post={
'https://a.blazemeter.com/api/v4/tests/4/start': {"result": {"id": 5}},
},
patch={
'https://a.blazemeter.com/api/v4/tests/4': {"result": []}
}
)
self.obj.settings["account"] = 1
self.obj.settings["workspace"] = 2
self.obj.settings["project"] = 3
self.obj.settings["test"] = 4
self.obj.settings["launch-existing-test"] = True
self.obj.prepare()
self.assertIsInstance(self.obj.router, CloudTaurusTest)
self.assertEqual(9, len(self.mock.requests))
self.obj.startup()
self.assertEqual(10, len(self.mock.requests))
def test_lookup_test_different_type(self):
self.configure(
engine_cfg={
"execution": [
{"executor": "mock",
"iterations": 1,
"locations": {"eu-west-1": 1},
"scenario": {"requests": ["http://blazedemo.com/"]}}
]
},
get={
'https://a.blazemeter.com/api/v4/accounts': {
"result": [{"id": 1, "name": "Acc name", "owner": {"id": 1}}]},
'https://a.blazemeter.com/api/v4/workspaces?accountId=1&enabled=true&limit=100': {
"result": [{"id": 2, "name": "Wksp name", "enabled": True, "accountId": 1,
"locations": [{"id": "eu-west-1"}]},
{"id": 1, "name": "Dflt name", "enabled": True, "accountId": 1,
"locations": [{"id": "eu-west-1"}]}]
},
'https://a.blazemeter.com/api/v4/workspaces/1': {
"result": {"id": 1, "name": "Wksp name", "enabled": True, "accountId": 1,
"locations": [{"id": "eu-west-1"}]}
},
'https://a.blazemeter.com/api/v4/projects?workspaceId=2': {
"result": [{"id": 3, "name": "Project name", "workspaceId": 2}]
},
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=ExternalTest': {"result": []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=ExternalTest': {"result": [
{"id": 4, "name": "ExternalTest", "configuration": {"type": "external"}},
]},
},
post={
'https://a.blazemeter.com/api/v4/tests/4/files': {"result": {}},
},
patch={
'https://a.blazemeter.com/api/v4/tests/4': {"result": {}},
}
)
self.obj.settings["test"] = "ExternalTest"
self.obj.prepare()
self.assertEqual(18, len(self.mock.requests))
def test_send_report_email_default(self):
self.configure(engine_cfg={EXEC: {"executor": "mock"}}, get={
'https://a.blazemeter.com/api/v4/tests?workspaceId=1&name=Taurus+Cloud+Test': {"result": [
{"id": 1, 'projectId': 1, 'name': 'Taurus Cloud Test', 'configuration': {'type': 'taurus'}}
]},
'https://a.blazemeter.com/api/v4/projects?workspaceId=1': [
{'result': []},
{'result': [{'id': 1}]}
],
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
}, post={
'https://a.blazemeter.com/api/v4/tests/1/start': {'result': {'id': 'mid'}}
})
self.obj.settings.merge({"project": "myproject"})
self.obj.prepare()
self.obj.startup()
reqs = self.mock.requests
self.assertEqual(reqs[13]['url'], 'https://a.blazemeter.com/api/v4/tests/1')
self.assertEqual(reqs[13]['method'], 'PATCH')
data = json.loads(reqs[13]['data'])
self.assertEqual(data["shouldSendReportEmail"], False)
def test_send_report_email(self):
self.configure(engine_cfg={EXEC: {"executor": "mock"}}, get={
'https://a.blazemeter.com/api/v4/tests?workspaceId=1&name=Taurus+Cloud+Test': {"result": [
{"id": 1, 'projectId': 1, 'name': 'Taurus Cloud Test', 'configuration': {'type': 'taurus'}}
]},
'https://a.blazemeter.com/api/v4/projects?workspaceId=1': [
{'result': []},
{'result': [{'id': 1}]}
],
'https://a.blazemeter.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Cloud+Test': {'result': []},
}, post={
'https://a.blazemeter.com/api/v4/tests/1/start': {'result': {'id': 'mid'}}
})
self.obj.settings.merge({"project": "myproject", "send-report-email": True})
self.obj.prepare()
self.obj.startup()
reqs = self.mock.requests
self.assertEqual(reqs[13]['url'], 'https://a.blazemeter.com/api/v4/tests/1')
self.assertEqual(reqs[13]['method'], 'PATCH')
data = json.loads(reqs[13]['data'])
self.assertEqual(data['shouldSendReportEmail'], True)
def test_multi_account_choice(self):
with open(RESOURCES_DIR + "json/blazemeter-api-accounts.json") as fhd:
accs = json.loads(fhd.read())
self.configure(
engine_cfg={EXEC: {"executor": "mock"}},
get={
'https://a.blazemeter.com/api/v4/accounts': accs,
},
)
self.obj.settings['launch-existing-test'] = False
self.obj.prepare()
exp = "https://a.blazemeter.com/api/v4/workspaces?accountId=1&enabled=true&limit=100"
self.assertEqual(exp, self.mock.requests[6]['url'])
self.assertEqual(21, len(self.mock.requests))
def test_cloud_failure_criteria(self):
self.configure(
engine_cfg={EXEC: {"executor": "mock"}},
get={
'https://a.blazemeter.com/api/v4/masters/1/status': {"result": {"id": 1, "progress": 100}},
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": []},
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {"hasThresholds": True}},
'https://a.blazemeter.com/api/v4/masters/1/reports/thresholds?external=false&source=default': {
"result": {"data": [{"success": False, "assertions": [{
"label": "ALL",
"field": "field",
"op": "gt",
"failValue": 1,
"success": False,
}]}]}
},
},
)
self.obj.prepare()
self.obj.startup()
self.obj.check()
self.obj.shutdown()
with self.assertRaises(AutomatedShutdown):
self.obj.post_process()
def test_cloud_failure_criteria_werent_met(self):
self.configure(
engine_cfg={EXEC: {"executor": "mock"}},
get={
'https://a.blazemeter.com/api/v4/masters/1/status': {"result": {"id": 1, "progress": 100}},
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": []},
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {"hasThresholds": True}},
'https://a.blazemeter.com/api/v4/masters/1/reports/thresholds?external=false&source=default': {
"result": {"data": [{"success": True, "assertions": [{
"label": "ALL",
"field": "field",
"op": "gt",
"failValue": 1,
"success": True,
}]}]}
},
},
)
self.obj.prepare()
self.obj.startup()
self.obj.check()
self.obj.shutdown()
try:
self.obj.post_process()
except AutomatedShutdown as exc:
self.fail("Raised automated shutdown %s" % exc)
def test_cloud_failure_criteria_default_reason(self):
self.configure(
engine_cfg={EXEC: {"executor": "mock"}},
get={
'https://a.blazemeter.com/api/v4/masters/1/status': {"result": {"id": 1, "progress": 100}},
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": []},
'https://a.blazemeter.com/api/v4/masters/1/full': {"result": {"hasThresholds": True}},
'https://a.blazemeter.com/api/v4/masters/1/reports/thresholds?external=false&source=default': {
"result": {"data": [{"success": True, "assertions": []}]}
},
},
)
self.obj.prepare()
self.obj.startup()
self.obj.check()
self.obj.shutdown()
try:
self.obj.post_process()
except AutomatedShutdown as exc:
self.fail("Raised automated shutdown %s" % exc)
def test_passfail_criteria(self):
criteria = ['avg-rt<100ms', 'bytes<1kb']
self.configure(
engine_cfg={
EXEC: {"executor": "mock"},
"reporting": [{"module": "passfail", "criteria": criteria}],
},
get={
'https://a.blazemeter.com/api/v4/tests/1/validations': {'result': [
{'status': 100,
'warnings': ["passfail warning"],
'fileWarnings': ["passfail file warning"]}]},
'https://a.blazemeter.com/api/v4/masters/1/status': {'result': {"status": "CREATED", "progress": 100}},
'https://a.blazemeter.com/api/v4/masters/1/sessions': {"result": {"sessions": []}},
},
post={
'https://a.blazemeter.com/api/v4/tests/1/start': {"result": {"id": 1}},
'https://a.blazemeter.com/api/v4/tests/1/validate': {'result': {'success': True}},
},
)
self.sniff_log(self.obj.log)
self.obj.prepare()
self.assertEqual(self.obj.engine.config['reporting'][0]['criteria'], criteria)
self.obj.startup()
self.obj.check()
warnings = self.log_recorder.warn_buff.getvalue()
self.assertIn("Passfail Warning: passfail warning", warnings)
self.assertIn("Passfail Warning: passfail file warning", warnings)
def test_nonstandard_env(self):
self.obj.user.address = "https://some-bzm-link.com"
self.obj.user.data_address = "https://some-bzm-link.com"
self.configure(
engine_cfg={EXEC: {"executor": "mock"}},
get={
'https://some-bzm-link.com/api/v4/accounts': {"result": [{'id': 1, 'owner': {'id': 1}}]},
'https://some-bzm-link.com/api/v4/workspaces?accountId=1&enabled=true&limit=100': {
"result": [{'id': 1, 'enabled': True}]},
'https://some-bzm-link.com/api/v4/user': {'id': 1,
'defaultProject': {'id': 1, 'accountId': 1,
'workspaceId': 1}},
'https://some-bzm-link.com/api/v4/projects?workspaceId=1&limit=1000': {"result": []},
'https://some-bzm-link.com/api/v4/multi-tests?projectId=1&name=Taurus+Cloud+Test': {"result": []},
'https://some-bzm-link.com/api/v4/tests?projectId=1&name=Taurus+Cloud+Test': {"result": []},
'https://some-bzm-link.com/api/v4/workspaces/1': {"result": {"locations": [
{'id': 'us-east-1', 'sandbox': False, 'title': 'East'}]}},
},
post={
'https://some-bzm-link.com/api/v4/projects': {"result": {"id": 1, 'workspaceId': 1, 'limit': 1000}},
'https://some-bzm-link.com/api/v4/tests': {"result": {"id": 1, "configuration": {"type": "taurus"}}},
'https://some-bzm-link.com/api/v4/tests/1/files': {"result": {"id": 1}},
'https://some-bzm-link.com/api/v4/tests/1/start': {"result": {"id": 1}},
},
patch={
'https://some-bzm-link.com/api/v4/tests/1': {"result": {}},
},
)
self.sniff_log(self.obj.log)
self.obj.prepare()
self.obj.startup()
self.assertIn("https://some-bzm-link.com", self.log_recorder.info_buff.getvalue())
class TestResultsFromBZA(BZTestCase):
@staticmethod
def convert_kpi_errors(errors):
result = {}
for error in errors:
result[error['msg']] = {'count': error['cnt'], 'rc': error['rc']}
return result
@staticmethod
def get_errors_mock(errors, assertions=None):
# return mock of server response for errors specified in internal format (see __get_errors_from_BZA())
result = []
if not assertions:
assertions = {}
for _id in list(set(list(errors.keys()) + list(assertions.keys()))): # unique keys from both dictionaries
errors_list = []
if errors.get(_id):
for msg in errors[_id]:
errors_list.append({
"m": msg,
"count": errors[_id][msg]["count"],
"rc": errors[_id][msg]["rc"]})
assertions_list = []
if assertions.get(_id):
for msg in assertions[_id]:
assertions_list.append({
"failureMessage": msg,
"failures": assertions[_id][msg]["count"],
"name": "All Assertions"})
result.append({
"_id": _id,
"name": _id,
"assertions": assertions_list,
"samplesNotCounted": 0,
"assertionsNotCounted": 0,
"otherErrorsCount": 0,
"errors": errors_list})
result.append({
"_id": "err_inconsistency",
"name": "err_inconsistency",
"assertions": [],
"samplesNotCounted": 0,
"assertionsNotCounted": 0,
"otherErrorsCount": 0,
"errors": []})
return {
"https://a.blazemeter.com/api/v4/masters/1/reports/errorsreport/data?noDataError=false": {
"api_version": 4,
"error": None,
"result": result}}
def test_get_errors(self):
mock = BZMock()
mock.mock_get.update({
'https://a.blazemeter.com/api/v4/data/labels?master_id=1': {
"api_version": 4,
"error": None,
"result": [{
"sessions": ["r-t-5746a8e38569a"],
"id": "ALL",
"name": "ALL"
}, {
"sessions": ["r-t-5746a8e38569a"],
"id": "e843ff89a5737891a10251cbb0db08e5",
"name": "http://blazedemo.com/"}]},
'https://a.blazemeter.com/api/v4/data/kpis?interval=1&from=0&master_ids%5B%5D=1&kpis%5B%5D=t&kpis%5B%5D=lt&kpis%5B%5D=by&kpis%5B%5D=n&kpis%5B%5D=ec&kpis%5B%5D=ts&kpis%5B%5D=na&labels%5B%5D=ALL&labels%5B%5D=e843ff89a5737891a10251cbb0db08e5': {
"api_version": 4,
"error": None,
"result": [{
"labelId": "ALL",
"labelName": "ALL",
"label": "ALL",
"kpis": [{
"n": 1, "na": 1, "ec": 0, "p90": 0, "t_avg": 817, "lt_avg": 82,
"by_avg": 0, "n_avg": 1, "ec_avg": 0, "ts": 1464248743
}, {"n": 1, "na": 1, "ec": 0, "p90": 0, "t_avg": 817, "lt_avg": 82,
"by_avg": 0, "n_avg": 1, "ec_avg": 0, "ts": 1464248744}]}]},
'https://a.blazemeter.com/api/v4/masters/1/reports/aggregatereport/data': {
"api_version": 4,
"error": None,
"result": [{
"labelName": "ALL", "99line": 1050, "90line": 836, "95line": 912}, {
"labelName": "http://blazedemo.com", "99line": 1050, "90line": 836, "95line": 912}]},
'https://a.blazemeter.com/api/v4/data/kpis?interval=1&from=1464248744&master_ids%5B%5D=1&kpis%5B%5D=t&kpis%5B%5D=lt&kpis%5B%5D=by&kpis%5B%5D=n&kpis%5B%5D=ec&kpis%5B%5D=ts&kpis%5B%5D=na&labels%5B%5D=ALL&labels%5B%5D=e843ff89a5737891a10251cbb0db08e5': {
"api_version": 4,
"error": None,
"result": [{
"labelId": "ALL",
"labelName": "ALL",
"label": "ALL",
"kpis": [{
"n": 1, "na": 1, "ec": 0, "p90": 0, "t_avg": 817, "lt_avg": 82,
"by_avg": 0, "n_avg": 1, "ec_avg": 0, "ts": 1464248744
}, {"n": 1, "na": 1, "ec": 0, "p90": 0, "t_avg": 817, "lt_avg": 82,
"by_avg": 0, "n_avg": 1, "ec_avg": 0, "ts": 1464248745}]}]},
'https://a.blazemeter.com/api/v4/data/kpis?interval=1&from=1464248745&master_ids%5B%5D=1&kpis%5B%5D=t&kpis%5B%5D=lt&kpis%5B%5D=by&kpis%5B%5D=n&kpis%5B%5D=ec&kpis%5B%5D=ts&kpis%5B%5D=na&labels%5B%5D=ALL&labels%5B%5D=e843ff89a5737891a10251cbb0db08e5': {
"api_version": 4,
"error": None,
"result": [{
"labelId": "ALL",
"labelName": "ALL",
"label": "ALL",
"kpis": [{
"n": 1, "na": 1, "ec": 0, "p90": 0, "t_avg": 817, "lt_avg": 82,
"by_avg": 0, "n_avg": 1, "ec_avg": 0, "ts": 1464248745}]}]}})
obj = ResultsFromBZA()
obj.master = Master(data={"id": 1})
mock.apply(obj.master)
# set cumulative errors from BM
mock.mock_get.update(self.get_errors_mock({
'ALL': {"Not found": {"count": 10, "rc": "404"}},
# 'broken': {"Not found": {"count": 10, "rc": "404"}},
}))
# frame [0, 1464248744)
res1 = list(obj.datapoints(False))
self.assertEqual(1, len(res1))
cumul = res1[0][DataPoint.CUMULATIVE]
cur = res1[0][DataPoint.CURRENT]
self.assertEqual(1, len(cumul.keys()))
self.assertEqual(1, len(cur.keys()))
errors_1 = {'Not found': {'count': 10, 'rc': u'404'}}
self.assertEqual(self.convert_kpi_errors(cumul[""]["errors"]), errors_1) # all error data is written
self.assertEqual(self.convert_kpi_errors(cur[""]["errors"]), errors_1) # to 'current' and 'cumulative'
# frame [1464248744, 1464248745)
res2 = list(obj.datapoints(False))
self.assertEqual(1, len(res2))
cumul = res2[0][DataPoint.CUMULATIVE]
cur = res2[0][DataPoint.CURRENT]
self.assertEqual(1, len(cumul.keys()))
self.assertEqual(1, len(cur.keys()))
self.assertEqual(self.convert_kpi_errors(cumul[""]["errors"]), errors_1) # the same errors,
self.assertEqual(cur[""]["errors"], []) # new errors not found
mock.mock_get.update(self.get_errors_mock({
"ALL": {
"Not found": {
"count": 11, "rc": "404"}, # one more error
"Found": {
"count": 2, "rc": "200"}}, # new error message (error ID)
"label1": {
"Strange behaviour": {
"count": 666, "rc": "666"}}}, { # new error label
"ALL": {"assertion_example": {"count": 33}}}))
res3 = list(obj.datapoints(True)) # let's add the last timestamp [1464248745]
self.assertEqual(1, len(res3))
cumul = res3[0][DataPoint.CUMULATIVE]
cur = res3[0][DataPoint.CURRENT]
errors_all_full = {
'Not found': {'count': 11, 'rc': '404'},
'Found': {'count': 2, 'rc': '200'},
'assertion_example': {'count': 33, 'rc': 'All Assertions'}}
errors_all_update = {
'Not found': {'count': 1, 'rc': '404'},
'Found': {'count': 2, 'rc': '200'},
'assertion_example': {'count': 33, 'rc': 'All Assertions'}}
errors_label1 = {'Strange behaviour': {'count': 666, 'rc': '666'}}
self.assertEqual(errors_label1, self.convert_kpi_errors(cumul["label1"]["errors"]))
self.assertEqual(errors_all_full, self.convert_kpi_errors(cumul[""]["errors"]))
self.assertEqual(errors_label1, self.convert_kpi_errors(cur["label1"]["errors"]))
self.assertEqual(errors_all_update, self.convert_kpi_errors(cur[""]["errors"]))
def test_datapoint(self):
mock = BZMock()
mock.mock_get.update({
'https://a.blazemeter.com/api/v4/data/labels?master_id=1': {
"api_version": 2,
"error": None,
"result": [{
"sessions": ["r-t-5746a8e38569a"],
"id": "ALL",
"name": "ALL"
}, {
"sessions": ["r-t-5746a8e38569a"],
"id": "e843ff89a5737891a10251cbb0db08e5",
"name": "http://blazedemo.com/"}]},
'https://a.blazemeter.com/api/v4/data/kpis?interval=1&from=0&master_ids%5B%5D=1&kpis%5B%5D=t&kpis%5B%5D=lt&kpis%5B%5D=by&kpis%5B%5D=n&kpis%5B%5D=ec&kpis%5B%5D=ts&kpis%5B%5D=na&labels%5B%5D=ALL&labels%5B%5D=e843ff89a5737891a10251cbb0db08e5': {
"api_version": 2,
"error": None,
"result": [{
"labelId": "ALL",
"labelName": "ALL",
"label": "ALL",
"kpis": [{
"n": 1,
"na": 1,
"ec": 0,
"p90": 0,
"t_avg": 817,
"lt_avg": 82,
"by_avg": 0,
"n_avg": 1,
"ec_avg": 0,
"ts": 1464248743}]}]},
'https://a.blazemeter.com/api/v4/masters/1/reports/aggregatereport/data': {
"api_version": 2,
"error": None,
"result": [{
"labelId": "ALL",
"labelName": "ALL",
"samples": 152,
"avgResponseTime": 786,
"90line": 836,
"95line": 912,
"99line": 1050,
"minResponseTime": 531,
"maxResponseTime": 1148,
"avgLatency": 81,
"geoMeanResponseTime": None,
"stDev": 108,
"duration": 119,
"avgBytes": 0,
"avgThroughput": 1.2773109243697,
"medianResponseTime": 0,
"errorsCount": 0,
"errorsRate": 0,
"hasLabelPassedThresholds": None
}, {
"labelId": "e843ff89a5737891a10251cbb0db08e5",
"labelName": "http://blazedemo.com/",
"samples": 152,
"avgResponseTime": 786,
"90line": 836,
"95line": 912,
"99line": 1050,
"minResponseTime": 531,
"maxResponseTime": 1148,
"avgLatency": 81,
"geoMeanResponseTime": None,
"stDev": 108,
"duration": 119,
"avgBytes": 0,
"avgThroughput": 1.2773109243697,
"medianResponseTime": 0,
"errorsCount": 0,
"errorsRate": 0,
"hasLabelPassedThresholds": None}]}})
mock.mock_get.update(self.get_errors_mock({"ALL": {}}))
obj = ResultsFromBZA()
obj.master = Master(data={"id": 1})
mock.apply(obj.master)
res = list(obj.datapoints(True))
cumulative_ = res[0][DataPoint.CUMULATIVE]
total = cumulative_['']
percentiles_ = total[KPISet.PERCENTILES]
self.assertEquals(1.05, percentiles_['99.0'])
def test_no_kpis_on_cloud_crash(self):
mock = BZMock()
mock.mock_get.update({
'https://a.blazemeter.com/api/v4/data/labels?master_id=0': {
"api_version": 2,
"error": None,
"result": [
{
"sessions": [
"r-t-5746a8e38569a"
],
"id": "ALL",
"name": "ALL"
},
{
"sessions": [
"r-t-5746a8e38569a"
],
"id": "e843ff89a5737891a10251cbb0db08e5",
"name": "http://blazedemo.com/"
}
]
},
'https://a.blazemeter.com/api/v4/data/kpis?interval=1&from=0&master_ids%5B%5D=0&kpis%5B%5D=t&kpis%5B%5D=lt&kpis%5B%5D=by&kpis%5B%5D=n&kpis%5B%5D=ec&kpis%5B%5D=ts&kpis%5B%5D=na&labels%5B%5D=ALL&labels%5B%5D=e843ff89a5737891a10251cbb0db08e5': {
"api_version": 2,
"error": None,
"result": [
{
"labelId": "ALL",
"labelName": "ALL",
}
]
},
'https://a.blazemeter.com/api/v4/masters/0/reports/aggregatereport/data': {
"api_version": 2,
"error": None,
"result": [
{
"labelId": "ALL",
"labelName": "ALL",
"samples": 152,
"avgResponseTime": 786,
"90line": 836,
"95line": 912,
"99line": 1050,
"minResponseTime": 531,
"maxResponseTime": 1148,
"avgLatency": 81,
"geoMeanResponseTime": None,
"stDev": 108,
"duration": 119,
"avgBytes": 0,
"avgThroughput": 1.2773109243697,
"medianResponseTime": 0,
"errorsCount": 0,
"errorsRate": 0,
"hasLabelPassedThresholds": None
},
{
"labelId": "e843ff89a5737891a10251cbb0db08e5",
"labelName": "http://blazedemo.com/",
"samples": 152,
"avgResponseTime": 786,
"90line": 836,
"95line": 912,
"99line": 1050,
"minResponseTime": 531,
"maxResponseTime": 1148,
"avgLatency": 81,
"geoMeanResponseTime": None,
"stDev": 108,
"duration": 119,
"avgBytes": 0,
"avgThroughput": 1.2773109243697,
"medianResponseTime": 0,
"errorsCount": 0,
"errorsRate": 0,
"hasLabelPassedThresholds": None
}
]
}
})
obj = ResultsFromBZA(Master(data={'id': 0}))
mock.apply(obj.master)
res = list(obj.datapoints(True))
self.assertEqual(res, [])
def test_inconsistent(self):
self.skipTest("just keep this code for future troubleshooting")
agg = ConsolidatingAggregator()
agg.engine = EngineEmul()
obj = ResultsFromBZA(MasterFromLog(data={'id': 0}))
with open("/home/undera/bzt.log") as fhd:
obj.master.loglines = fhd.readlines()
class Listener(AggregatorListener):
def aggregated_second(self, data):
for x in data[DataPoint.CURRENT].values():
a = x[KPISet.FAILURES] / x[KPISet.SAMPLE_COUNT]
obj.log.debug("TS: %s %s", data[DataPoint.TIMESTAMP], x[KPISet.SAMPLE_COUNT])
for x in data[DataPoint.CUMULATIVE].values():
a = x[KPISet.FAILURES] / x[KPISet.SAMPLE_COUNT]
obj.log.debug("TS: %s %s", data[DataPoint.TIMESTAMP], x[KPISet.SAMPLE_COUNT])
agg.add_underling(obj)
status = FinalStatus()
agg.add_listener(status)
agg.add_listener(Listener())
agg.prepare()
agg.startup()
try:
while not agg.check():
pass # 1537973736 fail, prev 1537973735 1537973734 1537973733
except NormalShutdown:
obj.log.warning("Shutting down")
agg.shutdown()
agg.post_process()
status.post_process()
# res = list(obj.datapoints(False)) + list(obj.datapoints(True))
# for point in res:
# obj.log.debug("TS: %s", point[DataPoint.TIMESTAMP])
# for x in point[DataPoint.CURRENT].values():
# a = x[KPISet.FAILURES] / x[KPISet.SAMPLE_COUNT]
class MasterFromLog(Master):
loglines = []
def _extract(self, marker):
marker = marker.replace('/', '[/]')
marker = marker.replace('?', '[?]')
regexp = re.compile(marker)
while self.loglines:
line = self.loglines.pop(0)
if "Shutting down..." in line:
raise NormalShutdown()
match = regexp.search(line)
if match:
self.log.debug("Found: %s", line)
while self.loglines:
line = self.loglines.pop(0)
if "Response [200]" in line:
self.log.debug("Found: %s", line)
buf = "{"
while self.loglines:
line = self.loglines.pop(0)
if len(line) < 5:
pass
if line.startswith("}"):
self.log.debug("Result data: %s}", buf)
return json.loads(buf + "}")['result']
else:
buf += line
# return []
raise AssertionError("Failed to find: %s", marker)
def get_kpis(self, min_ts):
return self._extract("GET https://a.blazemeter.com/api/v4/data/kpis")
def get_aggregate_report(self):
return self._extract("GET https://a.blazemeter.com/api/v4/masters/\d+/reports/aggregatereport/data")
def get_errors(self):
tpl = "GET https://a.blazemeter.com/api/v4/masters/\d+/reports/errorsreport/data?noDataError=false"
return self._extract(tpl)
class TestFunctionalBZAReader(BZTestCase):
def test_simple(self):
mock = BZMock()
mock.mock_get.update({
'https://a.blazemeter.com/api/v4/masters/1/reports/functional/groups': {"result": [{
"groupId": "gid",
"sessionId": "sid",
"summary": {
"testsCount": 3,
"requestsCount": 3,
"errorsCount": 2,
"assertions": {
"count": 0,
"passed": 0
},
"responseTime": {
"sum": 0
},
"isFailed": True,
"failedCount": 2,
"failedPercentage": 100
},
"id": "gid",
"name": None,
}]},
'https://a.blazemeter.com/api/v4/masters/1/reports/functional/groups/gid': {
"api_version": 2,
"error": None,
"result": {
"groupId": "gid",
"samples": [
{
"id": "s1",
"label": "test_breaking",
"created": 1505824780,
"responseTime": None,
"assertions": [{
"isFailed": True,
"errorMessage": "Ima failed",
}],
"error": True,
},
{
"id": "s2",
"label": "test_failing",
"created": 1505824780,
"responseTime": None,
"assertions": None,
"error": True,
},
{
"id": "s3",
"label": "test_passing",
"created": 1505824780,
"responseTime": None,
"assertions": None,
"error": False,
}
]
}}})
obj = FunctionalBZAReader(ROOT_LOGGER)
obj.master = Master(data={'id': 1})
mock.apply(obj.master)
samples = [x for x in obj.read(True)]
self.assertEquals(3, len(samples))
self.assertEqual(["BROKEN", "FAILED", "PASSED"], [sample.status for sample in samples])
self.assertEqual(samples[0].error_msg, "Ima failed")
self.assertEqual(samples[0].start_time, 1505824780)
self.assertEqual(samples[0].duration, 0.0)
self.assertEqual(["test_breaking", "test_failing", "test_passing"], [sample.test_case for sample in samples])
self.assertEqual(samples[0].test_suite, "Tests")
| []
| []
| [
"HOME"
]
| [] | ["HOME"] | python | 1 | 0 | |
library/src/main/java/hendrawd/storageutil/library/StorageUtil.java | package hendrawd.storageutil.library;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Helper class for getting all storages directories in an Android device
* <a href="https://stackoverflow.com/a/40582634/3940133">Solution of this problem</a>
* Consider to use
* <a href="https://developer.android.com/guide/topics/providers/document-provider">StorageAccessFramework(SAF)</>
* if your min SDK version is 19 and your requirement is just for browse and open documents, images, and other files
*
* @author Dmitriy Lozenko, HendraWD
*/
public class StorageUtil {
// Primary physical SD-CARD (not emulated)
private static final String EXTERNAL_STORAGE = System.getenv("EXTERNAL_STORAGE");
// All Secondary SD-CARDs (all exclude primary) separated by File.pathSeparator, i.e: ":", ";"
private static final String SECONDARY_STORAGES = System.getenv("SECONDARY_STORAGE");
// Primary emulated SD-CARD
private static final String EMULATED_STORAGE_TARGET = System.getenv("EMULATED_STORAGE_TARGET");
// PhysicalPaths based on phone model
@SuppressLint("SdCardPath")
@SuppressWarnings("SpellCheckingInspection")
private static final String[] KNOWN_PHYSICAL_PATHS = new String[]{
"/storage/sdcard0",
"/storage/sdcard1", //Motorola Xoom
"/storage/extsdcard", //Samsung SGS3
"/storage/sdcard0/external_sdcard", //User request
"/mnt/extsdcard",
"/mnt/sdcard/external_sd", //Samsung galaxy family
"/mnt/sdcard/ext_sd",
"/mnt/external_sd",
"/mnt/media_rw/sdcard1", //4.4.2 on CyanogenMod S3
"/removable/microsd", //Asus transformer prime
"/mnt/emmc",
"/storage/external_SD", //LG
"/storage/ext_sd", //HTC One Max
"/storage/removable/sdcard1", //Sony Xperia Z1
"/data/sdext",
"/data/sdext2",
"/data/sdext3",
"/data/sdext4",
"/sdcard1", //Sony Xperia Z
"/sdcard2", //HTC One M8s
"/storage/microsd" //ASUS ZenFone 2
};
/**
* Returns all available storages in the system (include emulated)
* <p/>
* Warning: Hack! Based on Android source code of version 4.3 (API 18)
* Because there is no standard way to get it.
*
* @return paths to all available storages in the system (include emulated)
*/
public static String[] getStorageDirectories(Context context) {
// Final set of paths
final Set<String> availableDirectoriesSet = new HashSet<>();
if (!TextUtils.isEmpty(EMULATED_STORAGE_TARGET)) {
// Device has an emulated storage
availableDirectoriesSet.add(getEmulatedStorageTarget());
} else {
// Device doesn't have an emulated storage
availableDirectoriesSet.addAll(getExternalStorage(context));
}
// Add all secondary storages
Collections.addAll(availableDirectoriesSet, getAllSecondaryStorages());
String[] storagesArray = new String[availableDirectoriesSet.size()];
return availableDirectoriesSet.toArray(storagesArray);
}
private static Set<String> getExternalStorage(Context context) {
final Set<String> availableDirectoriesSet = new HashSet<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Solution of empty raw emulated storage for android version >= marshmallow
// because the EXTERNAL_STORAGE become something like: "/Storage/A5F9-15F4",
// so we can't access it directly
File[] files = getExternalFilesDirs(context, null);
for (File file : files) {
if (file != null) {
String applicationSpecificAbsolutePath = file.getAbsolutePath();
String rootPath = applicationSpecificAbsolutePath.substring(
0,
applicationSpecificAbsolutePath.indexOf("Android/data")
);
availableDirectoriesSet.add(rootPath);
}
}
} else {
if (TextUtils.isEmpty(EXTERNAL_STORAGE)) {
availableDirectoriesSet.addAll(getAvailablePhysicalPaths());
} else {
// Device has physical external storage; use plain paths.
availableDirectoriesSet.add(EXTERNAL_STORAGE);
}
}
return availableDirectoriesSet;
}
private static String getEmulatedStorageTarget() {
String rawStorageId = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// External storage paths should have storageId in the last segment
// i.e: "/storage/emulated/storageId" where storageId is 0, 1, 2, ...
final String path = Environment.getExternalStorageDirectory().getAbsolutePath();
final String[] folders = path.split(File.separator);
final String lastSegment = folders[folders.length - 1];
if (!TextUtils.isEmpty(lastSegment) && TextUtils.isDigitsOnly(lastSegment)) {
rawStorageId = lastSegment;
}
}
if (TextUtils.isEmpty(rawStorageId)) {
return EMULATED_STORAGE_TARGET;
} else {
return EMULATED_STORAGE_TARGET + File.separator + rawStorageId;
}
}
private static String[] getAllSecondaryStorages() {
if (!TextUtils.isEmpty(SECONDARY_STORAGES)) {
// All Secondary SD-CARDs split into array
return SECONDARY_STORAGES.split(File.pathSeparator);
}
return new String[0];
}
/**
* Filter available physical paths from known physical paths
*
* @return List of available physical paths from current device
*/
private static List<String> getAvailablePhysicalPaths() {
List<String> availablePhysicalPaths = new ArrayList<>();
for (String physicalPath : KNOWN_PHYSICAL_PATHS) {
File file = new File(physicalPath);
if (file.exists()) {
availablePhysicalPaths.add(physicalPath);
}
}
return availablePhysicalPaths;
}
/**
* Returns absolute paths to application-specific directories on all
* external storage devices where the application can place persistent files
* it owns. These files are internal to the application, and not typically
* visible to the user as media.
* <p>
* This is like {@link Context#getFilesDir()} in that these files will be
* deleted when the application is uninstalled, however there are some
* important differences:
* <ul>
* <li>External files are not always available: they will disappear if the
* user mounts the external storage on a computer or removes it.
* <li>There is no security enforced with these files.
* </ul>
* <p>
* External storage devices returned here are considered a permanent part of
* the device, including both emulated external storage and physical media
* slots, such as SD cards in a battery compartment. The returned paths do
* not include transient devices, such as USB flash drives.
* <p>
* An application may store data on any or all of the returned devices. For
* example, an app may choose to store large files on the device with the
* most available space, as measured by {@link android.os.StatFs}.
* <p>
* Starting in {@link android.os.Build.VERSION_CODES#KITKAT}, no permissions
* are required to write to the returned paths; they're always accessible to
* the calling app. Before then,
* {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} is required to
* write. Write access outside of these paths on secondary external storage
* devices is not available. To request external storage access in a
* backwards compatible way, consider using {@code android:maxSdkVersion}
* like this:
*
* <pre class="prettyprint"><uses-permission
* android:name="android.permission.WRITE_EXTERNAL_STORAGE"
* android:maxSdkVersion="18" /></pre>
* <p>
* The first path returned is the same as
* {@link Context#getExternalFilesDir(String)}. Returned paths may be
* {@code null} if a storage device is unavailable.
*
* @see Context#getExternalFilesDir(String)
*/
private static File[] getExternalFilesDirs(Context context, String type) {
if (Build.VERSION.SDK_INT >= 19) {
return context.getExternalFilesDirs(type);
} else {
return new File[]{context.getExternalFilesDir(type)};
}
}
}
| [
"\"EXTERNAL_STORAGE\"",
"\"SECONDARY_STORAGE\"",
"\"EMULATED_STORAGE_TARGET\""
]
| []
| [
"EMULATED_STORAGE_TARGET",
"SECONDARY_STORAGE",
"EXTERNAL_STORAGE"
]
| [] | ["EMULATED_STORAGE_TARGET", "SECONDARY_STORAGE", "EXTERNAL_STORAGE"] | java | 3 | 0 | |
registry/nats/environment_test.go | package nats_test
import (
"os"
"testing"
log "github.com/btccom/go-micro/v2/logger"
"github.com/btccom/go-micro/v2/registry"
"github.com/btccom/go-micro-plugins/registry/nats/v2"
)
type environment struct {
registryOne registry.Registry
registryTwo registry.Registry
registryThree registry.Registry
serviceOne registry.Service
serviceTwo registry.Service
nodeOne registry.Node
nodeTwo registry.Node
nodeThree registry.Node
}
var e environment
func TestMain(m *testing.M) {
natsURL := os.Getenv("NATS_URL")
if natsURL == "" {
log.Infof("NATS_URL is undefined - skipping tests")
return
}
e.registryOne = nats.NewRegistry(registry.Addrs(natsURL), nats.Quorum(1))
e.registryTwo = nats.NewRegistry(registry.Addrs(natsURL), nats.Quorum(1))
e.registryThree = nats.NewRegistry(registry.Addrs(natsURL), nats.Quorum(1))
e.serviceOne.Name = "one"
e.serviceOne.Version = "default"
e.serviceOne.Nodes = []*registry.Node{&e.nodeOne}
e.serviceTwo.Name = "two"
e.serviceTwo.Version = "default"
e.serviceTwo.Nodes = []*registry.Node{&e.nodeOne, &e.nodeTwo}
e.nodeOne.Id = "one"
e.nodeTwo.Id = "two"
e.nodeThree.Id = "three"
if err := e.registryOne.Register(&e.serviceOne); err != nil {
log.Fatal(err)
}
if err := e.registryOne.Register(&e.serviceTwo); err != nil {
log.Fatal(err)
}
result := m.Run()
if err := e.registryOne.Deregister(&e.serviceOne); err != nil {
log.Fatal(err)
}
if err := e.registryOne.Deregister(&e.serviceTwo); err != nil {
log.Fatal(err)
}
os.Exit(result)
}
| [
"\"NATS_URL\""
]
| []
| [
"NATS_URL"
]
| [] | ["NATS_URL"] | go | 1 | 0 | |
src/main.go | package main
import (
"encoding/json"
"flag"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
)
var token string
func handler(w http.ResponseWriter, r *http.Request) {
client := &http.Client{}
// Get user's servers
request, _ := http.NewRequest("GET", "https://api.online.net/api/v1/server", nil)
request.Header.Add("Authorization", "Bearer " + token)
response, err := client.Do(request)
if err != nil {
log.Println("Error while doing GET /api/v1/servers")
w.WriteHeader(503)
return
}
if response.StatusCode != 200 {
log.Println("Server return HTTP code " + strconv.Itoa(response.StatusCode) + " on GET /api/v1/servers")
w.WriteHeader(503)
return
}
body, _ := ioutil.ReadAll(response.Body)
var servers []string
_ = json.Unmarshal(body, &servers)
// Display help
_, _ = w.Write([]byte("# HELP dedibackup_active Indicates if you enabled the backup space storage on your panel\n"))
_, _ = w.Write([]byte("# TYPE dedibackup_active gauge\n"))
_, _ = w.Write([]byte("# HELP dedibackup_total_bytes Indicates the number of bytes on your backup plan\n"))
_, _ = w.Write([]byte("# TYPE dedibackup_total_bytes gauge\n"))
_, _ = w.Write([]byte("# HELP dedibackup_used_bytes Indicates the number of bytes used on your backup plan\n"))
_, _ = w.Write([]byte("# TYPE dedibackup_used_bytes gauge\n"))
_, _ = w.Write([]byte("# HELP dedibackup_total_files_number Indicates the number of files you can create on your backup plan\n"))
_, _ = w.Write([]byte("# TYPE dedibackup_total_files_number gauge\n"))
_, _ = w.Write([]byte("# HELP dedibackup_used_files_number Indicates the number of files you are using on your backup plan\n"))
_, _ = w.Write([]byte("# TYPE dedibackup_used_files_number gauge\n"))
// For each server, get backup status, and append metrics
for _, k := range servers {
tmp := strings.Split(k, "/")
request, _ := http.NewRequest("GET", "https://api.online.net/api/v1/server/backup/"+tmp[len(tmp)-1], nil)
request.Header.Add("Authorization", "Bearer " + token)
response, err := client.Do(request)
if err != nil {
log.Println("Error while doing GET /api/v1/servers/backup/"+tmp[len(tmp)-1])
continue
}
if response.StatusCode != 200 {
log.Println("Server return HTTP code " + strconv.Itoa(response.StatusCode) + " on GET /api/v1/servers/backup"+tmp[len(tmp)-1])
continue
}
body, _ := ioutil.ReadAll(response.Body)
var data BackupStatus
_ = json.Unmarshal(body, &data)
active := "0"
if data.Active {
active = "1"
}
_, _ = w.Write([]byte("dedibackup_active{server_id=\"" + tmp[len(tmp)-1] + "\"} " + active + "\n"))
_, _ = w.Write([]byte("dedibackup_total_bytes{server_id=\"" + tmp[len(tmp)-1] + "\"} " + strconv.Itoa(data.QuotaSpace) + "\n"))
_, _ = w.Write([]byte("dedibackup_used_bytes{server_id=\"" + tmp[len(tmp)-1] + "\"} " + strconv.Itoa(data.QuotaSpaceUsed) + "\n"))
_, _ = w.Write([]byte("dedibackup_total_files_number{server_id=\"" + tmp[len(tmp)-1] + "\"} " + strconv.Itoa(data.QuotaFiles) + "\n"))
_, _ = w.Write([]byte("dedibackup_used_files_number{server_id=\"" + tmp[len(tmp)-1] + "\"} " + strconv.Itoa(data.QuotaFilesUsed) + "\n"))
}
}
func main() {
tokenPtr := flag.String("token", "", "Online API Token")
portPtr := flag.Int("port", 9101, "Port to bind on")
flag.Parse()
token = *tokenPtr
if token == "" {
//Try to get from environment
token = os.Getenv("DEDIBOX_API_TOKEN")
}
if token == "" {
//Exit with error : no token provided
log.Fatal("No token provided.")
}
http.HandleFunc("/metrics", handler)
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(*portPtr), nil))
}
| [
"\"DEDIBOX_API_TOKEN\""
]
| []
| [
"DEDIBOX_API_TOKEN"
]
| [] | ["DEDIBOX_API_TOKEN"] | go | 1 | 0 | |
enterprise/internal/insights/background/background.go | package background
import (
"context"
"database/sql"
"os"
"strconv"
"github.com/sourcegraph/sourcegraph/enterprise/internal/insights/background/pings"
"github.com/sourcegraph/sourcegraph/internal/database"
"github.com/sourcegraph/sourcegraph/enterprise/internal/insights/discovery"
"github.com/sourcegraph/sourcegraph/enterprise/internal/insights/compression"
"github.com/inconshreveable/log15"
"github.com/opentracing/opentracing-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/sourcegraph/sourcegraph/enterprise/internal/insights/background/queryrunner"
"github.com/sourcegraph/sourcegraph/enterprise/internal/insights/store"
"github.com/sourcegraph/sourcegraph/internal/database/basestore"
"github.com/sourcegraph/sourcegraph/internal/goroutine"
"github.com/sourcegraph/sourcegraph/internal/observation"
"github.com/sourcegraph/sourcegraph/internal/trace"
"github.com/sourcegraph/sourcegraph/internal/workerutil"
"github.com/sourcegraph/sourcegraph/internal/workerutil/dbworker"
)
// GetBackgroundJobs is the main entrypoint which starts background jobs for code insights. It is
// called from the worker service.
func GetBackgroundJobs(ctx context.Context, mainAppDB *sql.DB, insightsDB *sql.DB) []goroutine.BackgroundRoutine {
insightPermStore := store.NewInsightPermissionStore(mainAppDB)
insightsStore := store.New(insightsDB, insightPermStore)
// Create a base store to be used for storing worker state. We store this in the main app Postgres
// DB, not the TimescaleDB (which we use only for storing insights data.)
workerBaseStore := basestore.NewWithDB(mainAppDB, sql.TxOptions{})
// Create basic metrics for recording information about background jobs.
observationContext := &observation.Context{
Logger: log15.Root(),
Tracer: &trace.Tracer{Tracer: opentracing.GlobalTracer()},
Registerer: prometheus.DefaultRegisterer,
}
insightsMetadataStore := store.NewInsightStore(insightsDB)
// Start background goroutines for all of our workers.
// The query runner worker is started in a separate routine so it can benefit from horizontal scaling.
routines := []goroutine.BackgroundRoutine{
// Register the background goroutine which discovers and enqueues insights work.
newInsightEnqueuer(ctx, workerBaseStore, insightsMetadataStore, observationContext),
// TODO(slimsag): future: register another worker here for webhook querying.
}
// todo(insights) add setting to disable this indexer
routines = append(routines, compression.NewCommitIndexerWorker(ctx, database.NewDB(mainAppDB), insightsDB, observationContext))
// Register the background goroutine which discovers historical gaps in data and enqueues
// work to fill them - if not disabled.
disableHistorical, _ := strconv.ParseBool(os.Getenv("DISABLE_CODE_INSIGHTS_HISTORICAL"))
if !disableHistorical {
routines = append(routines, newInsightHistoricalEnqueuer(ctx, workerBaseStore, insightsMetadataStore, insightsStore, observationContext))
}
// this flag will allow users to ENABLE the settings sync job. This is a last resort option if for some reason the new GraphQL API does not work. This
// should not be published as an option externally, and will be deprecated as soon as possible.
enableSync, _ := strconv.ParseBool(os.Getenv("ENABLE_CODE_INSIGHTS_SETTINGS_STORAGE"))
if enableSync {
log15.Warn("Enabling Code Insights Settings Storage - This is a deprecated functionality!")
routines = append(routines, discovery.NewMigrateSettingInsightsJob(ctx, mainAppDB, insightsDB))
}
routines = append(
routines,
pings.NewInsightsPingEmitterJob(ctx, mainAppDB, insightsDB),
NewInsightsDataPrunerJob(ctx, mainAppDB, insightsDB),
)
// I suspect the linter doesn't like this not being used when I delete it. So let's try this.
enableLicenseCheck := false
if enableLicenseCheck {
routines = append(routines, NewLicenseCheckJob(ctx, mainAppDB, insightsDB))
}
return routines
}
// GetBackgroundQueryRunnerJob is the main entrypoint for starting the background jobs for code
// insights query runner. It is called from the worker service.
func GetBackgroundQueryRunnerJob(ctx context.Context, mainAppDB *sql.DB, insightsDB *sql.DB) []goroutine.BackgroundRoutine {
insightPermStore := store.NewInsightPermissionStore(mainAppDB)
insightsStore := store.New(insightsDB, insightPermStore)
// Create a base store to be used for storing worker state. We store this in the main app Postgres
// DB, not the TimescaleDB (which we use only for storing insights data.)
workerBaseStore := basestore.NewWithDB(mainAppDB, sql.TxOptions{})
// Create basic metrics for recording information about background jobs.
observationContext := &observation.Context{
Logger: log15.Root(),
Tracer: &trace.Tracer{Tracer: opentracing.GlobalTracer()},
Registerer: prometheus.DefaultRegisterer,
}
queryRunnerWorkerMetrics, queryRunnerResetterMetrics := newWorkerMetrics(observationContext, "query_runner_worker")
workerStore := queryrunner.CreateDBWorkerStore(workerBaseStore, observationContext)
return []goroutine.BackgroundRoutine{
// Register the query-runner worker and resetter, which executes search queries and records
// results to TimescaleDB.
queryrunner.NewWorker(ctx, workerStore, insightsStore, queryRunnerWorkerMetrics),
queryrunner.NewResetter(ctx, workerStore, queryRunnerResetterMetrics),
queryrunner.NewCleaner(ctx, workerBaseStore, observationContext),
}
}
// newWorkerMetrics returns a basic set of metrics to be used for a worker and its resetter:
//
// * WorkerMetrics records worker operations & number of jobs.
// * ResetterMetrics records the number of jobs that got reset because workers timed out / took too
// long.
//
// Individual insights workers may then _also_ want to register their own metrics, if desired, in
// their NewWorker functions.
func newWorkerMetrics(observationContext *observation.Context, workerName string) (workerutil.WorkerMetrics, dbworker.ResetterMetrics) {
workerMetrics := workerutil.NewMetrics(observationContext, workerName+"_processor")
resetterMetrics := dbworker.NewMetrics(observationContext, workerName)
return workerMetrics, *resetterMetrics
}
| [
"\"DISABLE_CODE_INSIGHTS_HISTORICAL\"",
"\"ENABLE_CODE_INSIGHTS_SETTINGS_STORAGE\""
]
| []
| [
"DISABLE_CODE_INSIGHTS_HISTORICAL",
"ENABLE_CODE_INSIGHTS_SETTINGS_STORAGE"
]
| [] | ["DISABLE_CODE_INSIGHTS_HISTORICAL", "ENABLE_CODE_INSIGHTS_SETTINGS_STORAGE"] | go | 2 | 0 | |
templates_advanced_lab/templates_advanced/asgi.py | """
ASGI config for templates_advanced project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'templates_advanced.settings')
application = get_asgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
notifications/notifications.go | package notifications
import (
"fmt"
"os"
"time"
"github.com/asobti/kube-monkey/chaos"
"github.com/asobti/kube-monkey/config"
"github.com/asobti/kube-monkey/schedule"
"github.com/golang/glog"
)
func Send(client Client, endpoint string, msg string, headers map[string]string) error {
if err := client.Request(endpoint, msg, headers); err != nil {
return fmt.Errorf("send request: %v", err)
}
return nil
}
func ReportSchedule(client Client, schedule *schedule.Schedule) bool {
success := true
receiver := config.NotificationsAttacks()
msg := fmt.Sprintf("{\"text\": \"\n%s\n\"}", schedule)
glog.V(1).Infof("reporting next schedule")
if err := Send(client, receiver.Endpoint, msg, toHeaders(receiver.Headers)); err != nil {
glog.Errorf("error reporting next schedule")
success = false
}
return success
}
func ReportAttack(client Client, result *chaos.Result, time time.Time) bool {
success := true
receiver := config.NotificationsAttacks()
errorString := ""
if result.Error() != nil {
errorString = result.Error().Error()
}
msg := ReplacePlaceholders(receiver.Message, result.Victim().Name(), result.Victim().Kind(), result.Victim().Namespace(), errorString, time, os.Getenv("KUBE_MONKEY_ID"))
glog.V(1).Infof("reporting attack for %s %s to %s with message %s\n", result.Victim().Kind(), result.Victim().Name(), receiver.Endpoint, msg)
if err := Send(client, receiver.Endpoint, msg, toHeaders(receiver.Headers)); err != nil {
glog.Errorf("error reporting attack for %s %s to %s with message %s, error: %v\n", result.Victim().Kind(), result.Victim().Name(), receiver.Endpoint, msg, err)
success = false
}
return success
}
| [
"\"KUBE_MONKEY_ID\""
]
| []
| [
"KUBE_MONKEY_ID"
]
| [] | ["KUBE_MONKEY_ID"] | go | 1 | 0 | |
src/main.go | package main
import (
"errors"
"fmt"
"os"
"strings"
"time"
"sync"
"mime"
"path/filepath"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
//"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/k0kubun/pp"
"github.com/dogwood008/members_only_cdn/cwlogs"
"github.com/dogwood008/members_only_cdn/authorization"
)
var (
errInvalidHash = errors.New("Given Auth Token is Invalid")
errNoUserHashs = errors.New("UserID Hash Map is Empty")
errInvalidDlOrUl = errors.New("Given was not \"UL\" or \"DB\"")
envMapJSONString = os.Getenv("USER_TOKEN_MAP_JSON")
envS3ULBucketName = os.Getenv("UL_BUCKET_NAME")
envS3DLBucketName = os.Getenv("DL_BUCKET_NAME")
envLogGroupName = os.Getenv("CLOUD_WATCH_LOG_GROUP_NAME")
envCloudWatchSetup = getEnv("CLOUD_WATCH_ENABLE_SETUP", "false") == "true"
envAWSRegion = os.Getenv("AWS_REGION")
awsSession = session.New()
awsConfig = aws.NewConfig().WithRegion(envAWSRegion)
cloudWatchLogs = cwlogs.CWLogs {Setup: envCloudWatchSetup, LogGroupName: &envLogGroupName}
)
type params struct {
ProjectID string
ObjectID string
UserIDInPath string
FileID string
}
// https://stackoverflow.com/questions/40326540/how-to-assign-default-value-if-env-var-is-empty
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
func userID(hash string, jsonString string) (string, error) {
if jsonString == "" {
return "", errNoUserHashs
}
var extractedUserID string
var intf interface{}
bytes := []byte(jsonString)
json.Unmarshal(bytes, &intf)
hmm := intf.(map[string]interface{})
hmmm :=hmm["Maps"].(map[string]interface{})
uncastUID := hmmm[hash]
if uncastUID == nil {
return "", errInvalidHash
}
extractedUserID = uncastUID.(string)
return extractedUserID, nil
}
func auth(authHeader string) (string, error) {
var hexToken, authRawToken string
authRawToken = strings.Replace(authHeader, "Bearer ", "", 1)
bytes := sha256.Sum256([]byte(authRawToken))
hexToken = hex.EncodeToString(bytes[:])
uid, err := userID(hexToken, envMapJSONString)
return uid, err
}
func s3GetURLWithPreSign (keyName string, bucketName string, region string) (string, error) {
// https://qiita.com/sakayuka/items/1328c1ad93f9b982a0d5
svc := s3.New(awsSession, awsConfig)
req, _ := svc.GetObjectRequest(&s3.GetObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(keyName),
})
url, err := req.Presign(time.Minute * 10)
pp.Print(err)
return url, err
}
func fileType (keyName string) (string) {
ext := filepath.Ext(strings.Replace(keyName, "/upload", "", 1))
mime.AddExtensionType(".csv", "text/csv")
mime.AddExtensionType(".tsv", "text/tab-separated-values")
mime.AddExtensionType(".txt", "text/plain")
return mime.TypeByExtension(ext)
}
func s3URLWithPreSign (dlOrUl string, keyName string, bucketName string, region string) (string, error) {
switch dlOrUl {
case "DL": return s3GetURLWithPreSign(keyName, bucketName, region)
case "UL": return s3PutURLWithPreSign(keyName, bucketName, region)
}
return "", errInvalidDlOrUl
}
// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#PutObjectInput
// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutObjectRequest
// https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL
// https://www.whatsajunting.com/posts/s3-presigned/
func s3PutURLWithPreSign (keyName string, bucketName string, region string) (string, error) {
svc := s3.New(awsSession, awsConfig)
input := s3.PutObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(keyName),
// ContentType: aws.String(fileType(keyName)),
// ACL: aws.String("private"),
}
req, _ := svc.PutObjectRequest(&input)
url, err := req.Presign(time.Minute * 10)
pp.Print(err)
return url, err
}
func outputLog2CloudWatch (userID string, s3Key string, bucketName string, err string) {
log := fmt.Sprintf(",%s,\"s3://%s%s\",\"%s\"", userID, bucketName, s3Key, err)
cloudWatchLogs.OutputLog2CloudWatch(&log)
}
func checkPermittedFileID (ch chan<- bool, waitGroup *sync.WaitGroup, params *params) {
isOkToAllow := authorization.Authorize(
params.ProjectID, params.ObjectID, params.UserIDInPath, params.FileID)
ch <- isOkToAllow
waitGroup.Done()
}
func extractParams(request events.APIGatewayProxyRequest) (*params) {
// Path: /v1/projects/{project_id}/objects/{object_id}/users/{user_id}/files/{id_full}
p := request.PathParameters
projectID := p["project_id"]
objectID := p["object_id"]
userIDInPath := p["user_id"]
fileID := p["file_id"]
paramsStruct := params {
ProjectID: projectID,
ObjectID: objectID,
UserIDInPath: userIDInPath,
FileID : fileID,
}
return ¶msStruct
}
func userIDFromAuthHeader (authHeader string, userIDInPath string) (string, error){
userIDFromAuthHeader, err := auth(authHeader)
fmt.Printf("userIDFromAuthHeader: %s\n", userIDFromAuthHeader)
fmt.Printf("userIDInPath: %s\n", userIDInPath)
if userIDFromAuthHeader != userIDInPath {
err = errInvalidHash
}
return userIDFromAuthHeader, err
}
func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
params := extractParams(request)
if strings.HasSuffix(request.Path, "/upload") {
return upload(request, params)
}
return download(request, params)
}
func buildErrorResponseForAuthHeader(err error, userIDInPath string, s3Key string, bucketName string) (events.APIGatewayProxyResponse) {
var code int
var body string
switch err {
case errNoUserHashs:
code = 500; body = "Server setup does not finished. (Error code: 001)"
case errInvalidHash:
code = 403; body = "Invalid auth token given. (Error code: 002)"
default:
code = 500; body = "InternalServerError. (Error code: 005)"
}
log := fmt.Sprintf("userIDFromAuthHeader:%s", userIDFromAuthHeader)
outputLog2CloudWatch(userIDInPath, s3Key, bucketName, log)
return events.APIGatewayProxyResponse{
Body : fmt.Sprintf("{\"error\":\"%s\"}", body),
StatusCode: code,
}
}
func buildErrorResponseWithS3URL (userIDInPath string, s3Key string, bucketName string) (events.APIGatewayProxyResponse) {
body := "Internal server error (Error code: 003)"
outputLog2CloudWatch(userIDInPath, s3Key, bucketName, body)
return events.APIGatewayProxyResponse{
Body : fmt.Sprintf("{\"error\":\"%s\"}", body),
StatusCode: 500,
}
}
func buildCannotLoggingToCloudWatchErrorResponse () (events.APIGatewayProxyResponse) {
body := "Internal server error (Error code: 006)"
return events.APIGatewayProxyResponse{
Body : fmt.Sprintf("{\"error\":\"%s\"}", body),
StatusCode: 500,
}
}
func download(request events.APIGatewayProxyRequest, params *params) (events.APIGatewayProxyResponse, error) {
return workflow(request, params, "DL")
}
func upload(request events.APIGatewayProxyRequest, params *params) (events.APIGatewayProxyResponse, error) {
return workflow(request, params, "UL")
}
func workflow(request events.APIGatewayProxyRequest, params *params, dlOrUl string) (events.APIGatewayProxyResponse, error) {
var bucketName string
var successCode int
switch dlOrUl {
case "DL": successCode = 302; bucketName = envS3DLBucketName
case "UL": successCode = 200; bucketName = envS3ULBucketName
default:
pp.Print("Invalid dlOrUl given: %s", dlOrUl)
return buildCannotLoggingToCloudWatchErrorResponse(), nil
}
// Check permission parallelly for time efficiency
waitGroup := &sync.WaitGroup{}
waitGroup.Add(1)
checkPermissionCh := make(chan bool, 1)
defer close(checkPermissionCh) // https://qiita.com/convto/items/b2e95e549f35a1beb0b8
go checkPermittedFileID(checkPermissionCh, waitGroup, params)
s3Key := fmt.Sprintf("/%s/%s/%s", params.ProjectID, params.ObjectID, params.FileID)
userIDFromAuthHeader, err := userIDFromAuthHeader(request.Headers["Authorization"], params.UserIDInPath)
if userIDFromAuthHeader != params.UserIDInPath {
err = errInvalidHash
}
if err != nil {
return buildErrorResponseForAuthHeader(err, params.UserIDInPath, s3Key, bucketName), nil
}
fmt.Printf("s3Key: %s\n", s3Key)
presignedURL, err := s3URLWithPreSign(dlOrUl, s3Key, bucketName, envAWSRegion)
if err != nil {
return buildErrorResponseWithS3URL(params.UserIDInPath, s3Key, bucketName), nil
}
waitGroup.Wait() // Wait for checking permissions in dynamodb
isOkToAllow := <-checkPermissionCh
if !isOkToAllow {
body := "The requested file id is invalid for you. (Error code: 004)"
outputLog2CloudWatch(params.UserIDInPath, s3Key, bucketName, body)
return events.APIGatewayProxyResponse{
Body : fmt.Sprintf("{\"error\":\"%s\"}", body),
StatusCode: 403,
}, nil
}
outputLog2CloudWatch(params.UserIDInPath, s3Key, bucketName, "succeeded")
respHeaders := map[string]string{}
if dlOrUl == "DL" {
respHeaders["Location"] = presignedURL
}
return events.APIGatewayProxyResponse{
Body : fmt.Sprintf("{\"url\":\"%s\"}", presignedURL),
StatusCode: successCode,
Headers : respHeaders,
}, nil
}
func main() {
lambda.Start(handler)
}
| [
"\"USER_TOKEN_MAP_JSON\"",
"\"UL_BUCKET_NAME\"",
"\"DL_BUCKET_NAME\"",
"\"CLOUD_WATCH_LOG_GROUP_NAME\"",
"\"AWS_REGION\""
]
| []
| [
"CLOUD_WATCH_LOG_GROUP_NAME",
"AWS_REGION",
"DL_BUCKET_NAME",
"USER_TOKEN_MAP_JSON",
"UL_BUCKET_NAME"
]
| [] | ["CLOUD_WATCH_LOG_GROUP_NAME", "AWS_REGION", "DL_BUCKET_NAME", "USER_TOKEN_MAP_JSON", "UL_BUCKET_NAME"] | go | 5 | 0 | |
src/agent/k8s-rest-agent/src/server/urls.py | """server URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
import os
from api.routes.hello.views import HelloViewSet
from django.conf import settings
from django.contrib import admin
from django.urls import path, include
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions
from rest_framework.routers import DefaultRouter
DEBUG = getattr(settings, "DEBUG", False)
VERSION = os.getenv("API_VERSION", "v1")
router = DefaultRouter(trailing_slash=False)
router.register("hello", HelloViewSet, basename="hello")
router.include_root_view = False
urlpatterns = router.urls
swagger_info = openapi.Info(
title="Django Example API",
default_version=VERSION,
description="""
Django Example API
""",
)
SchemaView = get_schema_view(
info=swagger_info,
validators=["flex"],
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns += [
path("admin/", admin.site.urls),
path("jet/", include("jet.urls", "jet")),
]
if DEBUG:
urlpatterns += [
path(
"docs/",
SchemaView.with_ui("swagger", cache_timeout=0),
name="docs",
),
path(
"redoc/",
SchemaView.with_ui("redoc", cache_timeout=0),
name="redoc",
),
]
| []
| []
| [
"API_VERSION"
]
| [] | ["API_VERSION"] | python | 1 | 0 | |
source/c1cconnectorapi.py | import urllib3
import json
import logging
import os
logger = logging.getLogger()
GET = 'GET'
POST = 'POST'
DELETE = 'DELETE'
class CloudOneConformityConnector:
def __init__(self, api_key):
self.base_url = 'https://{region}-api.cloudconformity.com/v1'.format(region=os.environ['ConformityRegionEndpoint'])
self.api_key = api_key
self.headers = {
'Content-Type': 'application/vnd.api+json',
'Authorization': f'ApiKey {api_key}'.format(api_key=api_key)
}
self.external_id = ''
self.http = urllib3.PoolManager()
def request(self, method, endpoint, body=None):
if body is not None:
body = bytes(json.dumps(body), encoding='utf-8')
request_response = self.http.request(method, f'{self.base_url}{endpoint}', headers=self.headers, body=body)
logger.info(f'http status for call to {endpoint} '
f'was: {request_response.status} with response: {request_response.data}')
response = json.loads(request_response.data.decode('utf-8'))
return response
def create_external_id(self):
return self.request(POST, '/external-ids')['data']['id']
def get_external_id(self):
self.external_id = self.request(GET, '/organisation/external-id')['data']['id']
if self.external_id is None:
self.external_id = self.create_external_id()
return self.external_id
def add_account(self, role_arn):
body = {
"data": {
"type": "account",
"attributes": {
"name": role_arn.rsplit(':')[4],
"environment": "ControlTower",
"access": {
"keys": {
"roleArn": role_arn,
"externalId": self.external_id
}
},
"costPackage": False,
"hasRealTimeMonitoring": True
}
}
}
return self.request(POST, '/accounts', body)
def remove_account(self, aws_account_id):
conformity_account_id = self.get_account_id(aws_account_id)
return self.request(DELETE, f'/accounts/{conformity_account_id}')
def get_account_id(self, aws_account_id):
try:
all_accounts = self.request(GET, '/accounts')
for account in all_accounts.get('data'):
if account.get('attributes').get('awsaccount-id') == aws_account_id:
logger.info('Found account id: ' + account.get('id') + ' for ' + aws_account_id)
return account.get('id')
except Exception as e:
logger.info(e)
raise e
| []
| []
| [
"ConformityRegionEndpoint"
]
| [] | ["ConformityRegionEndpoint"] | python | 1 | 0 | |
epixdeploy/wsgi.py | """
WSGI config for epixdeploy project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'epixdeploy.settings')
application = get_wsgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
achristos/asgi.py | """
ASGI config for achristos project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'achristos.settings')
application = get_asgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
vendor/github.com/moby/buildkit/util/appdefaults/appdefaults_unix.go | // +build !windows
package appdefaults
import (
"os"
"path/filepath"
"strings"
)
const (
Address = "unix:///run/buildkit/buildkitd.sock"
Root = "/var/lib/buildkit"
ConfigDir = "/etc/buildkit"
)
// UserAddress typically returns /run/user/$UID/buildkit/buildkitd.sock
func UserAddress() string {
// pam_systemd sets XDG_RUNTIME_DIR but not other dirs.
xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR")
if xdgRuntimeDir != "" {
dirs := strings.Split(xdgRuntimeDir, ":")
return "unix://" + filepath.Join(dirs[0], "buildkit", "buildkitd.sock")
}
return Address
}
// EnsureUserAddressDir sets sticky bit on XDG_RUNTIME_DIR if XDG_RUNTIME_DIR is set.
// See https://github.com/opencontainers/runc/issues/1694
func EnsureUserAddressDir() error {
xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR")
if xdgRuntimeDir != "" {
dirs := strings.Split(xdgRuntimeDir, ":")
dir := filepath.Join(dirs[0], "buildkit")
if err := os.MkdirAll(dir, 0700); err != nil {
return err
}
return os.Chmod(dir, 0700|os.ModeSticky)
}
return nil
}
// UserRoot typically returns /home/$USER/.local/share/buildkit
func UserRoot() string {
// pam_systemd sets XDG_RUNTIME_DIR but not other dirs.
xdgDataHome := os.Getenv("XDG_DATA_HOME")
if xdgDataHome != "" {
dirs := strings.Split(xdgDataHome, ":")
return filepath.Join(dirs[0], "buildkit")
}
home := os.Getenv("HOME")
if home != "" {
return filepath.Join(home, ".local", "share", "buildkit")
}
return Root
}
// UserConfigDir returns dir for storing config. /home/$USER/.config/buildkit/
func UserConfigDir() string {
xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
if xdgConfigHome != "" {
return filepath.Join(xdgConfigHome, "buildkit")
}
home := os.Getenv("HOME")
if home != "" {
return filepath.Join(home, ".config", "buildkit")
}
return ConfigDir
}
| [
"\"XDG_RUNTIME_DIR\"",
"\"XDG_RUNTIME_DIR\"",
"\"XDG_DATA_HOME\"",
"\"HOME\"",
"\"XDG_CONFIG_HOME\"",
"\"HOME\""
]
| []
| [
"XDG_RUNTIME_DIR",
"HOME",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME"
]
| [] | ["XDG_RUNTIME_DIR", "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME"] | go | 4 | 0 | |
tests/test_client.py | import os
import unittest
from dotenv import load_dotenv
from culqi import __version__
from culqi.client import Culqi
class ClientTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(ClientTest, self).__init__(*args, **kwargs)
load_dotenv()
self.version = __version__
self.public_key = os.environ.get("API_PUBLIC_KEY")
self.private_key = os.environ.get("API_PRIVATE_KEY")
self.culqi = Culqi(self.public_key, self.private_key)
def test_version(self):
# pylint: disable=protected-access
assert self.culqi._get_version() == self.version
def test_keys(self):
assert self.public_key == self.culqi.public_key
assert self.private_key == self.culqi.private_key
def test_session_headers(self):
session_headers = self.culqi.session.headers
headers = {
"User-Agent": "Culqi-API-Python/{0}".format(self.version),
"Authorization": "Bearer {0}".format(self.private_key),
"Content-type": "application/json",
"Accept": "application/json",
}
assert headers["User-Agent"] == session_headers["User-Agent"]
assert headers["Authorization"] == session_headers["Authorization"]
assert headers["Content-type"] == session_headers["Content-type"]
assert headers["Accept"] == session_headers["Accept"]
if __name__ == "__main__":
unittest.main()
| []
| []
| [
"API_PRIVATE_KEY",
"API_PUBLIC_KEY"
]
| [] | ["API_PRIVATE_KEY", "API_PUBLIC_KEY"] | python | 2 | 0 | |
server/blob/blob-cassandra/src/main/java/org/apache/james/blob/cassandra/CassandraBlobStoreDAO.java | /****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you 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 org.apache.james.blob.cassandra;
import static org.apache.james.util.ReactorUtils.DEFAULT_CONCURRENCY;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.james.backends.cassandra.init.configuration.CassandraConfiguration;
import org.apache.james.blob.api.BlobId;
import org.apache.james.blob.api.BlobStore;
import org.apache.james.blob.api.BlobStoreDAO;
import org.apache.james.blob.api.BucketName;
import org.apache.james.blob.api.ObjectNotFoundException;
import org.apache.james.blob.api.ObjectStoreIOException;
import org.apache.james.metrics.api.Metric;
import org.apache.james.metrics.api.MetricFactory;
import org.apache.james.util.DataChunker;
import org.apache.james.util.ReactorUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.fge.lambdas.Throwing;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteSource;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* WARNING: JAMES-3591 Cassandra is not made to store large binary content, its use will be suboptimal compared to
* alternatives (namely S3 compatible BlobStores backed by for instance S3, MinIO or Ozone)
*/
public class CassandraBlobStoreDAO implements BlobStoreDAO {
public static final boolean LAZY = false;
public static final String CASSANDRA_BLOBSTORE_CL_ONE_MISS_COUNT_METRIC_NAME = "cassandraBlobStoreClOneMisses";
public static final String CASSANDRA_BLOBSTORE_CL_ONE_HIT_COUNT_METRIC_NAME = "cassandraBlobStoreClOneHits";
private static final Logger LOGGER = LoggerFactory.getLogger(CassandraBlobStoreDAO.class);
private final CassandraDefaultBucketDAO defaultBucketDAO;
private final CassandraBucketDAO bucketDAO;
private final CassandraConfiguration configuration;
private final BucketName defaultBucket;
private final MetricFactory metricFactory;
private final Metric metricClOneHitCount;
private final Metric metricClOneMissCount;
@Inject
@VisibleForTesting
public CassandraBlobStoreDAO(CassandraDefaultBucketDAO defaultBucketDAO,
CassandraBucketDAO bucketDAO,
CassandraConfiguration cassandraConfiguration,
@Named(BlobStore.DEFAULT_BUCKET_NAME_QUALIFIER) BucketName defaultBucket,
MetricFactory metricFactory) {
this.defaultBucketDAO = defaultBucketDAO;
this.bucketDAO = bucketDAO;
this.configuration = cassandraConfiguration;
this.defaultBucket = defaultBucket;
this.metricFactory = metricFactory;
this.metricClOneMissCount = metricFactory.generate(CASSANDRA_BLOBSTORE_CL_ONE_MISS_COUNT_METRIC_NAME);
this.metricClOneHitCount = metricFactory.generate(CASSANDRA_BLOBSTORE_CL_ONE_HIT_COUNT_METRIC_NAME);
if (Objects.equals(System.getenv("cassandra.blob.store.disable.startup.warning"), "false")) {
LOGGER.warn("WARNING: JAMES-3591 Cassandra is not made to store large binary content, its use will be suboptimal compared to " +
" alternatives (namely S3 compatible BlobStores backed by for instance S3, MinIO or Ozone)");
}
}
@Override
public InputStream read(BucketName bucketName, BlobId blobId) throws ObjectStoreIOException, ObjectNotFoundException {
return ReactorUtils.toInputStream(readBlobParts(bucketName, blobId));
}
@Override
public Mono<byte[]> readBytes(BucketName bucketName, BlobId blobId) {
return readBlobParts(bucketName, blobId)
.collectList()
.map(this::byteBuffersToBytesArray);
}
@Override
public Mono<Void> save(BucketName bucketName, BlobId blobId, byte[] data) {
Preconditions.checkNotNull(data);
return Mono.fromCallable(() -> DataChunker.chunk(data, configuration.getBlobPartSize()))
.flatMap(chunks -> save(bucketName, blobId, chunks));
}
@Override
public Mono<Void> save(BucketName bucketName, BlobId blobId, InputStream inputStream) {
Preconditions.checkNotNull(bucketName);
Preconditions.checkNotNull(inputStream);
return Mono.fromCallable(() -> DataChunker.chunkStream(inputStream, configuration.getBlobPartSize()))
.flatMap(chunks -> save(bucketName, blobId, chunks))
.onErrorMap(e -> new ObjectStoreIOException("Exception occurred while saving input stream", e));
}
@Override
public Mono<Void> save(BucketName bucketName, BlobId blobId, ByteSource content) {
return Mono.using(content::openBufferedStream,
stream -> save(bucketName, blobId, stream),
Throwing.consumer(InputStream::close).sneakyThrow(),
LAZY);
}
private Mono<Void> save(BucketName bucketName, BlobId blobId, Flux<ByteBuffer> chunksAsFlux) {
return saveBlobParts(bucketName, blobId, chunksAsFlux)
.flatMap(numberOfChunk -> saveBlobPartReference(bucketName, blobId, numberOfChunk));
}
private Mono<Integer> saveBlobParts(BucketName bucketName, BlobId blobId, Flux<ByteBuffer> chunksAsFlux) {
return chunksAsFlux
.index()
.concatMap(pair -> writePart(bucketName, blobId, pair.getT1().intValue(), pair.getT2()))
.count()
.map(Long::intValue);
}
private Mono<?> writePart(BucketName bucketName, BlobId blobId, int position, ByteBuffer data) {
Mono<?> write;
if (isDefaultBucket(bucketName)) {
write = defaultBucketDAO.writePart(data, blobId, position);
} else {
write = bucketDAO.writePart(data, bucketName, blobId, position);
}
int anyNonEmptyValue = 1;
return write.thenReturn(anyNonEmptyValue);
}
private Mono<Void> saveBlobPartReference(BucketName bucketName, BlobId blobId, Integer numberOfChunk) {
if (isDefaultBucket(bucketName)) {
return defaultBucketDAO.saveBlobPartsReferences(blobId, numberOfChunk);
} else {
return bucketDAO.saveBlobPartsReferences(bucketName, blobId, numberOfChunk);
}
}
private boolean isDefaultBucket(BucketName bucketName) {
return bucketName.equals(defaultBucket);
}
@Override
public Mono<Void> delete(BucketName bucketName, BlobId blobId) {
if (isDefaultBucket(bucketName)) {
return defaultBucketDAO.deletePosition(blobId)
.then(defaultBucketDAO.deleteParts(blobId));
} else {
return bucketDAO.deletePosition(bucketName, blobId)
.then(bucketDAO.deleteParts(bucketName, blobId));
}
}
@Override
public Mono<Void> deleteBucket(BucketName bucketName) {
Preconditions.checkNotNull(bucketName);
Preconditions.checkArgument(!isDefaultBucket(bucketName), "Deleting the default bucket is forbidden");
return bucketDAO.listAll()
.filter(bucketNameBlobIdPair -> bucketNameBlobIdPair.getKey().equals(bucketName))
.map(Pair::getValue)
.flatMap(blobId -> delete(bucketName, blobId), DEFAULT_CONCURRENCY)
.then();
}
private Mono<ByteBuffer> readPart(BucketName bucketName, BlobId blobId, Integer partIndex) {
if (configuration.isOptimisticConsistencyLevel()) {
return readPartClOne(bucketName, blobId, partIndex)
.doOnNext(any -> metricClOneHitCount.increment())
.switchIfEmpty(Mono.fromRunnable(metricClOneMissCount::increment)
.then(readPartClDefault(bucketName, blobId, partIndex)));
} else {
return readPartClDefault(bucketName, blobId, partIndex);
}
}
private Mono<ByteBuffer> readPartClOne(BucketName bucketName, BlobId blobId, Integer partIndex) {
if (isDefaultBucket(bucketName)) {
return defaultBucketDAO.readPartClOne(blobId, partIndex);
} else {
return bucketDAO.readPartClOne(bucketName, blobId, partIndex);
}
}
private Mono<ByteBuffer> readPartClDefault(BucketName bucketName, BlobId blobId, Integer partIndex) {
if (isDefaultBucket(bucketName)) {
return defaultBucketDAO.readPart(blobId, partIndex);
} else {
return bucketDAO.readPart(bucketName, blobId, partIndex);
}
}
private Mono<Integer> selectRowCount(BucketName bucketName, BlobId blobId) {
if (configuration.isOptimisticConsistencyLevel()) {
return selectRowCountClOne(bucketName, blobId)
.doOnNext(any -> metricClOneHitCount.increment())
.switchIfEmpty(Mono.fromRunnable(metricClOneMissCount::increment)
.then(selectRowCountClDefault(bucketName, blobId)));
} else {
return selectRowCountClDefault(bucketName, blobId);
}
}
private Mono<Integer> selectRowCountClOne(BucketName bucketName, BlobId blobId) {
if (isDefaultBucket(bucketName)) {
return defaultBucketDAO.selectRowCountClOne(blobId);
} else {
return bucketDAO.selectRowCountClOne(bucketName, blobId);
}
}
private Mono<Integer> selectRowCountClDefault(BucketName bucketName, BlobId blobId) {
if (isDefaultBucket(bucketName)) {
return defaultBucketDAO.selectRowCount(blobId);
} else {
return bucketDAO.selectRowCount(bucketName, blobId);
}
}
private Flux<ByteBuffer> readBlobParts(BucketName bucketName, BlobId blobId) {
return selectRowCount(bucketName, blobId)
.single()
.onErrorMap(NoSuchElementException.class, e ->
new ObjectNotFoundException(String.format("Could not retrieve blob metadata for %s", blobId)))
.flatMapMany(rowCount -> Flux.range(0, rowCount)
.concatMap(partIndex -> readPart(bucketName, blobId, partIndex)
.single()
.onErrorMap(NoSuchElementException.class, e ->
new ObjectNotFoundException(String.format("Missing blob part for blobId %s and position %d", blobId.asString(), partIndex)))));
}
private byte[] byteBuffersToBytesArray(List<ByteBuffer> byteBuffers) {
int targetSize = byteBuffers
.stream()
.mapToInt(ByteBuffer::remaining)
.sum();
return byteBuffers
.stream()
.reduce(ByteBuffer.allocate(targetSize), ByteBuffer::put)
.array();
}
}
| [
"\"cassandra.blob.store.disable.startup.warning\""
]
| []
| [
"cassandra.blob.store.disable.startup.warning"
]
| [] | ["cassandra.blob.store.disable.startup.warning"] | java | 1 | 0 | |
plugins/store/mysql/mysql_test.go | package mysql
import (
"encoding/json"
"os"
"testing"
"time"
_ "github.com/go-sql-driver/mysql"
"go-micro.dev/v4/store"
)
var (
sqlStoreT store.Store
)
func TestMain(m *testing.M) {
if tr := os.Getenv("TRAVIS"); len(tr) > 0 {
os.Exit(0)
}
sqlStoreT = NewStore(
store.Database("testMicro"),
store.Nodes("root:123@(127.0.0.1:3306)/test?charset=utf8&parseTime=true&loc=Asia%2FShanghai"),
)
os.Exit(m.Run())
}
func TestWrite(t *testing.T) {
err := sqlStoreT.Write(
&store.Record{
Key: "test",
Value: []byte("foo2"),
Expiry: time.Second * 200,
},
)
if err != nil {
t.Error(err)
}
}
func TestDelete(t *testing.T) {
err := sqlStoreT.Delete("test")
if err != nil {
t.Error(err)
}
}
func TestRead(t *testing.T) {
records, err := sqlStoreT.Read("test")
if err != nil {
t.Error(err)
}
t.Log(string(records[0].Value))
}
func TestList(t *testing.T) {
records, err := sqlStoreT.List()
if err != nil {
t.Error(err)
} else {
beauty, _ := json.Marshal(records)
t.Log(string(beauty))
}
}
| [
"\"TRAVIS\""
]
| []
| [
"TRAVIS"
]
| [] | ["TRAVIS"] | go | 1 | 0 | |
src/github.com/getlantern/appdir/appdir_windows.go | package appdir
import (
"os"
"path/filepath"
)
func general(app string) string {
return filepath.Join(os.Getenv("APPDATA"), app)
}
func logs(app string) string {
return filepath.Join(general(app), "logs")
}
| [
"\"APPDATA\""
]
| []
| [
"APPDATA"
]
| [] | ["APPDATA"] | go | 1 | 0 | |
main.go | package main
import (
"encoding/json"
"github.com/comail/colog"
"github.com/julienschmidt/httprouter"
"gopkg.in/yaml.v2"
v1autoscaling "k8s.io/api/autoscaling/v1"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/apis/autoscaling"
schedulerapi "k8s.io/kubernetes/pkg/scheduler/apis/extender/v1"
"log"
"math"
"net/http"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"fmt"
)
const (
versionPath = "/version"
apiPrefix = "/scheduler"
bindPath = apiPrefix + "/bind"
preemptionPath = apiPrefix + "/preemption"
predicatesPrefix = apiPrefix + "/predicates"
prioritiesPrefix = apiPrefix + "/priorities"
EPS = 0.1)
type safeIntValueMap struct {
mu sync.RWMutex
intValueMap map[string]int
}
type safeFloatValueMap struct {
mu sync.RWMutex
stringFloat64Map map[string]float64
}
type safeAppTrafficInfo struct {
mu sync.RWMutex
appTrafficInfo map[string]safeFloatValueMap
}
type safePodsDistributionMap struct {
mu sync.RWMutex
podsDistributionRatioMap map[string]safeIntValueMap
}
type safeUpdatedCheckMap struct {
mu sync.RWMutex
isMapUpdated map[string]bool
}
type Config struct {
Application struct {
Name string `yaml:"name"`
NameSpace string `yaml:"namespace"`
DefaultPods string `yaml:"defaultPods"`
}
K8sConfigPath struct {
Path string `yaml:"path"`
}
}
var (
version string // injected via ldflags at build time
//Phuc
sHpaObject = "HorizontalPodAutoscaler"
//example message HorizontalPodAutoscaler--app-example1--New size: 7; reason: cpu resource utilization (percentage of request) above target
bInit = false
bCalculating = false
neighborsInfo map[string]map[string]float64
node1Neighbors map[string]float64
node2Neighbors map[string]float64
node3Neighbors map[string]float64
//podsDistributionRatioMap safeIntValueMap
//nodesTrafficMap safeFloatValueMap
podsDistributionInfo safePodsDistributionMap
appTrafficInfo safeAppTrafficInfo
appUpdateInfoMap safeUpdatedCheckMap
//global variable
customConfig Config
config *rest.Config
clientset *kubernetes.Clientset
appPodOptions metav1.ListOptions
defaultApplicationPods int
start time.Time
// end Phuc
// Create Filter, Priority, .. for scheduling
TruePredicate Predicate
ZeroPriority Prioritize
NoBind Bind
EchoPreemption Preemption
podsDis map[string]int
)
func StringToLevel(levelStr string) colog.Level {
switch level := strings.ToUpper(levelStr); level {
case "TRACE":
return colog.LTrace
case "DEBUG":
return colog.LDebug
case "INFO":
return colog.LInfo
case "WARNING":
return colog.LWarning
case "ERROR":
return colog.LError
case "ALERT":
return colog.LAlert
default:
log.Printf("warning: LOG_LEVEL=\"%s\" is empty or invalid, fallling back to \"INFO\".\n", level)
return colog.LInfo
}
}
func main() {
// Init configs
podsDis = make(map[string]int)
podsDis["1node1"] = 7
podsDis["2node2"] = 1
podsDis["3node3"] = 1
initConfigs()
start = time.Now()
defaultApplicationPods, _ = strconv.Atoi(customConfig.Application.DefaultPods)
//Init test set
bInit = true
//TODO we must update neighbors for each node in another func
//1node1 neighbors
node1Neighbors = make(map[string]float64)
node1Neighbors["2node2"] = 5
node1Neighbors["3node3"] = 20
log.Printf("node1Neighbors len = %d", len(node1Neighbors))
//2node2 neighbors
node2Neighbors = make(map[string]float64)
node2Neighbors["1node1"] = 5
node2Neighbors["3node3"] = 10
//3node3 neighbors
node3Neighbors = make(map[string]float64)
node3Neighbors["2node2"] = 10
node3Neighbors["1node1"] = 20
neighborsInfo = make(map[string]map[string]float64)
neighborsInfo["1node1"] = node1Neighbors
neighborsInfo["2node2"] = node2Neighbors
neighborsInfo["3node3"] = node3Neighbors
appTrafficInfo = safeAppTrafficInfo{
mu: sync.RWMutex{},
appTrafficInfo: make(map[string]safeFloatValueMap),
}
podsDistributionInfo = safePodsDistributionMap{
mu: sync.RWMutex{},
podsDistributionRatioMap: make(map[string]safeIntValueMap),
}
appUpdateInfoMap = safeUpdatedCheckMap{
mu: sync.RWMutex{},
isMapUpdated: make(map[string]bool),
}
//podsDis := make(map[string]int)
//podsDis["1node1"] = 3
//podsDis["2node2"] = 3
//podsDis["3node3"] = 2
colog.SetDefaultLevel(colog.LInfo)
colog.SetMinLevel(colog.LInfo)
colog.SetFormatter(&colog.StdFormatter{
Colors: true,
Flag: log.Ldate | log.Ltime | log.Lshortfile,
})
colog.Register()
level := StringToLevel(os.Getenv("LOG_LEVEL"))
log.Print("Log level was set to ", strings.ToUpper(level.String()))
colog.SetMinLevel(level)
router := httprouter.New()
AddVersion(router)
predicates := []Predicate{TruePredicate}
for _, p := range predicates {
AddPredicate(router, p)
}
priorities := []Prioritize{ZeroPriority}
for _, p := range priorities {
AddPrioritize(router, p)
}
AddBind(router, NoBind)
// watch used to get all events
watch, err := clientset.CoreV1().Events(customConfig.Application.NameSpace).Watch(metav1.ListOptions{})
if err != nil {
log.Fatal(err.Error())
}
ch := watch.ResultChan()
// this goroutine is used to parse all the events that generated by HPA object.
go func() {
for event := range ch {
e, _ := event.Object.(*v1.Event)
if (start.Sub(e.FirstTimestamp.Time)).Minutes() > 1 {
// This if statement is used to ignore old events
continue
}
if strings.Contains(e.Message, "old size") && strings.Contains(e.Message, "new size") {
message := e.Message
oldSizeMessagePart := message[strings.Index(message, "old size: "):strings.Index(message, ", new size")]
oldSize, _ := strconv.Atoi(strings.ReplaceAll(oldSizeMessagePart, "old size: ", ""))
newSizeMessagePart := message[strings.Index(message, "new size: "):strings.Index(message, ", reason")]
newSize, _ := strconv.Atoi(strings.ReplaceAll(newSizeMessagePart, "new size: ", ""))
if newSize < oldSize {
continue
}
appName := e.InvolvedObject.Name
appUpdateInfoMap.mu.Lock()
appUpdateInfoMap.isMapUpdated[appName] = false
appUpdateInfoMap.mu.Unlock()
if _, exist := appTrafficInfo.appTrafficInfo[appName]; !exist {
appTrafficInfo.mu.Lock()
podsDistributionInfo.mu.Lock()
appTrafficInfo.appTrafficInfo[appName] = nodesTrafficMapInit()
podsDistributionInfo.podsDistributionRatioMap[appName] = nodesPodsDistributionMapInit()
appTrafficInfo.mu.Unlock()
podsDistributionInfo.mu.Unlock()
}
log.Printf("goroutine id %d", goid())
log.Print("============================")
log.Print("====HPA Upscale happends====")
log.Printf("=======New pod = %d=========", newSize - oldSize)
log.Print("============================")
updateNodesTraffic(appTrafficInfo.appTrafficInfo[appName], appName)
podsDistributionInfo.mu.Lock()
calculatePodsDistribution(newSize - oldSize, appTrafficInfo.appTrafficInfo[appName], podsDistributionInfo.podsDistributionRatioMap[appName])
podsDistributionInfo.mu.Unlock()
appUpdateInfoMap.mu.Lock()
appUpdateInfoMap.isMapUpdated[appName] = true
appUpdateInfoMap.mu.Unlock()
}
}
}()
time.Sleep(2 * time.Second)
log.Print("info: server starting on localhost port :8888")
bInit = false // Prevent old events affect
if err := http.ListenAndServe("localhost:8888", router); err != nil {
log.Fatal(err)
}
}
func calculatePodsDistribution(iNumberOfNewPodScheduledByHPA int, nodesTrafficMap safeFloatValueMap, podsDistributionRatioMap safeIntValueMap) {
log.Print("(Calculation Begin) Calculating pods distribution")
// We need to update latest traffic info for all nodes before calculation
sumTrafficFromMap := nodesTrafficMap.getValuesSum()
allNodesHasSameTraffic := false
if sumTrafficFromMap - EPS < 0 {
log.Printf("Sum < EPS")
nodesTrafficMap.equalizeValuesTo1()
sumTrafficFromMap = nodesTrafficMap.getValuesSum()
allNodesHasSameTraffic = true
}
sortedNodesNameBasedOnTraffic := getSortedMapKeysByValueDesc(nodesTrafficMap.getFloat64ValueMap())
podsDistributionRatioMap.mu.Lock()
iNumberOfNewPodScheduledByHPAClone := iNumberOfNewPodScheduledByHPA
for iNumberOfNewPodScheduledByHPAClone > 0 {
for i, nodeName := range sortedNodesNameBasedOnTraffic {
if iNumberOfNewPodScheduledByHPAClone == 0 {
break
}
numberOfPods := int(math.RoundToEven(float64(iNumberOfNewPodScheduledByHPA) * (nodesTrafficMap.getFloat64Value(nodeName) / sumTrafficFromMap)))
if numberOfPods > iNumberOfNewPodScheduledByHPAClone {
numberOfPods = iNumberOfNewPodScheduledByHPAClone
}
if numberOfPods == 0 && i == 0 {
allNodesHasSameTraffic = true
}
if allNodesHasSameTraffic == true {
numberOfPods = 1
}
currentPodsOnNode := podsDistributionRatioMap.getInValue(nodeName)
podsDistributionRatioMap.setIntValue(nodeName, currentPodsOnNode + numberOfPods)
iNumberOfNewPodScheduledByHPAClone = iNumberOfNewPodScheduledByHPAClone - numberOfPods
}
}
log.Print("(Calculation Done) Pods distribution calculated")
podsDistributionRatioMap.printPodsDistributionInfo()
podsDistributionRatioMap.mu.Unlock()
}
func getAllRunningAppPod () int {
// get the pod list
podList, _ := clientset.CoreV1().Pods(customConfig.Application.NameSpace).List(metav1.ListOptions{
LabelSelector: "app=" + customConfig.Application.Name,
})
count := 0
for _, pod := range podList.Items {
if pod.Status.Phase == v1.PodRunning {
count++
}
}
// List() returns a pointer to slice, derefernce it, before iterating
log.Printf("info:func GetAllActiveAppPod() => Current pods in cluster = %d", count)
return count
}
func initConfigs () {
log.Print("Initialize configuration")
//Read configuration file
log.Print("Read configuration file")
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
log.Printf("Current dir = %s", dir)
if err != nil {
log.Fatal(err)
}
f, err := os.Open(dir + "/config.yaml")
if err != nil {
log.Fatal(err)
}
decoder := yaml.NewDecoder(f)
err = decoder.Decode(&customConfig)
if err != nil {
log.Fatal(err)
}
if errWhenCloseFile := f.Close(); errWhenCloseFile != nil {
log.Fatal(errWhenCloseFile)
}
log.Printf("config path %s", customConfig.K8sConfigPath.Path)
// initConfigs
config , _ = clientcmd.BuildConfigFromFlags("", customConfig.K8sConfigPath.Path)
if config == nil {
log.Print("Config is nil")
}
clientset, _ = kubernetes.NewForConfig(config)
appPodOptions = metav1.ListOptions{
LabelSelector: "app=" + customConfig.Application.Name,
}
initScheduleRules()
}
func initScheduleRules () {
log.Print("Adding schedule rules")
TruePredicate = Predicate{
Name: "always_true",
Func: func(pod v1.Pod, node v1.Node) (bool, error) {
return true, nil
},
}
ZeroPriority = Prioritize{
Name: "traffic_neighbors_scoring",
Func: func(pod v1.Pod, nodes []v1.Node) (*schedulerapi.HostPriorityList, error) {
var priorityList schedulerapi.HostPriorityList
isScheduled := false
priorityList = make([]schedulerapi.HostPriority, len(nodes))
//missingLabelErr := "Application " + pod.Name + "does not have app label"
bMissingAppLabel := false
labelMap := pod.ObjectMeta.Labels
if labelMap == nil {
bMissingAppLabel = true
}
if _, exist := labelMap["app"]; !exist {
bMissingAppLabel = true
}
appName := labelMap["app"]
isHPAReady := false
hpa, err := clientset.AutoscalingV1().HorizontalPodAutoscalers("default").Get(appName, metav1.GetOptions{})
if err == nil {
// The below code is used to check that hpa is ready or not => If it is not ready, it means that all pods pass to this extender prioritize is init pods
var hpaConditions []v1autoscaling.HorizontalPodAutoscalerCondition
if err := json.Unmarshal([]byte(hpa.ObjectMeta.Annotations[autoscaling.HorizontalPodAutoscalerConditionsAnnotation]), &hpaConditions); err != nil {
panic("Cannot get hpa conditions")
}
for _, condition := range hpaConditions {
if condition.Type == v1autoscaling.ScalingActive {
if condition.Status == "True" {
isHPAReady = true
log.Printf("### HPA %s is ready", hpa.Name)
}
}
}
}
if strings.Contains(pod.Name, appName) && isHPAReady == true && !bMissingAppLabel && false {
isAppNameExistInPodsDisMap := false
isAppNameExistInUpdateInfoMap := false
podsDistributionInfo.mu.RLock()
_, isAppNameExistInPodsDisMap = podsDistributionInfo.podsDistributionRatioMap[appName]
podsDistributionInfo.mu.RUnlock()
appUpdateInfoMap.mu.RLock()
_, isAppNameExistInUpdateInfoMap = appUpdateInfoMap.isMapUpdated[appName]
bIsMapUpdated := appUpdateInfoMap.isMapUpdated[appName]
appUpdateInfoMap.mu.RUnlock()
bLog1Time := true
for !isAppNameExistInPodsDisMap || !isAppNameExistInUpdateInfoMap || !bIsMapUpdated {
if bLog1Time {
log.Printf("Wait for all maps to be updated ...")
bLog1Time = false
}
podsDistributionInfo.mu.RLock()
_, isAppNameExistInPodsDisMap = podsDistributionInfo.podsDistributionRatioMap[appName]
podsDistributionInfo.mu.RUnlock()
appUpdateInfoMap.mu.RLock()
_, isAppNameExistInUpdateInfoMap = appUpdateInfoMap.isMapUpdated[appName]
bIsMapUpdated = appUpdateInfoMap.isMapUpdated[appName]
appUpdateInfoMap.mu.RUnlock()
}
log.Printf("All Maps are updated")
// Use for loop here to make sure that no anynomous host prioritize exist
for !isScheduled {
podsDistributionInfo.mu.RLock()
sortedNodeNameBasedOnPodsValue := getSortedMapKeysByPodsValueDesc(podsDistributionInfo.podsDistributionRatioMap[appName].intValueMap)
podsDistributionInfo.mu.RUnlock()
for _, nodeName := range sortedNodeNameBasedOnPodsValue {
podsDistributionInfo.mu.RLock()
podsOnNode := podsDistributionInfo.podsDistributionRatioMap[appName].intValueMap[nodeName]//podsDistributionRatioMap.getInValue(nodeName)
podsDistributionInfo.mu.RUnlock()
if podsOnNode == 0 {
continue
}
log.Print("Start to schedule 1 pod")
if nodeExistOnList(nodeName, nodes) {
iMaxScore := len(nodes) * 10
iIndex := 0
priorityList[iIndex] = schedulerapi.HostPriority{
Host: nodeName,
Score: int64(iMaxScore),
}
log.Printf("Node %s has score = %d", nodeName, iMaxScore)
iIndex += 1
iMaxScore = iMaxScore - 10
sortedNodeNameBasedOnDelayValue := getSortedMapKeysByValueAsc(neighborsInfo[nodeName])
for _, neighbors := range sortedNodeNameBasedOnDelayValue {
if nodeExistOnList(neighbors, nodes) {
priorityList[iIndex] = schedulerapi.HostPriority{
Host: neighbors,
Score: int64(iMaxScore),
}
log.Printf("Node %s has score = %d", neighbors, iMaxScore)
iIndex++
iMaxScore = iMaxScore - 10
}
}
isScheduled = true
podsDistributionInfo.mu.Lock()
oldPodsValueOnNode := podsDistributionInfo.podsDistributionRatioMap[appName].intValueMap[nodeName]//podsDistributionRatioMap.getInValue(nodeName)
podsDistributionInfo.podsDistributionRatioMap[appName].intValueMap[nodeName] = oldPodsValueOnNode - 1
podsDistributionInfo.mu.Unlock()
break
} else {
// Iterate all neighbors and give them score
iMaxScore := len(nodes) * 10
iIndex := 0
sortedNodeNameBasedOnDelayValue := getSortedMapKeysByValueAsc(neighborsInfo[nodeName])
for _, neighbors := range sortedNodeNameBasedOnDelayValue {
if nodeExistOnList(neighbors, nodes) {
priorityList[iIndex] = schedulerapi.HostPriority{
Host: neighbors,
Score: int64(iMaxScore),
}
iIndex++
iMaxScore = iMaxScore - 10
}
}
isScheduled = true
podsDistributionInfo.mu.Lock()
oldPodsValueOnNode := podsDistributionInfo.podsDistributionRatioMap[appName].intValueMap[nodeName]
podsDistributionInfo.podsDistributionRatioMap[appName].intValueMap[nodeName] = oldPodsValueOnNode - 1
podsDistributionInfo.mu.Unlock()
break
}
}
}
} else {
log.Printf("No Prioritize schedule")
iMaxScore := len(nodes) * 10
log.Printf("Len of podsDis map = %d", len(podsDis))
for k, v := range podsDis {
if v == 0 {
log.Print("Hello")
continue
}
log.Printf("k = %s", k)
for i, node := range nodes {
log.Printf("i = %d", i)
log.Printf("Filtered: node name = %s", node.Name)
if node.Name == k {
priorityList[i] = schedulerapi.HostPriority{
Host: node.Name,
Score: int64(iMaxScore),
}
} else {
priorityList[i] = schedulerapi.HostPriority{
Host: node.Name,
Score: 0,
}
}
}
podsDis[k] = podsDis[k] - 1
return &priorityList, nil
}
// If no pods will be scheduled by HPA => we do not need to care about them
//for i, node := range nodes {
// tempHostPriority := schedulerapi.HostPriority{}
// tempHostPriority.Host = node.Name
// priorityList[i] = tempHostPriority
//}
}
if _, exist := podsDistributionInfo.podsDistributionRatioMap[appName]; exist {
isAllNodesRemainZeroPod := true
for _, v := range podsDistributionInfo.podsDistributionRatioMap[appName].intValueMap {
if v != 0 {
isAllNodesRemainZeroPod = false
break
}
}
if isAllNodesRemainZeroPod {
appUpdateInfoMap.mu.Lock()
appUpdateInfoMap.isMapUpdated[appName] = false
appUpdateInfoMap.mu.Unlock()
}
}
return &priorityList, nil
},
}
NoBind = Bind{
Func: func(podName string, podNamespace string, podUID types.UID, node string) error {
return fmt.Errorf("This extender doesn't support Bind. Please make 'BindVerb' be empty in your ExtenderConfig.")
},
}
EchoPreemption = Preemption{
Func: func(_ v1.Pod, _ map[string]*schedulerapi.Victims, nodeNameToMetaVictims map[string]*schedulerapi.MetaVictims, ) map[string]*schedulerapi.MetaVictims {
return nodeNameToMetaVictims
},
}
}
func getNodesTrafficInfoFromEndpoints(workerNodeName string, appName string) float64 {
realEPName := ""
endpoints, _ := clientset.CoreV1().Endpoints("default").List(metav1.ListOptions{})
for _, ep := range endpoints.Items {
if strings.Contains(ep.Name, workerNodeName) && strings.Contains(ep.Name, appName) {
realEPName = ep.Name
break
}
}
if realEPName == "" {
klog.Infof("EP name = empty")
return 0
}
realEP, _ := clientset.CoreV1().Endpoints("default").Get(realEPName, metav1.GetOptions{})
annotation := realEP.ObjectMeta.Annotations
if annotation == nil {
klog.Infof("EP %s does not have traffic info annotations", realEPName)
return 0
}
curNumRequests, _ := strconv.Atoi(annotation["numRequests"])
klog.Infof("CurrentNumRequests = %d", curNumRequests)
oldNumRequests, _ := strconv.Atoi(annotation["oldNumRequests"])
klog.Infof("oldNumRequests = %d", oldNumRequests)
trafficValue := float64(curNumRequests - oldNumRequests)
klog.Infof("Traffic value from ep %s = %f", realEPName, trafficValue)
annotation["reset"] = "true"
return trafficValue
}
func updateNodesTraffic(nodesTrafficMap safeFloatValueMap, appName string) {
//TODO update nodes traffic here by getting information from endpoint on each node
// Get all worker nodes
//nodesTrafficMap.mu.Lock()
log.Print("(Update begin) Updating nodes traffic")
workerNodes, _ := clientset.CoreV1().Nodes().List(metav1.ListOptions{
LabelSelector: "node-role.kubernetes.io/worker=true",
})
// Get traffic for all worker nodes from EP
for _, workerNode := range workerNodes.Items {
nodesTrafficMap.setFloatValue(workerNode.Name, getNodesTrafficInfoFromEndpoints(workerNode.Name, appName))
}
log.Print("(Update Done) Updated nodes traffic")
nodesTrafficMap.printNodesTrafficInfo()
//nodesTrafficMap.mu.Unlock()
}
// This func is used to sort map keys by their values
func getSortedMapKeysByValueAsc(inputMap map[string]float64) []string {
mapKeys := make([]string, 0, len(inputMap))
for key := range inputMap {
mapKeys = append(mapKeys, key)
}
sort.Slice(mapKeys, func(i, j int) bool {
return inputMap[mapKeys[i]] < inputMap[mapKeys[j]]
})
klog.Info("Neighbors name sorted by delay asc")
for i, key := range mapKeys {
klog.Infof("- Index %d: %s", i, key)
}
return mapKeys
}
// This func is used to sort map keys by their values
func getSortedMapKeysByPodsValueDesc(inputMap map[string]int) []string {
mapKeys := make([]string, 0, len(inputMap))
for key := range inputMap {
mapKeys = append(mapKeys, key)
}
sort.Slice(mapKeys, func(i, j int) bool {
return inputMap[mapKeys[i]] > inputMap[mapKeys[j]]
})
return mapKeys
}
func getSortedMapKeysByValueDesc(inputMap map[string]float64) []string {
mapKeys := make([]string, 0, len(inputMap))
for key := range inputMap {
mapKeys = append(mapKeys, key)
}
sort.Slice(mapKeys, func(i, j int) bool {
return inputMap[mapKeys[i]] > inputMap[mapKeys[j]]
})
klog.Info("Sorted keys of traffic map")
for i, key := range mapKeys {
klog.Infof("- Index %d: %s", i, key)
}
return mapKeys
}
func nodesTrafficMapInit() safeFloatValueMap {
nodesTrafficMap := safeFloatValueMap{stringFloat64Map: make(map[string]float64)}
workerNodes, _ := clientset.CoreV1().Nodes().List(metav1.ListOptions{
LabelSelector: "node-role.kubernetes.io/worker=true",
})
// Get traffic for all worker nodes from EP
for _, workerNode := range workerNodes.Items {
nodesTrafficMap.setFloatValue(workerNode.Name, 0.0)
}
return nodesTrafficMap
}
func nodesPodsDistributionMapInit() safeIntValueMap {
nodesPodsDistributionMap := safeIntValueMap{intValueMap: make(map[string]int)}
workerNodes, _ := clientset.CoreV1().Nodes().List(metav1.ListOptions{
LabelSelector: "node-role.kubernetes.io/worker=true",
})
// Get traffic for all worker nodes from EP
for _, workerNode := range workerNodes.Items {
nodesPodsDistributionMap.setIntValue(workerNode.Name, 0)
}
return nodesPodsDistributionMap
}
func calTotalFromMapValues(trafficMap map[string]float64) float64 {
result := 0.0
for _, value := range trafficMap {
result += value
}
return result
}
func nodeExistOnList(a string, list []v1.Node) bool {
for _, b := range list {
if b.Name == a {
return true
}
}
return false
}
func equalizeNodeTraffic(cloneNodesTrafficMap map[string]float64){
for nodeName, _ := range cloneNodesTrafficMap {
cloneNodesTrafficMap[nodeName] = 1.0
}
}
func updateOldTrafficForEPs() {
workerNodesName := make([]string, 0)
EPsName := make([]string, 0)
workerNodes, _ := clientset.CoreV1().Nodes().List(metav1.ListOptions{
LabelSelector: "node-role.kubernetes.io/worker=true",
})
for _, worker := range workerNodes.Items {
workerNodesName = append(workerNodesName, worker.Name)
}
if len(workerNodesName) == 0 {
log.Printf("Worker nodes name list is empty")
}
endpoints, _ := clientset.CoreV1().Endpoints("default").List(metav1.ListOptions{})
epPrefix := "-" + customConfig.Application.Name
for _, ep := range endpoints.Items {
if !strings.Contains(ep.Name, customConfig.Application.Name) || ep.Name == customConfig.Application.Name {
continue
}
if stringInSlice(ep.Name[0:strings.Index(ep.Name, epPrefix)], workerNodesName) {
EPsName = append(EPsName, ep.Name)
klog.Infof("EPsName value = %s", ep.Name)
}
}
for _, epName := range EPsName {
realEP, _ := clientset.CoreV1().Endpoints("default").Get(epName, metav1.GetOptions{})
annotation := realEP.ObjectMeta.Annotations
if annotation == nil {
klog.Infof("EP %s does not have traffic info annotations", epName)
continue
}
annotation["reset"] = "true"
realEP.ObjectMeta.Annotations = annotation
_, error := clientset.CoreV1().Endpoints("default").Update(realEP)
if error != nil {
klog.Infof("Can not update old num requests for EP %s", realEP.Name)
}
}
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func isAllMapValueEqualToZero (inputMap map[string]int) bool {
for _, v := range inputMap {
if v != 0 {
return false
}
}
return true
}
func (c *safeIntValueMap) setIntValue(key string, value int) {
// Lock so only one goroutine at a time can access the map c.intValueMap
c.intValueMap[key] = value
}
func (c *safeIntValueMap) getInValue(key string) int {
// Lock so only one goroutine at a time can access the map c.v.
return c.intValueMap[key]
}
func (c *safeIntValueMap) getIntValueMap() map[string]int {
return c.intValueMap
}
func (c *safeIntValueMap) printPodsDistributionInfo() {
for k, v := range c.intValueMap {
klog.Infof("Node %s has %d pods to schedule", k, v)
}
}
func (c *safeFloatValueMap) setFloatValue(key string, value float64) {
// Lock so only one goroutine at a time can access the map c.stringFloat64Map
c.stringFloat64Map[key] = value
}
func (c *safeFloatValueMap) getValuesSum() float64 {
sum := 0.0
for _, v := range c.stringFloat64Map {
sum += v
}
return sum
}
func (c *safeFloatValueMap) equalizeValuesTo1() {
// Lock so only one goroutine at a time can access the map c.stringFloat64Map
for k, _ := range c.stringFloat64Map {
c.stringFloat64Map[k] = 1.0
}
}
func (c *safeFloatValueMap) getFloat64Value(key string) float64 {
// Lock so only one goroutine at a time can access the map c.v.
return c.stringFloat64Map[key]
}
func (c *safeFloatValueMap) getFloat64ValueMap() map[string]float64 {
return c.stringFloat64Map
}
func (c *safeFloatValueMap) printNodesTrafficInfo() {
for k, v := range c.stringFloat64Map {
klog.Infof("Node %s has traffic %f", k, v)
}
}
func goid() int {
var buf [64]byte
n := runtime.Stack(buf[:], false)
idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
id, err := strconv.Atoi(idField)
if err != nil {
panic(fmt.Sprintf("cannot get goroutine id: %v", err))
}
return id
}
| [
"\"LOG_LEVEL\""
]
| []
| [
"LOG_LEVEL"
]
| [] | ["LOG_LEVEL"] | go | 1 | 0 | |
controllers/provider-aws/cmd/gardener-extension-provider-aws/app/app.go | // Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 app
import (
"context"
"fmt"
"os"
awsinstall "github.com/gardener/gardener-extensions/controllers/provider-aws/pkg/apis/aws/install"
"github.com/gardener/gardener-extensions/controllers/provider-aws/pkg/aws"
awscmd "github.com/gardener/gardener-extensions/controllers/provider-aws/pkg/cmd"
awscontrolplane "github.com/gardener/gardener-extensions/controllers/provider-aws/pkg/controller/controlplane"
awsinfrastructure "github.com/gardener/gardener-extensions/controllers/provider-aws/pkg/controller/infrastructure"
awsworker "github.com/gardener/gardener-extensions/controllers/provider-aws/pkg/controller/worker"
awscontrolplanebackup "github.com/gardener/gardener-extensions/controllers/provider-aws/pkg/webhook/controlplanebackup"
awscontrolplaneexposure "github.com/gardener/gardener-extensions/controllers/provider-aws/pkg/webhook/controlplaneexposure"
"github.com/gardener/gardener-extensions/pkg/controller"
controllercmd "github.com/gardener/gardener-extensions/pkg/controller/cmd"
"github.com/gardener/gardener-extensions/pkg/controller/infrastructure"
webhookcmd "github.com/gardener/gardener-extensions/pkg/webhook/cmd"
"github.com/spf13/cobra"
"sigs.k8s.io/controller-runtime/pkg/manager"
)
// NewControllerManagerCommand creates a new command for running a AWS provider controller.
func NewControllerManagerCommand(ctx context.Context) *cobra.Command {
var (
restOpts = &controllercmd.RESTOptions{}
mgrOpts = &controllercmd.ManagerOptions{
LeaderElection: true,
LeaderElectionID: controllercmd.LeaderElectionNameID(aws.Name),
LeaderElectionNamespace: os.Getenv("LEADER_ELECTION_NAMESPACE"),
}
configFileOpts = &awscmd.ConfigOptions{}
// options for the controlplane controller
controlPlaneCtrlOpts = &controllercmd.ControllerOptions{
MaxConcurrentReconciles: 5,
}
// options for the infrastructure controller
infraCtrlOpts = &controllercmd.ControllerOptions{
MaxConcurrentReconciles: 5,
}
infraReconcileOpts = &infrastructure.ReconcilerOptions{
IgnoreOperationAnnotation: true,
}
infraCtrlOptsUnprefixed = controllercmd.NewOptionAggregator(infraCtrlOpts, infraReconcileOpts)
// options for the worker controller
workerCtrlOpts = &controllercmd.ControllerOptions{
MaxConcurrentReconciles: 5,
}
controllerSwitches = awscmd.ControllerSwitchOptions()
webhookSwitches = awscmd.WebhookSwitchOptions()
webhookServerOptions = &webhookcmd.ServerOptions{
Port: 7890,
CertDir: "/tmp/cert",
Mode: webhookcmd.ServiceMode,
Name: "webhooks",
Namespace: os.Getenv("WEBHOOK_CONFIG_NAMESPACE"),
ServiceSelectors: "{}",
Host: "localhost",
}
webhookOptions = webhookcmd.NewAddToManagerOptions("aws-webhooks", webhookServerOptions, webhookSwitches)
aggOption = controllercmd.NewOptionAggregator(
restOpts,
mgrOpts,
controllercmd.PrefixOption("controlplane-", controlPlaneCtrlOpts),
controllercmd.PrefixOption("infrastructure-", &infraCtrlOptsUnprefixed),
controllercmd.PrefixOption("worker-", workerCtrlOpts),
configFileOpts,
controllerSwitches,
webhookOptions,
)
)
cmd := &cobra.Command{
Use: fmt.Sprintf("%s-controller-manager", aws.Name),
Run: func(cmd *cobra.Command, args []string) {
if err := aggOption.Complete(); err != nil {
controllercmd.LogErrAndExit(err, "Error completing options")
}
mgr, err := manager.New(restOpts.Completed().Config, mgrOpts.Completed().Options())
if err != nil {
controllercmd.LogErrAndExit(err, "Could not instantiate manager")
}
if err := controller.AddToScheme(mgr.GetScheme()); err != nil {
controllercmd.LogErrAndExit(err, "Could not update manager scheme")
}
if err := awsinstall.AddToScheme(mgr.GetScheme()); err != nil {
controllercmd.LogErrAndExit(err, "Could not update manager scheme")
}
configFileOpts.Completed().ApplyMachineImages(&awsworker.DefaultAddOptions.MachineImagesToAMIMapping)
configFileOpts.Completed().ApplyETCDStorage(&awscontrolplaneexposure.DefaultAddOptions.ETCDStorage)
configFileOpts.Completed().ApplyETCDBackup(&awscontrolplanebackup.DefaultAddOptions.ETCDBackup)
controlPlaneCtrlOpts.Completed().Apply(&awscontrolplane.Options)
infraCtrlOpts.Completed().Apply(&awsinfrastructure.DefaultAddOptions.Controller)
infraReconcileOpts.Completed().Apply(&awsinfrastructure.DefaultAddOptions.IgnoreOperationAnnotation)
workerCtrlOpts.Completed().Apply(&awsworker.DefaultAddOptions.Controller)
if err := controllerSwitches.Completed().AddToManager(mgr); err != nil {
controllercmd.LogErrAndExit(err, "Could not add controllers to manager")
}
if err := webhookOptions.Completed().AddToManager(mgr); err != nil {
controllercmd.LogErrAndExit(err, "Could not add webhooks to manager")
}
if err := mgr.Start(ctx.Done()); err != nil {
controllercmd.LogErrAndExit(err, "Error running manager")
}
},
}
aggOption.AddFlags(cmd.Flags())
return cmd
}
| [
"\"LEADER_ELECTION_NAMESPACE\"",
"\"WEBHOOK_CONFIG_NAMESPACE\""
]
| []
| [
"LEADER_ELECTION_NAMESPACE",
"WEBHOOK_CONFIG_NAMESPACE"
]
| [] | ["LEADER_ELECTION_NAMESPACE", "WEBHOOK_CONFIG_NAMESPACE"] | go | 2 | 0 | |
django/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smartcity.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
Welcomer 6.20/IPCServer.py | import asyncpg
import asyncio
import psycopg2
import base64
import copy
import csv
import html
import imghdr
import logging
import math
import os
import pathlib
import random
import re
import shutil
import string
import sys
import time
import traceback
# import tracemalloc
from datetime import timedelta, datetime
from functools import wraps
from urllib.parse import urlparse
from uuid import uuid4
from nacl.signing import VerifyKey
from nacl.exceptions import BadSignatureError
import aiohttp
import discord
import yaml
from itsdangerous import URLSafeSerializer
from PIL import Image, ImageDraw, ImageFont
from quart import (Quart, abort, jsonify, redirect, render_template, request,
send_file, session, websocket)
from quart.json import JSONDecoder, JSONEncoder
from quart.ctx import copy_current_websocket_context
from quart.sessions import SessionInterface, SessionMixin
from werkzeug.datastructures import CallbackDict
import asyncio
# import aiosmtplib
import sys
# from email.mime.multipart import MIMEMultipart
# from email.mime.text import MIMEText
import paypalrestsdk
import ujson as json
import uvloop
from quart_compress import Compress
from aoauth2_session import AOAuth2Session as OAuth2Session
from rockutils import rockutils
uvloop.install()
# tracemalloc.start()
config = rockutils.load_json("cfg/config.json")
paypal_api = paypalrestsdk.configure(config['paypal'])
recaptcha_key = config['keys']['recaptcha']
_oauth2 = config['oauth']
_domain = "welcomer.gg"
# _domain = "192.168.0.29:15007"
_debug = False
connection = None
connection_sync = None
async def connect(_debug, _config):
global connection
global connection_sync
host = config['db']['host']
db = config['db']['db']
password = config['db']['password']
user = config['db']['user']
rockutils.prefix_print(f"Connecting to DB {user}@{host}")
try:
connection = await asyncpg.create_pool(user=user, password=password,
database=db, host=host, max_size=50)
connection_sync = psycopg2.connect(user=user, password=password,
database=db, host=host)
except Exception as e:
rockutils.prefix_print(
f"Failed to connect to DB: {e}.",
prefix_colour="light red",
text_colour="red")
exit()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(
[asyncio.ensure_future(connect(_debug, config))]))
async def get_value(connection, table, key, default=None, raw=False):
print("FETCH", table, key)
async with connection.acquire() as pconnection:
value = await pconnection.fetchrow(
f"SELECT * FROM {table} WHERE id = $1",
key
)
if value:
print("FETCH", table, key, "OK")
if raw:
return value["value"]
else:
return json.loads(value["value"])
else:
print("FETCH", table, key, "FAIL")
return default
async def set_value(connection, table, key, value):
if key is None:
key = str(uuid.uuid4())
print("SET", table, key)
try:
async with connection.acquire() as pconnection:
await pconnection.execute(
f"INSERT INTO {table}(id, value) VALUES($1, $2) ON CONFLICT (id) DO UPDATE SET value = $2",
key, json.dumps(value),
)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
print("Failed to set value", table, ":", key, e)
# return False
else:
# return True
return {
"generated_keys": [key]
}
def get_value_sync(connection, table, key, default=None):
try:
cursor = connection.cursor()
cursor.execute(
f"SELECT * FROM {table} WHERE id = %s",
(key,)
)
value = cursor.fetchone()
if value:
print("FETCH", table, key, "OK")
return value[1]
else:
print("FETCH", table, key, "FAIL")
return default
except psycopg2.errors.InFailedSqlTransaction:
print("SQLTrans failed. Rolling back")
connection.rollback()
except psycopg2.InterfaceError:
global connection_sync
host = config['db']['host']
db = config['db']['db']
password = config['db']['password']
user = config['db']['user']
connection_sync = psycopg2.connect(user=user, password=password,
database=db, host=host)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
print("Failed to set value", table, ":", key, e)
return False
def set_value_sync(connection, table, key, value):
if key is None:
key = str(uuid.uuid4())
print("SET", table, key)
try:
cursor = connection.cursor()
cursor.execute(
f"""
INSERT INTO {table} (id, value)
VALUES (%s, %s)
ON CONFLICT (id)
DO UPDATE SET
value = EXCLUDED.value;""",
(key, json.dumps(value))
)
connection.commit()
cursor.close()
except psycopg2.errors.InFailedSqlTransaction:
print("SQLTrans failed. Rolling back")
connection.rollback()
except psycopg2.InterfaceError:
global connection_sync
host = config['db']['host']
db = config['db']['db']
password = config['db']['password']
user = config['db']['user']
connection_sync = psycopg2.connect(user=user, password=password,
database=db, host=host)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
print("Failed to set value", table, ":", key, e)
# return False
else:
# return True
return {
"generated_keys": [key]
}
class Cache:
def __init__(self):
self.cache = {}
def check_cache(self, key):
if key in self.cache:
keypair = self.cache[key]
if time.time() >= (keypair['now'] + keypair['timeout']):
return False, keypair['value']
else:
return True, keypair['value']
else:
return False, None
def add_cache(self, key, timeout, value):
self.cache[key] = {
"now": time.time(),
"timeout": timeout,
"value": value,
}
def get_cache(self, key):
val = self.cache[key]
cache = Cache()
blackfriday = False
# black friday sales 25% off everything
if blackfriday:
prices = {
'0:1': 3.75,
'1:1': 3.75,
'1:3': 11.25,
'1:6': 22.5,
'3:1': 7.5,
'3:3': 22.5,
'3:6': 45.0,
'5:1': 11.25,
'5:3': 33.75,
'5:6': 67.5,
}
else:
prices = {
"0:1": 5,
"1:1": 5,
"1:3": 13.50,
"1:6": 24.00,
"3:1": 10,
"3:3": 27,
"3:6": 48,
"5:1": 15,
"5:3": 40.50,
"5:6": 72.00,
}
_lastpost = 0
def empty(val):
return val in ['', ' ', None]
class PostgresSession(CallbackDict, SessionMixin):
def __init__(self, initial=None, sid=None, new=False):
def on_update(self):
self.modified = True
CallbackDict.__init__(self, initial, on_update)
self.sid = sid
self.new = new
self.modified = False
# def __setitem__(self, item, value):
# print(item, value)
# if item != "_permanent":
# self.modified = True
# super(CallbackDict, self).__setitem__(item, value)
class PostgresSessionInterface(SessionInterface):
serializer = json
session_class = PostgresSession
def __init__(self, connection_sync, prefix=''):
self.connection_sync = connection_sync
self.prefix = prefix
self.serialize = URLSafeSerializer(_oauth2['serial_secret'])
self.modified = False
def generate_sid(self):
return str(uuid4())
# def get_redis_expiration_time(self, app, session):
# return app.permanent_session_lifetime
def open_session(self, app, request):
sid = request.cookies.get(app.session_cookie_name)
if not sid:
sid = self.generate_sid()
return self.session_class(sid=sid, new=True)
rockutils.prefix_print(
f"Retreiving session {self.prefix + sid}. URL: {request.path}",
prefix_colour="light blue")
# val = r.table("sessions").get(self.prefix + sid).run(self.rethink)
val = get_value_sync(self.connection_sync,
"sessions", self.prefix + sid)
if val is not None:
data = self.serializer.loads(self.serialize.loads(val['data']))
return self.session_class(data, sid=sid)
return self.session_class(sid=sid, new=True)
def save_session(self, app, session, response):
domain = self.get_cookie_domain(app)
path = self.get_cookie_path(app)
if not session:
if session.modified:
rockutils.prefix_print(
f"Deleting session {self.prefix + session.sid}. URL: {request.path}",
prefix_colour="light red")
# r.table("sessions").get(self.prefix +
# session.sid).delete().run(self.rethink)
# TODO: actually clean sessions lol
# delete_value_sync(self.connection_sync,
# "sessions", self.prefix + session.sid)
response.delete_cookie(app.session_cookie_name,
domain=domain,
path=path)
return
domain = self.get_cookie_domain(app)
cookie_exp = self.get_expiration_time(app, session)
val = self.serialize.dumps(self.serializer.dumps(dict(session)))
rockutils.prefix_print(
f"Updating session {self.prefix + session.sid}. URL: {request.path}",
prefix_colour="light yellow")
# if r.table("sessions").get(
# self.prefix +
# session.sid).run(
# self.rethink):
# r.table("sessions").get(self.prefix +
# session.sid).replace({"id": self.prefix +
# session.sid, "data": val}).run(self.rethink)
# else:
# r.table("sessions").insert(
# {"id": self.prefix + session.sid, "data": val}).run(self.rethink)
set_value_sync(self.connection_sync, "sessions", self.prefix +
session.sid, {"id": self.prefix + session.sid, "data": val})
response.set_cookie(app.session_cookie_name, session.sid,
expires=cookie_exp, httponly=True, domain=domain, secure=False)
# response.set_cookie(app.session_cookie_name, session.sid,
# expires=cookie_exp, httponly=True, domain=domain, secure=True)
print(app.session_cookie_name, session.sid, domain, cookie_exp)
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
try:
return json.dumps(obj)
except TypeError:
return JSONEncoder.default(self, obj)
class CustomJSONDecoder(JSONDecoder):
def default(self, obj):
try:
return json.dumps(obj)
except TypeError:
return JSONDecoder.default(self, obj)
print("[init] Setting up quart")
app = Quart(__name__)
app.json_encoder = CustomJSONEncoder
app.json_decoder = CustomJSONDecoder
# Compress(app, True)
app.session_cookie_name = "session"
app.session_interface = PostgresSessionInterface(connection_sync)
app.secret_key = _oauth2['secret_key']
# app.config["SESSION_COOKIE_DOMAIN"] = _domain
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.jinja_options['auto_reload'] = True
app.config['MAX_CONTENT_LENGTH'] = 268435456
# os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true'
logging.basicConfig(filename='errors.log', level=logging.ERROR,
format='[%(asctime)s] %(levelname)-8s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
# log = logging.getLogger('requests_oauthlib')
# log.setLevel(logging.DEBUG)
def normalize_colour(string):
if isinstance(string, int):
return f"RGB|FFFFFF"
if string.lower() == "transparent":
return f"transparent"
if string.startswith("RGBA|"):
return string
elif string.startswith("RGB|"):
return string
else:
try:
_hex = str(hex(int(string)))[2:]
if len(_hex) >= 8:
return f"RGBA|{str(hex(string))[:8]}"
elif len(_hex) >= 6:
return f"RGB|{str(hex(string))[:6]}"
except BaseException:
pass
return f"RGB|FFFFFF"
def normalize_form(v):
if str(v).lower() == "true":
return True
if str(v).lower() == "false":
return False
try:
if v[0] == "#":
return int(v[1:], 16)
except BaseException:
pass
try:
return int(v)
except BaseException:
return v
def get_size(start_path):
_sh = os.popen(f"du -sb {start_path}")
resp = _sh._stream.read()
_sh.close()
return int(resp.split()[0])
def expect(v, t):
if t == "hex":
if v:
if v[0] == "#":
try:
int(v[1:], 16)
return True
except BaseException:
pass
if "rgba" in v:
return True
if v.lower() == "transparent":
return True
try:
int(v, 16)
return True
except BaseException:
pass
if t == "int":
try:
int(v)
return True
except BaseException:
pass
if t == "bool":
if v in [True, "true", "True", False, "false", "False"]:
return True
return False
def iterat():
i = math.ceil(time.time() * 100000)
return base64.b32encode(
i.to_bytes(
(i.bit_length() + 8) // 8,
'big',
signed=True)).decode("ascii").replace(
"=",
"").lower()
def sub(s, b, e=None, a=False):
s = str(s)
if e:
return s[b:e]
else:
if a:
return s[:b]
else:
return s[b:]
app.jinja_env.globals['json_loads'] = json.loads
app.jinja_env.globals['len'] = len
app.jinja_env.globals['str'] = str
app.jinja_env.globals['dict'] = dict
app.jinja_env.globals['bool'] = bool
app.jinja_env.globals['int'] = int
app.jinja_env.globals['hex'] = hex
app.jinja_env.globals['sub'] = sub
app.jinja_env.globals['list'] = list
app.jinja_env.globals['iterat'] = iterat
app.jinja_env.globals['unesc'] = html.unescape
app.jinja_env.globals['ctime'] = time.time
app.jinja_env.globals['ceil'] = math.ceil
app.jinja_env.globals['enumerate'] = enumerate
app.jinja_env.globals['sorted'] = sorted
app.jinja_env.globals['dirlist'] = os.listdir
app.jinja_env.globals['exist'] = os.path.exists
app.jinja_env.globals['since_unix_str'] = rockutils.since_unix_str
app.jinja_env.globals['recaptcha_key'] = recaptcha_key
ipc_jobs = {}
ipc_locks = {}
cluster_jobs = {}
clusters_initialized = set()
last_ping = {}
user_cache = {}
cluster_status = {}
cluster_data = {}
identify_locks = {}
_status_name = {
0: "Connecting",
1: "Ready",
2: "Restarting",
3: "Hung",
4: "Resuming",
5: "Stopped"
}
discord_cache = {}
async def create_job(request=None, o="", a="", r="", timeout=10):
global ipc_jobs
global ipc_locks
global clusters_initialized
if request:
o = (o if o != "" else request.headers.get("op"))
a = (a if a != "" else request.headers.get("args"))
r = (r if r != "" else request.headers.get("recep"))
if timeout == 10:
timeout = int(request.headers.get("timeout"))
job_key = "".join(random.choices(string.ascii_letters, k=32))
recepients = []
if r == "*":
for i in clusters_initialized:
recepients.append(i)
else:
try:
for i in json.loads(r):
_c = str(i).lower()
if _c in clusters_initialized:
recepients.append(_c)
except BaseException:
_c = str(r).lower()
if _c in clusters_initialized:
recepients.append(_c)
ipc_jobs[job_key] = {}
ipc_locks[job_key] = asyncio.Lock()
payload = {"o": o, "a": a, "k": job_key, "t": time.time()}
for r in recepients:
cluster_jobs[r].append(payload)
time_start = time.time()
start_time = time_start
delay_time = int(time_start) + timeout
while time.time() < delay_time:
if len(ipc_jobs[job_key]) == len(recepients):
break
await asyncio.sleep(0.05)
if time.time()-start_time > 1:
start_time = time.time()
print("Waiting on job", job_key, "received:",
ipc_jobs[job_key].keys(), "total:", recepients)
responce_payload = {
"k": job_key,
"r": r,
"o": o,
"a": a,
"js": time_start,
"d": ipc_jobs[job_key]
}
time_end = time.time()
responce_payload['jd'] = time_end - time_start
del ipc_jobs[job_key]
return responce_payload
async def sending(cluster):
rockutils.prefix_print(f"Started sending for {cluster}")
_last_ping = 0
alive = time.time()
try:
while True:
_t = time.time()
_jobs = cluster_jobs[cluster]
if _t - _last_ping > 60:
_jobs.append({
"o": "PING",
"a": "",
"k": f"ping.{cluster}"
})
_last_ping = _t
if len(_jobs) > 0:
await websocket.send(json.dumps(_jobs))
cluster_jobs[cluster] = []
await asyncio.sleep(0.1)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
rockutils.prefix_print(str(e), prefix="IPC Sender",
prefix_colour="light red", text_colour="red")
async def receiving(cluster):
rockutils.prefix_print(f"Started receiving for {cluster}")
try:
while True:
_data = json.loads(await websocket.receive())
print(">>>", _data)
o = _data['o']
if o == "SUBMIT" and "ping" in _data['k']:
last_ping[cluster] = time.time()
cluster_data[cluster] = _data['d']
rockutils.prefix_print(
f"Retrieved PING from cluster {cluster}")
elif o == "SHARD_UPDATE":
d = _data['d']
text = f"- **Shard {d[1]}** is now **{_status_name.get(d[0])}**"
await rockutils.send_webhook("https://canary.[removed]", text)
rockutils.prefix_print(
f"shard {d[1]} is now {_status_name.get(d[0])}")
elif o == "STATUS_UPDATE":
d = _data['d']
cluster_status[cluster] = d
text = f"**Cluster {cluster}** is now **{_status_name.get(d)}**"
await rockutils.send_webhook("https://canary.[removed]_e9YSarA", text)
rockutils.prefix_print(
f"Cluster {cluster} is now {_status_name.get(d)}")
elif o == "SUBMIT" and _data['k'] != "push":
k = _data['k']
r = _data['r']
d = _data['d']
if k in ipc_jobs:
ipc_jobs[k][r] = d
elif o == "PUSH_OPCODE":
d = _data['d']
_opcode = d[0]
_args = d[1]
r = d[2]
recepients = []
if r == "*":
for i in clusters_initialized:
recepients.append(i)
else:
try:
for i in json.loads(r):
_c = str(i).lower()
if _c in clusters_initialized:
recepients.append(_c)
except BaseException:
_c = str(r).lower()
if _c in clusters_initialized:
recepients.append(_c)
for _r in recepients:
ipc_jobs[_r].append({
"o": _opcode,
"a": _args,
"k": "push"
})
await asyncio.sleep(0.05)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
rockutils.prefix_print(str(e), prefix="IPC Receiver",
prefix_colour="light red", text_colour="red")
# @app.route("/_internal/sendemail", methods=["POST"])
# async def sendemail():
# headers = request.headers
# if headers["Authorization"] != "gFt3hNzXnGmUC93BumXjzYfhXTFgcGCnprvxSDwu33ChAChs":
# return "", 400
# body = await request.data
# j = json.loads(body)
# mail_params = j["transport"]
# res = j["mail"]
# # Prepare Message
# msg = MIMEMultipart()
# msg.preamble = res["subject"]
# msg['Subject'] = res["subject"]
# msg['From'] = res["from"]
# msg['To'] = res["to"]
# msg.attach(MIMEText(res["data"], res["type"], 'utf-8'))
# # Contact SMTP server and send Message
# host = mail_params.get('host', 'localhost')
# isSSL = mail_params.get('SSL', False)
# isTLS = mail_params.get('TLS', False)
# port = mail_params.get('port', 465 if isSSL else 25)
# smtp = aiosmtplib.SMTP(hostname=host, port=port, use_tls=isSSL)
# await smtp.connect()
# if isTLS:
# await smtp.starttls()
# if 'user' in mail_params:
# await smtp.login(mail_params['user'], mail_params['password'])
# await smtp.send_message(msg)
# await smtp.quit()
@app.route("/future")
async def future():
return await render_template("future.html", session=session)
@app.route("/robots.txt")
async def robots():
return await send_file("robots.txt")
@app.route("/d5df36181ddf2ea3a832645f2aa16371.txt")
async def detectify():
return await send_file("d5df36181ddf2ea3a832645f2aa16371.txt")
@app.route("/a")
async def senda():
return await send_file("a.js")
@app.route("/ads.txt")
async def ads():
return await send_file("ads.txt")
@app.route("/.well-known/apple-developer-merchantid-domain-association")
async def apple_pay():
return await send_file("apple-developer-merchantid-domain-association")
@app.route("/api/interactions", methods=['POST'])
async def interactions():
# Your public key can be found on your application in the Developer Portal
PUBLIC_KEY = '2f519b930c9659919c7e96617a8e9a400b285ddfbb9fb225d36a0441b7e697bb'
signature = request.headers["X-Signature-Ed25519"]
timestamp = request.headers["X-Signature-Timestamp"]
body = await request.data
message = timestamp.encode() + await request.data
print(message)
try:
vk = VerifyKey(bytes.fromhex(PUBLIC_KEY))
vk.verify(message, bytes.fromhex(signature))
except BadSignatureError:
print("invalid signature")
return abort(401, 'invalid request signature')
except Exception as e:
print(e)
return abort(500, 'oops')
payload = await request.json
if payload["type"] == 1:
return jsonify({
"type": 1
})
if payload["data"]["name"] == "pog":
return jsonify({
"type": 4,
"data": {
"content": "<:_:732274836038221855>:mega: pog"
}
})
if payload["data"]["name"] == "rock" and payload["guild_id"] == "341685098468343822":
user_id = payload["member"]["user"]["id"]
a = datetime.now()
b = time.time()
week = b + (60*60*24*7)
if a.month != 12 or not (31 >= a.day >= 25):
return jsonify({
"type": 3,
"data": {
"content": "It is not that time of the year yet. Come back soon!"
}
})
userinfo = await get_user_info(user_id)
if userinfo["m"]["1"]["u"] and userinfo["m"]["1"]["u"] > week:
return jsonify({
"type": 3,
"data": {
"content": "You already have this present. Don't try again!"
}
})
userinfo["m"]["1"]["h"] = True
userinfo["m"]["1"]["u"] = week
await set_value(connection, "users", str(user_id), userinfo)
return jsonify({
"type": 4,
"data": {
"content": f":gift:<:_:732274836038221855> Enjoy the rest of this year <@{user_id}>, heres a week of Welcomer Pro for a special server of your choosing. Do `+membership add` on the server you want to add this to"
}
})
return jsonify({
"type": 5,
})
@app.route("/api/job/<auth>", methods=['POST', 'GET'])
async def ipc_job(auth):
if auth != config['ipc']['auth_key']:
return "Invalid authentication", 403
return jsonify(await create_job(request))
@app.route("/api/ipc_identify/<key>/<cluster>/<auth>", methods=["POST", "GET"])
async def ipc_identify(key, cluster, auth):
if auth != config['ipc']['auth_key']:
return "Invalid authentication", 403
cluster = str(cluster).lower()
lock = identify_locks.get(key)
if not lock:
identify_locks[key] = {
'limit': 1,
'available': 1,
'duration': 5.5, # 5.5 seconds
'resetsAt': 0,
}
lock = identify_locks[key]
now = time.time()
if lock['resetsAt'] <= now:
print(f"{key} has refreshed identify lock for {cluster}")
lock['resetsAt'] = now + lock['duration']
lock['available'] = lock['limit']
if lock['available'] <= 0:
sleepTime = lock['resetsAt'] - now
print(f"{cluster} has hit identify lock on {key} told to wait {sleepTime} seconds")
return jsonify({
"available": False,
"sleep": sleepTime,
})
lock['available'] -= 1
print(f"{cluster} has gotten identify lock on {key}")
return jsonify({
"available": True,
})
@app.route("/api/ipc_submit/<cluster>/<auth>", methods=["POST"])
async def ipc_submit(cluster, auth):
if auth != config['ipc']['auth_key']:
return "Invalid authentication", 403
cluster = str(cluster).lower()
form = dict(await request.json)
k = form['k']
r = form['r']
d = form['d']
if k == "push":
print(cluster, "pushed submit")
return "OK", 200
if "ping" in k:
last_ping[cluster] = time.time()
cluster_data[cluster] = d
rockutils.prefix_print(
f"Retrieved PING from cluster {cluster}")
else:
if k in ipc_jobs:
ipc_jobs[k][r] = d
print("Submitted", k, "for", cluster)
else:
print(k, "is not valid key")
return "OK", 200
@app.websocket("/api/ipc/<cluster>/<auth>")
async def ipc_slave(cluster, auth):
if auth != config['ipc']['auth_key']:
return "Invalid authentication", 403
else:
await websocket.accept()
cluster = str(cluster).lower()
ipc_jobs[cluster] = []
clusters_initialized.add(cluster)
if cluster not in cluster_jobs:
cluster_jobs[cluster] = []
rockutils.prefix_print(f"Connected to cluster {cluster}")
# loop = asyncio.get_event_loop()
try:
await asyncio.gather(
copy_current_websocket_context(sending)(cluster),
copy_current_websocket_context(receiving)(cluster)
)
except asyncio.CancelledError:
pass
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
rockutils.prefix_print(str(e), prefix="IPC Slave",
prefix_colour="light red", text_colour="red")
#############################################################
# DASHBOARD
#############################################################
@app.errorhandler(404)
async def not_found_error(e):
if "php" in request.url or ".env" in request.url:
return (await render_template('fakephpinfo.html', request=request)), 200
if "static" in request.url:
return "404", 404
return (await render_template('error.html', error="I cant seem to find this page. Maybe you went to the wrong place?", image="finding")), 404
@app.errorhandler(403)
async def forbidden_error(e):
print("403")
if "static" in request.url:
return "403"
return (await render_template('error.html', error="Hm, it seems you cant access this page. Good try though old chap. If this was a guild page, the owner disabled the public listing.", image="sir")), 403
@app.errorhandler(500)
async def internal_server_error(e):
print("500")
print(e)
if "static" in request.url:
return "500"
return (await render_template('error.html', error="Uh oh, seems something pretty bad just happened... Mr Developer, i dont feel so good...", image=random.choice(["sad1", "sad2", "sad3"]))), 500
# Functions
def token_updater(token):
session['oauth2_token'] = token
def make_session(token=None, state=None, scope=None):
return OAuth2Session(
client_id=_oauth2['client_id'],
token=token,
state=state,
scope=scope,
redirect_uri=_oauth2['redirect_uri'][_domain],
auto_refresh_kwargs={
'client_id': _oauth2['client_id'],
'client_secret': _oauth2['client_secret'],
},
auto_refresh_url=_oauth2['token_url'],
token_updater=token_updater
)
async def get_user_info(id, refer=""):
try:
rockutils.prefix_print(
f"{f'[Refer: {refer}] ' if refer != '' else ''}Getting information for U:{id}",
prefix="User Info:Get",
prefix_colour="light green")
# guild_info = r.table("users").get(str(id)).run(rethink)
guild_info = await get_value(connection, "users", str(id))
return guild_info or None
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
rockutils.prefix_print(
f"Error occured whilst retrieving info for U:{id}. {e}",
prefix="User Info:Update",
prefix_colour="red",
text_colour="light red")
return False
async def get_guild_info(id, refer="", default_if_empty=True):
try:
rockutils.prefix_print(
f"{f'[Refer: {refer}] ' if refer != '' else ''}Getting information for G:{id}",
prefix="Guild Info:Get",
prefix_colour="light green")
# guild_info = r.table("guilds").get(str(id)).run(rethink)
guild_info = await get_value(connection, "guilds", str(id))
if not guild_info:
await create_job(o="cachereload", a=str(id), r="*")
# guild_info = r.table("guilds").get(str(id)).run(rethink)
guild_info = await get_value(connection, "guilds", str(id))
if default_if_empty:
return guild_info or rockutils.load_json("cfg/default_guild.json")
else:
return guild_info
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
rockutils.prefix_print(
f"Error occured whilst retrieving info for G:{id}. {e}",
prefix="Guild Info:Update",
prefix_colour="red",
text_colour="light red")
return rockutils.load_json("cfg/default_guild.json")
async def update_guild_info(id, data, forceupdate=False, refer=""):
try:
rockutils.prefix_print(
f"{f'[Refer: {refer}] ' if refer != '' else ''}Updating information for G:{id}",
prefix="Guild Info:Update",
prefix_colour="light green")
t = time.time()
# if forceupdate:
# r.table("guilds").get(str(id)).update(data).run(rethink)
# else:
# r.table("guilds").get(str(id)).replace(data).run(rethink)
await set_value(connection, "guilds", str(id), data)
te = time.time()
if te - t > 1:
rockutils.prefix_print(
f"Updating guild info took {math.floor((te-t)*1000)}ms",
prefix="Guild Info:Update",
prefix_colour="red",
text_colour="light red")
return True
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
rockutils.prefix_print(
f"Error occured whilst updating info for G:{id}. {e}",
prefix="Guild Info:Update",
prefix_colour="red",
text_colour="light red")
return False
async def get_guild_donations(guild_info):
_time = time.time()
valid_donations = []
try:
_userinfo = await get_user_info(guild_info['d']['g']['o']['id'])
if _userinfo and _userinfo['m']['p']:
valid_donations.append("partner")
except BaseException:
pass
if guild_info['d']['b']['hb']:
valid_donations.append("cbg")
for id in guild_info['d']['de']:
try:
if has_special_permission(id, support=True, developer=True, admin=True, trusted=True):
return True
_userinfo = await get_user_info(id)
if _userinfo:
if _userinfo['m']['1']['h'] and (
_time < _userinfo['m']['1']['u'] or
_userinfo['m']['1']['p']):
valid_donations.append("donation")
break
if _userinfo['m']['3']['h'] and (
_time < _userinfo['m']['3']['u'] or
_userinfo['m']['3']['p']):
valid_donations.append("donation")
break
if _userinfo['m']['5']['h'] and (
_time < _userinfo['m']['5']['u'] or
_userinfo['m']['5']['p']):
valid_donations.append("donation")
break
except BaseException:
pass
return valid_donations
async def has_special_permission(self, id, support=False,
developer=False, admin=False,
trusted=False):
try:
id = int(id)
except BaseException:
return False
if support and id in config['roles']['support']:
return True
if developer and id in config['roles']['developer']:
return True
if admin and id in config['roles']['admins']:
return True
if trusted and id in config['roles']['trusted']:
return True
return False
async def has_guild_donated(guild_info, donation=True, partner=True):
_time = time.time()
try:
if partner:
_userinfo = await get_user_info(guild_info['d']['g']['o']['id'])
if _userinfo and _userinfo['m']['p']:
return True
except BaseException:
pass
for id in guild_info['d']['de']:
try:
_userinfo = await get_user_info(id)
if has_special_permission(id, support=True, developer=True, admin=True, trusted=True):
return True
if _userinfo:
if donation:
if _userinfo['m']['1']['h'] and (
_time < _userinfo['m']['1']['u'] or
_userinfo['m']['1']['p']):
return True
if _userinfo['m']['3']['h'] and (
_time < _userinfo['m']['3']['u'] or
_userinfo['m']['3']['p']):
return True
if _userinfo['m']['5']['h'] and (
_time < _userinfo['m']['5']['u'] or
_userinfo['m']['5']['p']):
return True
except BaseException:
pass
return False
# async def async_cache_discord(url, bot_type, key=None, custom_token=None, default={}, cachetime=120):
# if bot_type not in config['tokens']:
# return False, default
# if not custom_token:
# token = config['tokens'].get(bot_type)
# else:
# token = custom_token
# key = token['access_token']
# if not key:
# key = url
# url = f"{_oauth2['api_base']}/v6/{url}"
# _t = time.time()
# if key not in discord_cache or _t - discord_cache.get(key)['s'] > 0:
# try:
# rockutils.prefix_print(f"Retrieving {url}", prefix="Cacher")
# async with aiohttp.ClientSession() as session:
# async with requests.get(url, headers={"Authorization": f"Bot {token}"}) as r:
# data = await r.json()
# if isinstance(data, dict) and data.get("code"):
# rockutils.prefix_print(
# f"Encountered bad response: {data}", prefix="Cacher")
# discord_cache[key] = {
# "d": default,
# "s": _t + cachetime
# }
# return False, data.get("code", -1)
# discord_cache[key] = {
# "d": data,
# "s": _t + cachetime
# }
# except Exception as e:
# exc_info = sys.exc_info()
# traceback.print_exception(*exc_info)
# rockutils.prefix_print(
# str(e), prefix="cache_discord", text_colour="red")
# return False, []
# return True, discord_cache[key]['d']
async def cache_discord(url, bot_type, key=None, custom_token=None, default={}, cachetime=120):
if bot_type not in config['tokens']:
return False, default
if not custom_token:
token = config['tokens'].get(bot_type)
else:
token = custom_token
key = token['access_token']
if not key:
key = url
url = f"{_oauth2['api_base']}/v6/{url}"
_t = time.time()
if key not in discord_cache or _t - discord_cache.get(key)['s'] > 0:
try:
rockutils.prefix_print(f"Retrieving {url}", prefix="Cacher")
async with aiohttp.ClientSession() as _session:
async with _session.get(url, headers={"Authorization": f"Bot {token}"}) as res:
data = await res.json()
if isinstance(data, dict) and data.get("code"):
rockutils.prefix_print(
f"Encountered bad response: {data}", prefix="Cacher")
discord_cache[key] = {
"d": default,
"s": _t + cachetime
}
return False, data.get("code", -1)
discord_cache[key] = {
"d": data,
"s": _t + cachetime
}
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
rockutils.prefix_print(
str(e), prefix="cache_discord", text_colour="red")
return False, []
return True, discord_cache[key]['d']
async def has_elevation(guild_id, member_id, guild_info=None, bot_type="main"):
continue_cache = True
# if "user_id" in session:
# user_id = int(session['user_id'])
# if user_id in config['roles']['support']:
# return True
# if user_id in config['roles']['developer']:
# return True
# if user_id in config['roles']['admins']:
# return True
# _member_id = int(member_id)
# if _member_id in config['roles']['support']:
# return True
# if _member_id in config['roles']['developer']:
# return True
# if _member_id in config['roles']['admins']:
# return True
elevated = False
responce = await create_job(o="iselevated", a=[str(member_id), str(guild_id)], r="*")
for _, cluster_data in responce['d'].items():
if cluster_data.get("success", False):
if cluster_data.get("elevated", False):
elevated = True
return elevated
# if not guild_info:
# guild_info = await get_guild_info(guild_id)
# if isinstance(guild_info, dict) and guild_info['d']['b']['hd']:
# bot_type = "donator"
# bot_type = "debug" if _debug else bot_type
# guild_success, guild = await cache_discord(f"guilds/{guild_id}", bot_type, key=f"guild:{guild_id}", cachetime=600)
# if asyncio.iscoroutine(guild):
# guild = await guild()
# if not guild_success and guild == 50001:
# continue_cache = False
# if guild_info:
# if guild_info['d']['g']['o']:
# if int(guild_info['d']['g']['o']['id'] == int(member_id)):
# return True
# if guild_success:
# if "owner_id" in guild and (int(guild['owner_id']) == int(member_id)):
# return True
# if guild_info:
# # check staff list and if they are on it
# if guild_info.get("st"):
# if str(member_id) in guild_info['st']['u']:
# return True
# if continue_cache:
# member_success, member = await cache_discord(f"guilds/{guild_id}/members/{member_id}", bot_type, key=f"member:{guild_id}:{member_id}", cachetime=60)
# if asyncio.iscoroutine(member):
# member = await member()
# if not member_success and guild == 50001:
# continue_cache = False
# if continue_cache:
# role_success, roles = await cache_discord(f"guilds/{guild_id}/roles", bot_type, key=f"role:{guild_id}", cachetime=60)
# if asyncio.iscoroutine(roles):
# roles = await roles()
# if not role_success and guild == 50001:
# continue_cache = False
# # get member and roles they have and check if they have certain roles
# if continue_cache:
# if member_success and role_success and "roles" in member:
# for role_id in map(int, member['roles']):
# for role in roles:
# if int(role['id']) == role_id:
# permissions = discord.permissions.Permissions(
# role['permissions'])
# if permissions.manage_guild or permissions.ban_members or permissions.administrator:
# return True
# return False
# async def has_elevation(guild_id, member_id, guild_info=None, bot_type="main"):
# if "user_id" in session:
# user_id = int(session['user_id'])
# if user_id in config['roles']['support']:
# return True
# if user_id in config['roles']['developer']:
# return True
# if user_id in config['roles']['admins']:
# return True
# if not guild_info:
# guild_info = await get_guild_info(guild_id)
# if isinstance(guild_info, dict) and guild_info['d']['b']['hd']:
# bot_type = "donator"
# bot_type = "debug" if _debug else bot_type
# guild_success, guild = await async_cache_discord(
# f"guilds/{guild_id}", bot_type, key=f"guild:{guild_id}", cachetime=600)
# if asyncio.iscoroutine(guild):
# guild = await guild()
# if guild_info:
# if int(guild_info['d']['g']['o']['id'] == int(member_id)):
# return True
# if guild_success:
# if "owner_id" in guild and (int(guild['owner_id']) == int(member_id)):
# return True
# if guild_info:
# # check staff list and if they are on it
# if guild_info.get("st"):
# if str(member_id) in guild_info['st']['u']:
# return True
# member_success, member = await async_cache_discord(
# f"guilds/{guild_id}/members/{member_id}", bot_type, key=f"member:{guild_id}:{member_id}")
# role_success, roles = await async_cache_discord(
# f"guilds/{guild_id}/roles", bot_type, key=f"role:{guild_id}")
# if asyncio.iscoroutine(member):
# member = await member()
# if asyncio.iscoroutine(roles):
# roles = await roles()
# # get member and roles they have and check if they have certain roles
# if member_success and role_success and "roles" in member:
# for role_id in map(int, member['roles']):
# for role in roles:
# if int(role['id']) == role_id:
# permissions = discord.permissions.Permissions(
# role['permissions'])
# if permissions.manage_guild or permissions.ban_members or permissions.administrator:
# return True
# return False
async def get_guild_roles(guild_id):
roles = {}
responce = await create_job(o="getguildroles", a=str(guild_id), r="*")
for _, cluster_data in responce['d'].items():
if cluster_data.get("success", False):
for role in cluster_data.get("roles"):
if role['id'] in roles:
if role['higher'] == True:
roles[role['id']]['higher'] = True
else:
roles[role['id']] = role
return roles.values()
async def get_guild_channels(guild_id):
responce = await create_job(o="getguildchannels", a=str(guild_id), r="*")
for _, cluster_data in responce['d'].items():
if cluster_data.get("success", False):
return cluster_data.get("channels")
async def get_user(token):
_t = time.time()
key = token['access_token']
if key not in user_cache or _t - user_cache.get(key)['s'] > 0:
try:
discord = make_session(token=token)
user = await discord.request("GET", _oauth2['api_base'] + '/users/@me')
_users = await user.json()
has, _guilds = cache.check_cache(
"user:" + _users['id'] + ":guilds")
if not has:
guilds = await discord.request("GET", _oauth2['api_base'] + '/users/@me/guilds')
_guilds = await guilds.json()
cache.add_cache(
"user:" + _users['id'] + ":guilds", 30, _guilds)
await discord.close()
user_cache[key] = {
"d": {"user": _users, "guilds": _guilds},
"s": _t + 60
}
data = user_cache[key]['d']
if str(user.status)[0] != "2":
return False, data
if str(guilds.status)[0] != "2":
return False, data
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
print(f"[get_user] {e}")
return False, {}
data = user_cache[key]['d']
if data['user'].get('code') == 0 and "401" in data['user'].get('message', ''):
return False, data
# if "message" in data['user'] and "401: Unauthorized" in data['user'][
# 'message']:
# return False, data
return True, data
# has_elevation(guild id, member id, bot type)
# has_elevation(436243598925627392, 143090142360371200, "debug")
#############################################################
# DASHBOARD PAGES
#############################################################
@app.route("/logout")
async def _logout():
session.clear()
return redirect("/")
@app.route("/login")
async def _login():
discord = make_session(scope=['identify', 'guilds'])
authorization_url, state = discord.authorization_url(
_oauth2['authorization_url'])
session['oauth2_state'] = state
await discord.close()
return redirect(authorization_url)
@app.route("/callback")
async def _callback():
url = request.url.replace('http://', 'https://', 1)
try:
discord = make_session(state=session.get(
"oauth2_state"), scope=['identify', 'guilds'])
token = await discord.fetch_token(
_oauth2['token_url'],
client_secret=_oauth2['client_secret'],
authorization_response=url)
await discord.close()
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return redirect("/login")
user_success, user = await get_user(token)
if asyncio.iscoroutine(user):
user = await user()
if not user_success:
return redirect("/login")
_t = math.ceil(time.time())
session['oauth2_token'] = token
session['oauth2_check'] = math.ceil(time.time())
if user_success:
session['user_id'] = str(user['user']['id'])
session['user'] = str(user['user']['username']) + \
"#" + str(user['user']['discriminator'])
session['user_data'] = user['user']
session['guild_data'] = user['guilds']
session['reloaded_data'] = _t
session['dashboard_guild'] = "-"
session['developer_mode'] = False
session.permanent = True
if session.get("previous_path"):
return redirect(session['previous_path'])
return redirect("/dashboard")
def valid_oauth_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
session['previous_path'] = request.path
if session.get("oauth2_token") is None:
return redirect("/login")
should_check = False
if sum(
1 if not session.get(c) else 0 for c in [
'user_id',
'user_data',
'guild_data',
'oauth2_check']) > 0:
should_check = True
if session.get("oauth2_check") is None or time.time() - \
session.get("oauth2_check") > 604800:
should_check = True
if should_check:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
async def is_valid_dash_user():
session['previous_path'] = request.path
# Manualy retrieving the guild data from oauth2 every
# time is not required as oauth is updated every 2 minutes.
# Handled by before_requests -> cache_data()
guilds = session.get("guild_data")
if not guilds:
cache_data()
guilds = session.get("guild_data")
if not guilds:
return redirect("/login")
guild = None
dashboard_guild = session.get("dashboard_guild")
for item in guilds:
if isinstance(item, dict) and str(item.get("id")) == str(dashboard_guild):
guild = item
# redirects to invalid guild if no data and no developer mode
if not guild and not session.get("developer_mode", False):
return redirect("/dashboard?invalidguild")
# allow if they are the owner
if guild['owner']:
return True
# check users permissions from oauth2
permissions = discord.permissions.Permissions(guild['permissions'])
if permissions.manage_guild or permissions.ban_members or permissions.administrator:
return True
# check if has elevation
return await has_elevation(
guild['id'],
session.get("user_id"),
bot_type="main")
def valid_dash_user(f):
@wraps(f)
async def decorated_function(*args, **kwargs):
session['previous_path'] = request.path
# Manualy retrieving the guild data from oauth2 every
# time is not required as oauth is updated every 2 minutes.
# Handled by before_requests -> cache_data()
guilds = session.get("guild_data")
if not guilds:
cache_data()
guilds = session.get("guild_data")
if not guilds:
return redirect("/login")
guild = None
dashboard_guild = session.get("dashboard_guild")
for item in guilds:
if isinstance(item, dict) and str(item.get("id")) == str(dashboard_guild):
guild = item
# redirects to invalid guild if no data and no developer mode
if not guild and not session.get("developer_mode", False):
return redirect("/dashboard?invalidguild")
# allow if they are the owner
if guild['owner']:
return f(*args, **kwargs)
# check users permissions from oauth2
permissions = discord.permissions.Permissions(guild['permissions'])
if permissions.manage_guild or permissions.ban_members or permissions.administrator:
return f(*args, **kwargs)
# check if has elevation
if not await has_elevation(
guild['id'],
session.get("user_id"),
bot_type="main"):
return redirect("/dashboard?missingpermission")
return f(*args, **kwargs)
return decorated_function
@app.before_request
async def cache_data():
# Checks all oauth2 information is up to date and does not check if it is
# a static page
if "static" not in request.url:
_t = math.ceil(time.time())
if session.get("reloaded_data") and session.get(
"oauth2_token") and _t - session.get("reloaded_data") > 120:
user_success, user = await get_user(session.get("oauth2_token"))
if asyncio.iscoroutine(user):
user = await user()
if user_success:
session['reloaded_data'] = _t
session['user_id'] = str(user['user']['id'])
session['user_data'] = user['user']
session['guild_data'] = user['guilds']
session.permanent = True
session.permanent = True
app.permanent_session_lifetime = timedelta(days=7)
# @app.route("/dashboard")
# @valid_oauth_required
# async def _dashboard():
# return "I am dashboard"
# _args = list(dict(request.args).keys())
# if len(_args) == 1:
# arg = _args[0]
# if arg == "missingpermission":
# pass
# elif arg == "invalidguild":
# pass
# elif arg == "missingdata":
# pass
# handle invalid guild
# handle missing guild info
# handle no permissions\
@app.route("/api/session")
async def getsession():
return jsonify(dict(session))
@app.route("/api/getbackground/<background>")
async def getbackground(background):
cdnpath = config['cdn']['location']
if "custom" not in background:
f = os.path.join(cdnpath, "Images", background)
else:
f = os.path.join(cdnpath, "CustomImages", background)
if not os.path.exists(f):
background = background.replace(".png", ".gif")
f = os.path.join(cdnpath, "CustomImages", background)
if not os.path.exists(f):
background = background.replace(".gif", ".jpg")
f = os.path.join(cdnpath, "CustomImages", background)
if not os.path.exists(f):
bgloc = f"preview-samples/none.jpg"
if not os.path.exists(bgloc):
txt = "This background could not be found"
f_h = open(os.path.join(cdnpath, "Images", "default.png"), "rb")
i_h = Image.open(f_h)
i_h = i_h.convert("RGBA")
size = 40
while True:
default = ImageFont.truetype(os.path.join(
cdnpath, "Fonts", "default.ttf"), size)
size -= 1
w, h = default.getsize(txt)
if w < i_h.size[0] or size < 2:
break
iw, ih = i_h.size
y = ih - 20 - h
x = math.floor((iw - w) / 2)
frame_draw = ImageDraw.Draw(i_h)
frame_draw.text((x + 1, y + 1), txt, font=default, fill=(0, 0, 0))
frame_draw.text((x + 1, y - 1), txt, font=default, fill=(0, 0, 0))
frame_draw.text((x - 1, y + 1), txt, font=default, fill=(0, 0, 0))
frame_draw.text((x - 1, y - 1), txt, font=default, fill=(0, 0, 0))
frame_draw.text((x, y), txt, font=default, fill=(255, 255, 255))
i_h = i_h.convert("RGB")
i_h.thumbnail((400, 160))
i_h.save(bgloc, format="jpeg", quality=50)
f_h.close()
else:
bgloc = f"preview-samples/{'.'.join(background.split('.')[:-1])}.jpg"
if not os.path.exists(bgloc) or "custom" in f.lower():
txt = background
f_h = open(f, "rb")
i_h = Image.open(f_h)
i_h = i_h.convert("RGBA")
txt = ".".join(txt.split(".")[:-1])
size = 40
while True:
default = ImageFont.truetype(os.path.join(
cdnpath, "Fonts", "default.ttf"), size)
size -= 1
w, h = default.getsize(txt)
if w < i_h.size[0] or size < 2:
break
iw, ih = i_h.size
y = ih - 20 - h
x = math.floor((iw - w) / 2)
frame_draw = ImageDraw.Draw(i_h)
frame_draw.text((x + 1, y + 1), txt, font=default, fill=(0, 0, 0))
frame_draw.text((x + 1, y - 1), txt, font=default, fill=(0, 0, 0))
frame_draw.text((x - 1, y + 1), txt, font=default, fill=(0, 0, 0))
frame_draw.text((x - 1, y - 1), txt, font=default, fill=(0, 0, 0))
frame_draw.text((x, y), txt, font=default, fill=(255, 255, 255))
i_h = i_h.convert("RGB")
i_h.thumbnail((400, 160))
i_h.save(bgloc, format="jpeg", quality=50)
f_h.close()
return await send_file(bgloc, cache_timeout=-1)
@app.route("/api/internal-status")
async def api_internal_status():
return jsonify(cluster_status)
@app.route("/api/status")
async def api_status():
_time = time.time()
clusters = {}
for i in list(["debug", "donator", "b"] + list(range(config['bot']['clusters']))):
if i == "debug":
name = "DB"
elif i == "b":
name = "B"
elif "donator" in str(i):
name = i.replace("donator", "DN")
else:
name = f"C{i}"
clusters[str(i)] = {
"alive": False,
"pingalive": False,
"stats": {},
"lastping": 0,
"id": i,
"name": name
}
for cluster, ping in last_ping.items():
cluster = str(cluster)
clusters[cluster]['alive'] = True
if _time - ping < 70:
clusters[cluster]['pingalive'] = True
clusters[cluster]['lastping'] = _time - ping
for cluster, data in cluster_data.items():
print(cluster, data)
cluster = str(cluster)
clusters[cluster]['stats'] = data
clusters[cluster]['stats']['uptime'] = time.time() - data['init']
clusters[cluster]['stats']['displayed'] = rockutils.produce_human_timestamp(
time.time() - data['init'])
if data.get("latencies"):
clusters[cluster]['stats']['highest_latency'] = max(
list(map(lambda o: o[1], data['latencies'])))
clusters[cluster]['stats']['lowest_latency'] = max(
list(map(lambda o: o[1], data['latencies'])))
else:
clusters[cluster]['stats']['highest_latency'] = 0
clusters[cluster]['stats']['lowest_latency'] = 0
cdnpath = os.path.join(config['cdn']['location'], "Output")
total, used, free = shutil.disk_usage(config['cdn']['location'])
space_used = round(get_size(cdnpath) / 10000000) / 100
total_space = round(total / 10000000) / 100
space_percentage = round((space_used / total_space) * 1000) / 10
total_images = len(os.listdir(cdnpath))
data = {}
totalstats = {}
averages = {}
for v, k in clusters.items():
if "socketstats" in k.get('stats', {}):
for name, value in k['stats']['socketstats'][0].items():
if name not in totalstats:
totalstats[name] = 0
totalstats[name] += value
averages[v] = k['stats']['socketstats'][2]
data['socketstats'] = {
"events": sum([int(c['stats']['socketstats'][1]) for c in clusters.values() if "socketstats" in c.get('stats', {})]),
"totalevents": totalstats,
"average": str(sum([int(c['stats']['socketstats'][2]) for c in clusters.values() if "socketstats" in c.get('stats', {})])),
"averages": averages,
}
_clusters = {}
for k, v in clusters.items():
_clusters[k] = copy.deepcopy(v)
if "socketstats" in _clusters[k].get('stats', {}):
_clusters[k]['stats'].pop("socketstats")
data['clusters'] = list(
sorted(_clusters.values(), key=lambda o: o['name']))
data['space'] = {
"space_used": space_used,
"total_space": total_space,
"space_percentage": space_percentage,
"stored_images": total_images,
"analytics": {
"kb_generated": int(await get_value(connection, "stats", "kb_generated", raw=True)),
"images_made": int(await get_value(connection, "stats", "images_made", raw=True)),
"images_requested": int(await get_value(connection, "stats", "images_requested", raw=True))
}
}
return jsonify(data)
@ app.route("/api/search", methods=["GET", "POST"])
async def api_search():
form = dict(await request.form)
if "term" in form and len(form['term']) > 3:
term = form.get("term")
if len(term) > 2:
try:
term = int(term)
canInt = True
except BaseException:
canInt = False
pass
if canInt:
result_payload = await create_job(request=None, o="guildsfind", a=[0, term], r="*")
payload = []
for data in result_payload['d'].values():
if data['success']:
payload = [data['results']]
else:
result_payload = await create_job(request=None, o="guildsfind", a=[1, term], r="*")
payload = rockutils.merge_results_lists(result_payload['d'])
payload = sorted(
payload, key=lambda o: o['users'], reverse=True)
_payload = payload
ids = []
for load in payload:
if not load['id'] in ids:
_payload.append(load)
ids.append(load['id'])
return jsonify(success=True, data=_payload)
else:
return jsonify(success=True, data=[])
else:
return jsonify(
success=False,
error="Missing search term at key 'term'")
@ app.route("/api/searchemoji", methods=["GET", "POST"])
async def api_searchemoji():
form = dict(await request.form)
if "term" in form and len(form['term']) > 3:
result_payload = await create_job(request=None, o="searchemoji", a=form.get("term"), r="*")
payload = rockutils.merge_results_lists(
result_payload['d'], key="data")
for i, v in enumerate(payload):
payload[i][3] = ""
return jsonify(success=True, data=payload)
return jsonify(
success=False,
error="Missing search term at key 'term'")
async def check_guild(guild):
guildinfo = await get_guild_info(int(guild.get("id")), default_if_empty=False)
if guildinfo:
return await has_elevation(int(guild.get("id")), int(session.get("user_id")), guild_info=guildinfo, bot_type="main")
else:
return False
@ app.route("/api/guilds")
@ valid_oauth_required
async def api_guilds():
user_id = session.get("user_id", None)
has, mutres = cache.check_cache("user:" + user_id + ":guilds_mutual")
if has:
_guilds = mutres[0]
clusters = mutres[1]
missing = mutres[2]
else:
# try:
# discord = make_session(token=session.get("oauth2_token"))
# user_guilds = await discord.request("GET", _oauth2['api_base'] + '/users/@me/guilds')
# guilds = []
# for guild in await user_guilds.json():
# if isinstance(guild, dict):
# guild['has_elevation'] = await check_guild(guild)
# guilds.append(guild)
# except Exception as e:
# return jsonify({"success": False, "error": str(e)})
# return jsonify({"success": True, "guilds": guilds})
discord = make_session(token=session.get("oauth2_token"))
has, val = cache.check_cache("user:" + session['user_id'] + ":guilds")
if not has:
guilds = await discord.request("GET", _oauth2['api_base'] + '/users/@me/guilds')
user_guilds_json = await guilds.json()
if type(user_guilds_json) == dict:
if user_guilds_json.get("message", "") == "You are being rate limited.":
# fuck
return jsonify({"success": False, "error": f"We are being ratelimited, try again in {user_guilds_json.get('retry_after')} seconds"})
cache.add_cache(
"user:" + session['user_id'] + ":guilds", 30, user_guilds_json)
else:
user_guilds_json = val
# user_guilds = await discord.request("GET", _oauth2['api_base'] + '/users/@me/guilds')
# user_guilds_json = await user_guilds.json()
# print(user_guilds_json)
ids = list(map(lambda o: o['id'], user_guilds_json))
guilds = []
clusters = []
missing = list(["debug", "donator", "b"] +
list(map(str, range(config['bot']['clusters']))))
if user_id:
responce = await create_job(o="userelevated", a=[user_id, ids], r="*", timeout=50)
for cluster, cluster_data in responce['d'].items():
if cluster_data.get("success", False):
if cluster in missing:
missing.remove(cluster)
else:
print(cluster, "is not in missing list")
clusters.append(cluster)
guilds += cluster_data.get("mutual", [])
_guildids = {}
_guilds = []
for guild in guilds:
_id = guild['id']
if _guildids.get(_id, True):
_guilds.append(guild)
_guildids[_id] = False
cache.add_cache(
"user:" + user_id + ":guilds_mutual", 30, [_guilds, clusters, missing])
return jsonify({"success": True, "guilds": _guilds, "clusters": clusters, "missing": missing})
@ app.route("/api/resetconfig", methods=["POST"])
@ valid_oauth_required
async def api_resetconfig():
user_id = session.get("user_id", None)
guild_id = session.get("dashboard_guild", None)
if not guild_id:
return jsonify(success=False, error="Invalid guild key")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return jsonify(success=False, error="No guild information")
if not await has_elevation(guild_id, user_id, guild_info=guild_info, bot_type="main"):
return jsonify(success=False, error="Missing permissions")
# r.table("guilds").get(guild_id).delete().run(rethink)
await self.delete_value("guilds", guild_id)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
@ app.route("/api/invites", methods=["POST"])
@ valid_oauth_required
async def api_invites():
user_id = session.get("user_id", None)
guild_id = session.get("dashboard_guild", None)
if not guild_id:
return jsonify(success=False, error="Invalid guild key")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return jsonify(success=False, error="No guild information")
if not await has_elevation(guild_id, user_id, guild_info=guild_info, bot_type="main"):
return jsonify(success=False, error="Missing permissions")
invites = []
_time = time.time()
for invite in guild_info['d']['i']:
invite['duration'] = int(invite.get('duration', 0))
invite['created_at_str'] = rockutils.since_unix_str(
invite['created_at'])
if invite['duration'] > 0:
invite['expires_at_str'] = rockutils.since_seconds_str(
_time - (invite['created_at'] + invite['duration']), include_ago=False)
else:
invite['expires_at_str'] = "∞"
invites.append(invite)
invites = sorted(invites, key=lambda o: o['uses'], reverse=True)
return jsonify(success=True, data=invites)
@ app.route("/api/punishments/<mtype>", methods=["GET", "POST"])
@ valid_oauth_required
# @valid_dash_user
async def api_punishments(mtype="false"):
res = await is_valid_dash_user()
if res != True:
return res
# user id | user display | moderator id | moderator name | punishment type
# | reason | punishment start | punishment duration | is handled
guild_id = session.get("dashboard_guild", None)
if not guild_id:
return jsonify(success=False, error="Invalid guild key")
if not mtype.lower() in ['true', 'false', 'reset', 'export']:
mtype = "false"
if mtype.lower() in ['true', 'false']:
try:
if os.path.exists(f"punishments/{guild_id}.csv"):
file = open(f"punishments/{guild_id}.csv", "r")
data = csv.reader(file)
else:
data = []
if mtype.lower() == "true":
data = list(filter(lambda o: o[8].lower() == "false", data))
# punishment type | user display | moderator display | reason |
# date occured | duration | handled
_data = sorted(data, key=lambda o: int(o[6]), reverse=True)
data = []
for audit in _data:
data.append(
[f"{audit[4][0].upper()}{audit[4][1:].lower()}",
f"{audit[1]} ({audit[0]})", f"{audit[3]} ({audit[2]})",
"-" if audit[5] in [None, "", " "] else audit[5].strip(),
rockutils.since_unix_str(int(audit[6])).strip(),
rockutils.since_seconds_str(
int(audit[7]),
allow_secs=True, include_ago=False).strip()
if int(audit[7]) > 0 else ("∞" if "temp" in audit[4].lower() else "-"),
"Handled" if audit[8].lower() == "true" else "Ongoing", ])
return jsonify(success=True, data=data)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
elif mtype.lower() == "export":
if os.path.exists(f"punishments/{guild_id}.csv"):
return await send_file(f"punishments/{guild_id}.csv", as_attachment=True, attachment_filename=f"{guild_id}.csv")
else:
return jsonify(success=False)
elif mtype.lower() == "reset":
if os.path.exists(f"punishments/{guild_id}.csv"):
os.remove(f"punishments/{guild_id}.csv")
return jsonify(success=True)
else:
return jsonify(success=True)
@ app.route("/api/logs/<mtype>", methods=["GET", "POST"])
@ valid_oauth_required
# @valid_dash_user
async def api_logs(mtype="false"):
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
if not guild_id:
return jsonify(success=False, error="Invalid guild key")
if not mtype.lower() in ['view', 'reset', 'export']:
mtype = "view"
if mtype.lower() == "view":
try:
if os.path.exists(f"logs/{guild_id}.csv"):
file = open(f"logs/{guild_id}.csv", "r")
data = list(csv.reader(file))
else:
data = []
return jsonify(success=True, data=data)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
elif mtype.lower() == "export":
if os.path.exists(f"logs/{guild_id}.csv"):
return await send_file(f"logs/{guild_id}.csv", as_attachment=True, attachment_filename=f"{guild_id}.csv")
else:
return jsonify(success=False)
elif mtype.lower() == "reset":
if os.path.exists(f"logs/{guild_id}.csv"):
os.remove(f"logs/{guild_id}.csv")
return jsonify(success=True)
else:
return jsonify(success=True)
@ app.route("/api/invite/<id>", methods=["GET", "POST"])
async def api_invite(id):
guild_info = await get_guild_info(id)
if not guild_info:
return jsonify(success=False, error="This guild is not valid")
if not guild_info['d']['b']['ai']:
return jsonify(
success=False,
error="This server has disabled invites through welcomer")
has_invite = False
invite_code = ""
responce = await create_job(o="guildinvite", a=str(id), r="*")
for cluster_id, cluster_data in responce['d'].items():
if cluster_data.get("success", False) and \
cluster_data.get("invite", None):
invite_code = cluster_data['invite']
has_invite = True
if not has_invite:
return jsonify(
success=False,
error="Failed to create an invite. The bot may be missing permissions")
return jsonify(success=True, code=invite_code)
# /api/logs/retrieve
# /api/logs/clear
# /api/logs/export
# /api/punishments/retrieve
# /api/punishments/clear
# /api/punishments/export
##########################################################################
@ app.route("/patreonhook", methods=['GET', 'POST'])
async def patreon():
print("Received patreon webhook")
headers = request.headers
json_data = await request.json
print("recieved patreon hook")
patreon_event = headers['X-Patreon-Event']
try:
discord_info = json_data['included'][1]['attributes']['social_connections']['discord']
except BaseException:
discord_info = None
if isinstance(discord_info, dict):
patreon_discord_id = discord_info.get("user_id")
else:
patreon_discord_id = 0
if "members:" in patreon_event:
await rockutils.send_webhook("https://canary.[removed]", json.dumps(json_data['data']['attributes']))
patreon_donation_ammount = json_data['data']['attributes'].get(
'will_pay_amount_cents', 0) / 100
lifetime_donation = json_data['data']['attributes'].get(
'lifetime_support_cents', 0) / 100
patreon_name = json_data['data']['attributes']['full_name']
patreon_webhook = rockutils.load_json(
"cfg/config.json")['webhooks']['donations']
if patreon_event == "members:pledge:create":
await rockutils.send_webhook(patreon_webhook, f":money_with_wings: | `{patreon_name}` {f'<@{patreon_discord_id}> `{patreon_discord_id}`' if patreon_discord_id != 0 else '`No discord provided`'} has pledged $`{patreon_donation_ammount}`! Total Pledge: $`{lifetime_donation}`")
elif patreon_event == "members:pledge:update":
await rockutils.send_webhook(patreon_webhook, f":money_with_wings: | `{patreon_name}` {f'<@{patreon_discord_id}> `{patreon_discord_id}`' if patreon_discord_id != 0 else '`No discord provided`'} has updated their pledge to $`{patreon_donation_ammount}`! Total Pledge: $`{lifetime_donation}`")
elif patreon_event == "members:pledge:delete":
await rockutils.send_webhook(patreon_webhook, f":money_with_wings: | `{patreon_name}` {f'<@{patreon_discord_id}> `{patreon_discord_id}`' if patreon_discord_id != 0 else '`No discord provided`'} is no longer pledging. Total Pledge: $`{lifetime_donation}`")
elif patreon_event == "members:delete":
await rockutils.send_webhook(patreon_webhook, f":money_with_wings: | `{patreon_name}` {f'<@{patreon_discord_id}> `{patreon_discord_id}`' if patreon_discord_id != 0 else '`No discord provided`'} is no longer pledging. Total Pledge: $`{lifetime_donation}`")
if patreon_discord_id != 0:
await create_job(o="retrieveuser", a=patreon_discord_id, r="*")
# userinfo = r.table("users").get(
# str(patreon_discord_id)).run(rethink)
userinfo = await get_value(connection, "users", str(patreon_discord_id))
values = ['1', '3', '5']
if userinfo:
for key in values:
if key in userinfo['m']:
if userinfo['m'][key]['p']:
userinfo['m'][key]['h'] = False
userinfo['m'][key]['p'] = False
donation_types = {
"0": ["Welcomer Custom Background"],
"1": ["Welcomer Pro x1"],
"3": ["Welcomer Pro x3"],
"5": ["Welcomer Pro x5"]
}
k = None
if patreon_donation_ammount == 5:
k = "1"
elif patreon_donation_ammount == 10:
k = "3"
elif patreon_donation_ammount == 15:
k = "5"
if k:
if patreon_event == "members:pledge:create":
userinfo['m'][k]['h'] = True
userinfo['m'][k]['p'] = True
elif patreon_event == "members:pledge:update":
userinfo['m'][k]['h'] = True
userinfo['m'][k]['p'] = True
if patreon_donation_ammount in [1, 6]:
k = "0"
userinfo['m']['hs'] = True
if k:
membership_name = donation_types[k]
else:
return "False"
# r.table("users").get(str(patreon_discord_id)
# ).update(userinfo).run(rethink)
await set_value(connection, "users", str(patreon_discord_id), userinfo)
mutual_clusters = sorted(userinfo['m'].keys())
for recep in mutual_clusters:
try:
recep = int(recep)
except BaseException:
pass
data = await create_job(o="donationannounce", a=[patreon_discord_id, membership_name], r=recep)
if recep in data['d']:
break
return "True"
@ app.route("/donate/<dtype>/<months>")
@ valid_oauth_required
async def donate_create(dtype, months):
# return redirect("/donate?disabled")
donation_types = {
"0": ["Welcomer Custom Background"],
"1": ["Welcomer Pro x1"],
"3": ["Welcomer Pro x3"],
"5": ["Welcomer Pro x5"],
}
dontype = dtype + ":" + str(months)
if str(dtype) == "0":
months = "ever"
else:
months = f" {months} month(s)"
if dontype not in prices.keys():
return redirect("/donate?invaliddonation")
donation = donation_types.get(dtype)
price = prices.get(dontype)
description = f"{donation[0]} for{months}"
patreon_webhook = config['webhooks']['donations']
if not donation:
return redirect("/donate?invaliddonation")
payer = {"payment_method": "paypal"}
items = [{"name": dontype, "price": price,
"currency": "GBP", "quantity": "1"}]
amount = {"total": price, "currency": "GBP"}
redirect_urls = {
"return_url": f"https://{_domain}/donate/confirm?success=true",
"cancel_url": f"https://{_domain}/donate?cancel"}
payment = paypalrestsdk.Payment({"intent": "sale",
"payer": payer,
"redirect_urls": redirect_urls,
"transactions": [{"item_list": {"items": items},
"amount": amount,
"description": description}]},
api=paypal_api)
valid = payment.create()
if valid:
for link in payment.links:
if link['method'] == "REDIRECT":
return redirect(link["href"])
else:
await rockutils.send_webhook(patreon_webhook, f"`{str(payment.error)}`")
return redirect("/donate?paymentcreateerror")
@ app.route("/donate/confirm")
@ valid_oauth_required
async def donate_confirm():
# return redirect("/donate?disabled")
user = session['user_data']
userid = session['user_id']
responce = await create_job(o="retrieveuser", a=userid, r="*")
# userinfo = r.table("users").get(str(userid)).run(rethink)
userinfo = await get_value(connection, "users", str(userid))
if not userinfo:
return redirect("/donate?userinfogone")
try:
payment = paypalrestsdk.Payment.find(request.args.get('paymentId'))
except BaseException:
return redirect("/donate?invalidpaymentid")
name = payment.transactions[0]['item_list']['items'][0]['name']
amount = float(payment.transactions[0]["amount"]["total"])
if name not in prices or amount != prices.get(name):
return redirect("/donate?invalidprice")
dtype, months = name.split(":")
try:
months = int(months)
except BaseException:
return redirect("/donate?invalidmonth")
if not dtype or not months:
return redirect("/donate?invalidarg")
donation_types = {
"0": ["Welcomer Custom Background"],
"1": ["Welcomer Pro x1"],
"3": ["Welcomer Pro x3"],
"5": ["Welcomer Pro x5"]
}
dname = donation_types.get(dtype, "???")
success = payment.execute({"payer_id": request.args.get('PayerID')})
with open("pperrs.txt", "a+") as fil:
print(f"\n{request.args.get('PayerID')} : {success}\n")
fil.write(f"\n{request.args.get('PayerID')} : {success}\n")
if success:
patreon_webhook = config['webhooks']['donations']
message = f"""User: `{user.get('username')}` <@{userid}>\nDonation: **{dname[0]}** (£ **{amount}**)\nMonths: {months}"""
await rockutils.send_webhook(patreon_webhook, message)
try:
name = payment.transactions[0]["amount"]
if dtype == "0":
userinfo['m']['hs'] = True
membership_name = "Custom Background"
if dtype == "1":
userinfo['m']['1']['h'] = True
userinfo['m']['1']['u'] = time.time() + \
(2592000 * (months))
membership_name = "Welcomer Pro x1"
elif dtype == "3":
userinfo['m']['3']['h'] = True
userinfo['m']['3']['u'] = time.time() + \
(2592000 * (months))
membership_name = "Welcomer Pro x3"
elif dtype == "5":
userinfo['m']['5']['h'] = True
userinfo['m']['5']['u'] = time.time() + \
(2592000 * (months))
membership_name = "Welcomer Pro x5"
else:
membership_name = f"Donation (£{amount})"
# r.table("users").get(str(userid)).update(userinfo).run(rethink)
await set_value(connection, "users", str(userid), userinfo)
receps = []
for cluster_id, cluster_data in responce['d'].items():
if cluster_data.get("success", False):
receps.append(cluster_id)
for recep in receps:
data = await create_job(o="donationannounce", a=[userid, membership_name], r=recep)
if recep in data['d'] and data['d'][recep]:
break
return redirect("/donate?success")
except Exception as e:
await rockutils.send_webhook(patreon_webhook, f":warning: | <@143090142360371200> Problem processing donation for <@{userid}>\n`{e}`")
return redirect("/donate?fatalexception")
else:
return redirect("/")
##########################################################################
# @app.route("/dashboard/{}", methods=['GET', 'POST'])
# @valid_oauth_required
# @valid_dash_user
# async def dashboard_():
# guild_id = session.get("dashboard_guild", None)
# guilds = list(sorted(session.get("guild_data", []), key=lambda o: o.get("name", "")))
# guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
# if not guild_id:
# return redirect("/dashboard")
# guild_info = await get_guild_info(guild_id)
# guild_donations = await get_guild_donations(guild_info)
# if not guild_info:
# return redirect("/dashboard?missingdata")
# if request.method == "GET":
# _config = {
# "_all_translations": os.listdir("locale"),
# "_donations": guild_donations,
# "prefix": guild_info['d']['b']['p'],
# "locale": guild_info['d']['b']['l'],
# "forcedms": guild_info['d']['g']['fd'],
# "embedcolour": guild_info['d']['b']['ec'],
# "showstaff": guild_info['d']['b']['ss'],
# "allowinvites": guild_info['d']['b']['ai'],
# "splash": guild_info['d']['b']['s'] or "",
# "description": guild_info['d']['b']['d'] or ""
# }
# return await render_template("dashboard/botconfig.html",
# session=session, guild=guild, guilds=guilds, config=config)
# if request.method == "POST":
# form = dict(await request.form)
# try:
# update_payload = {}
# replaces = [
# ["d.b.p", form['prefix'], False, None, "prefix" ],
# ["d.b.l", form['locale'], False, None, "locale" ],
# ["d.b.d", form['description'], False, None, "description" ],
# ["d.b.ec", form['embedcolour'], True, "hex", "embedcolour" ],
# ["d.b.ss", form['showstaff'], True, "bool", "showstaff" ],
# ["d.b.ai", form['allowinvites'], True, "bool", "allowinvites" ],
# ["d.g.fd", form['forcedms'], True, "bool", "forcedms" ],
# ]
# for replace in replaces:
# if replace[2] and replace[3] and expect(replace[1], replace[3]) or not replace[2]:
# if not replace[1] is None:
# value = normalize_form(replace[1])
# oldvalue = rockutils.getvalue(replace[0], guild_info)
# rockutils.setvalue(replace[0], guild_info, value)
# if oldvalue != value:
# update_payload[replace[4]] = [oldvalue, value]
# if len(guild_donations) > 0:
# parsed_url = urlparse(form['splash'])
# if "imgur.com" in parsed_url.netloc:
# guild_info['d']['b']['s'] = form['splash']
# if form['splash'] != rockutils.getvalue("d.b.s", guild_info):
# update_payload['splash'] = [guild_info['d']['b']['s'], form['splash']]
# await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user_id", ""), json.dumps(update_payload)], f"{guild_id}.csv")
# await update_guild_info(guild_id, guild_info)
# await create_job(o="cachereload", a=guild_id, r="*")
# return jsonify(success=True)
# except Exception as e:
# return jsonify(success=False, error=str(e))
@ app.route("/dashboard/botconfig", methods=["GET", "POST"])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_botconfig():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
guild_donations = await get_guild_donations(guild_info)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
_config = {
"_all_translations": os.listdir("locale"),
"_donations": guild_donations,
"prefix": guild_info['d']['b']['p'],
"locale": guild_info['d']['b']['l'],
"forcedms": guild_info['d']['g']['fd'],
"embedcolour": guild_info['d']['b']['ec'],
"showstaff": guild_info['d']['b']['ss'],
"allowinvites": guild_info['d']['b']['ai'],
"splash": guild_info['d']['b']['s'] or "",
"description": guild_info['d']['b']['d'] or "",
"showwebsite": guild_info['d']['b'].get('sw', True)
}
return await render_template("dashboard/botconfig.html", session=session, guild=guild, guilds=guilds, config=_config)
if request.method == "POST":
form = dict(await request.form)
try:
update_payload = {}
replaces = [
["d.b.p", form['prefix'], False, None, "bot.prefix"],
["d.b.l", form['locale'], False, None, "bot.locale"],
["d.g.fd", form['forcedms'], True, "bool", "bot.forcedms"],
["d.b.ss", form['showstaff'], True, "bool", "bot.showstaff"],
["d.b.d", form['description'], False, None, "bot.description"],
["d.b.ec", form['embedcolour'], True, "hex", "bot.embedcolour"],
["d.b.ai", form['allowinvites'], True, "bool", "bot.allowinvites"],
["d.b.sw", form['showwebsite'], True, "bool", "bot.showwebsite"]
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
if len(guild_donations) > 0:
parsed_url = urlparse(form['splash'])
if "imgur.com" in parsed_url.netloc:
oldvalue = rockutils.getvalue("d.b.s", guild_info)
rockutils.setvalue("d.b.s", guild_info, form['splash'])
if oldvalue != form['splash']:
rockutils.setvalue(
"bot.splash", update_payload, [
rockutils.getvalue(
"d.b.s", guild_info), form['splash']])
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/guilddetails")
@ valid_oauth_required
# @valid_dash_user
async def dashboard_guilddetails():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
await create_job(o="cachereload", a=guild_id, r="*")
guild_info = await get_guild_info(guild_id)
guild_donations = await get_guild_donations(guild_info)
if not guild_info:
return redirect("/dashboard?missingdata")
return await render_template("dashboard/guilddetails.html", session=session, guild=guild, guilds=guilds, config=guild_info, donations=guild_donations)
@ app.route("/dashboard/invites")
@ valid_oauth_required
# @valid_dash_user
async def dashboard_invites():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
guild_donations = await get_guild_donations(guild_info)
if not guild_info:
return redirect("/dashboard?missingdata")
return await render_template("dashboard/invites.html", session=session, guild=guild, guilds=guilds, config=guild_info, donations=guild_donations)
@ app.route("/dashboard/welcomergeneral", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_welcomergeneral():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
channels = await get_guild_channels(guild_id)
_config = {
"channel": guild_info['w']['c'],
"embed": guild_info['w']['e'],
"badges": guild_info['w']['b'],
"invited": guild_info['w']['iv'],
"imagesenabled": guild_info['w']['i']['e'],
"textenabled": guild_info['w']['t']['e'],
"dmsenabled": guild_info['w']['dm']['e'],
"embedenabled": guild_info['w']['ue'],
"customembed": guild_info['w']['em'][1],
}
channellist = []
for channel in sorted(
channels['text'],
key=lambda o: o['position']):
channellist.append(f"{channel['name']} ({channel['id']})")
if guild_info['w']['c']:
_config['welcomerchannel'] = f"deleted-channel ({guild_info['w']['c']})"
results = list(filter(lambda o, id=guild_info['w']['c']: str(
o['id']) == str(id), channels['text']))
if len(results) == 1:
_config['welcomerchannel'] = f"{results[0]['name']} ({results[0]['id']})"
else:
_config['welcomerchannel'] = ""
return await render_template("dashboard/welcomergeneral.html", session=session, guild=guild, guilds=guilds, config=_config, channellist=channellist)
if request.method == "POST":
channels = await get_guild_channels(guild_id)
form = dict(await request.form)
try:
update_payload = {}
replaces = [
['w.b', form['badges'], True, "bool", "welcomer.badges"],
['w.iv', form['invited'], True, "bool", "welcomer.invited"],
['w.e', form['embed'], True, "bool", "welcomer.embed"],
['w.i.e', form['imagesenabled'], True,
"bool", "welcomer.imagesenabled"],
['w.t.e', form['textenabled'], True,
"bool", "welcomer.textenabled"],
['w.dm.e', form['dmsenabled'], True,
"bool", "welcomer.dmsenabled"],
['w.ue', form['embedenabled'], True,
"bool", "welcomer.embedenabled"]
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
value = re.findall(r".+ \(([0-9]+)\)", form['channel'])
if len(value) == 1:
value = value[0]
results = list(filter(lambda o, id=value: str(
o['id']) == str(id), channels['text']))
if len(results) == 1:
oldvalue = rockutils.getvalue("w.c", guild_info)
rockutils.setvalue("w.c", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"welcomer.channel", update_payload, [
oldvalue, value])
else:
value = None
oldvalue = rockutils.getvalue("w.c", guild_info)
rockutils.setvalue("w.c", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"welcomer.channel", update_payload, [
oldvalue, value])
value = form['customembed']
loader_type = None
try:
yaml.load(value, Loader=yaml.SafeLoader)
loader_type = "y"
except BaseException:
pass
try:
json.loads(value)
loader_type = "j"
except BaseException:
pass
if loader_type:
oldvalue = rockutils.getvalue("w.em", guild_info)[1]
rockutils.setvalue("w.em", guild_info, [loader_type, value])
if oldvalue != value:
rockutils.setvalue(
"welcomer.customembed", update_payload, None)
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/welcomerimages", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_welcomerimages():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
guild_donations = await get_guild_donations(guild_info)
if not guild_info:
return redirect("/dashboard?missingdata")
# welcomer channel
# welcomer badges
# welcomer invited
# welcomer images enable
# welcomer text enabled
# welcomer dm enabled
if request.method == "GET":
if isinstance(guild_info['w']['i']['m'], list):
guild_info['w']['i']['m'] = "\n".join(guild_info['w']['i']['m'])
_config = {
"donations": guild_donations,
"enableimages": guild_info['w']['i']['e'],
"textcolour": guild_info['w']['i']['c']['b'],
"textbordercolour": guild_info['w']['i']['c']['bo'],
"profileoutlinecolour": guild_info['w']['i']['c']['pb'],
"imagebordercolour": guild_info['w']['i']['c']['ib'],
"enableimageborder": guild_info['w']['i']['b'],
"textalign": guild_info['w']['i']['a'],
"texttheme": guild_info['w']['i']['t'],
"profilebordertype": guild_info['w']['i']['pb'],
"message": guild_info['w']['i']['m'],
"background": guild_info['w']['i']['bg'],
}
keys = ['textcolour', 'textbordercolour',
'profileoutlinecolour', 'imagebordercolour']
for key in keys:
if key in _config:
_config[key] = normalize_colour(_config[key])
backgrounds = list(map(lambda o: pathlib.Path(o).stem, os.listdir(
os.path.join(config['cdn']['location'], "Images"))))
return await render_template("dashboard/welcomerimages.html", session=session, guild=guild, guilds=guilds, config=_config, backgrounds=backgrounds)
if request.method == "POST":
files = await request.files
_file = files.get('file', None)
form = dict(await request.form)
try:
update_payload = {}
_allow_bg = False
if len(guild_donations) > 0:
_allow_bg = True
# if "cbg" in guild_donations:
# _allow_bg = True
# if "donation" in guild_donations:
# _allow_bg = True
# _allow_hq = True
# if "donation" in guild_donations:
# _allow_gif = True
if _file and _allow_bg:
location = os.path.join(
config['cdn']['location'],
"CustomImages",
f"custom_{guild['id']}")
isgif = imghdr.what(_file.filename, h=_file.read()) in [
"gif"]
_file.seek(0)
if os.path.exists(location + ".gif"):
os.remove(location + ".gif")
if os.path.exists(location + ".png"):
os.remove(location + ".png")
if os.path.exists(location + ".jpg"):
os.remove(location + ".jpg")
if isgif:
location += ".gif"
_file.save(location)
# image.save(location, "gif")
else:
location += ".png"
image = Image.open(_file)
image.save(location, "png")
# else:
# location += ".jpg"
# image = image.convert("RGB")
# image.save(location, "jpeg", quality=30,
# optimize=True, progressive=True)
form['background'] = f"custom_{guild['id']}"
replaces = [
# ['w.b', form['badges'], True, "bool", "badges"],
['w.i.e', form['enableimages'],
True, "bool", "welcomer.imagesenabled"],
['w.i.b', form['enableimageborder'], True,
"bool", "welcomerimg.enableimageborder"],
['w.i.a', form['textalign'],
False, None, "welcomerimg.textalign"],
['w.i.t', form['texttheme'], True,
"int", "welcomerimg.texttheme"],
['w.i.pb', form['profilebordertype'], True,
"int", "welcomerimg.profilebordertype"],
['w.i.m', form['message'],
False, None, "welcomerimg.message"],
['w.i.bg', form['background'],
False, None, "welcomerimg.background"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
replaces = [
['w.i.c.b', form['textcolour'], True,
"hex", "welcomerimg.textcolour"],
['w.i.c.bo', form['textbordercolour'], True,
"hex", "welcomerimg.textbordercolour"],
['w.i.c.pb', form['profileoutlinecolour'], True,
"hex", "welcomerimg.profileoutlinecolour"],
['w.i.c.ib', form['imagebordercolour'], True,
"hex", "welcomerimg.imagebordercolour"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = None
if "rgba" in replace[1]:
matches = re.findall(
r"rgba\((\d+),(\d+),(\d+),([\d\.?]+)\)", replace[1])
if len(matches) > 0:
rgba = matches[0]
_hex = ""
_hex += f"{str(hex(rgba[0]))[2:]}"
_hex += f"{str(hex(rgba[1]))[2:]}"
_hex += f"{str(hex(rgba[2]))[2:]}"
_hex += f"{str(hex(rgba[3]))[2:]}"
value = f"RGBA|{_hex}"
elif replace[1] == "transparent":
value = f"transparent"
else:
rgb = replace[1].replace("#", "")
try:
int(rgb, 16)
isrgb = True
except BaseException:
isrgb = False
if isrgb:
value = f"RGB|{rgb[:6]}"
if value:
oldvalue = rockutils.getvalue(
replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
keys = ['w.i.c.b', 'w.i.c.b', 'w.i.c.pb', 'w.i.c.ib']
for key in keys:
value = rockutils.getvalue(key, guild_info)
newvalue = normalize_colour(value)
rockutils.setvalue(key, guild_info, newvalue)
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/welcomertext", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_welcomertext():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
channels = await get_guild_channels(guild_id)
_config = {
"badges": guild_info['w']['b'],
"invited": guild_info['w']['iv'],
"textenabled": guild_info['w']['t']['e'],
"embedenabled": guild_info['w']['ue'],
"customembed": guild_info['w']['em'][1],
"message": guild_info['w']['t']['m'],
}
channellist = []
for channel in sorted(
channels['text'],
key=lambda o: o['position']):
channellist.append(f"{channel['name']} ({channel['id']})")
if guild_info['w']['c']:
_config['welcomerchannel'] = f"deleted-channel ({guild_info['w']['c']})"
results = list(filter(lambda o, id=guild_info['w']['c']: str(
o['id']) == str(id), channels['text']))
if len(results) == 1:
_config['welcomerchannel'] = f"{results[0]['name']} ({results[0]['id']})"
else:
_config['welcomerchannel'] = ""
return await render_template("dashboard/welcomertext.html", session=session, guild=guild, guilds=guilds, config=_config, channellist=channellist)
if request.method == "POST":
channels = await get_guild_channels(guild_id)
form = dict(await request.form)
try:
update_payload = {}
replaces = [
['w.b', form['badges'], True,
"bool", "welcomer.badges"],
['w.iv', form['invited'], True,
"bool", "welcomer.invited"],
['w.t.e', form['textenabled'], True,
"bool", "welcomer.textenabled"],
['w.ue', form['embedenabled'], True,
"bool", "welcomer.embedenabled"],
['w.t.m', form['message'], False,
None, "welcomer.message"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
value = form['customembed']
loader_type = None
try:
yaml.load(value, Loader=yaml.SafeLoader)
loader_type = "y"
except BaseException:
pass
try:
json.loads(value)
loader_type = "j"
except BaseException:
pass
if loader_type:
oldvalue = rockutils.getvalue("w.em", guild_info)[1]
rockutils.setvalue("w.em", guild_info, [loader_type, value])
if oldvalue != value:
rockutils.setvalue(
"welcomer.customembed", update_payload, None)
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/welcomerdms", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_welcomerdms():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
channels = await get_guild_channels(guild_id)
_config = {
"dmsenabled": guild_info['w']['dm']['e'],
"embedenabled": guild_info['w']['dm']['ue'],
"customembed": guild_info['w']['dm']['em'][1],
"message": guild_info['w']['dm']['m'],
}
channellist = []
for channel in sorted(
channels['text'],
key=lambda o: o['position']):
channellist.append(f"{channel['name']} ({channel['id']})")
if guild_info['w']['c']:
_config['welcomerchannel'] = f"deleted-channel ({guild_info['w']['c']})"
results = list(filter(lambda o, id=guild_info['w']['c']: str(
o['id']) == str(id), channels['text']))
if len(results) == 1:
_config['welcomerchannel'] = f"{results[0]['name']} ({results[0]['id']})"
else:
_config['welcomerchannel'] = ""
return await render_template("dashboard/welcomerdms.html", session=session, guild=guild, guilds=guilds, config=_config, channellist=channellist)
if request.method == "POST":
channels = await get_guild_channels(guild_id)
form = dict(await request.form)
try:
update_payload = {}
replaces = [
['w.dm.e', form['dmenabled'], True,
"bool", "welcomerdms.enabled"],
['w.dm.ue', form['embedenabled'], True,
"bool", "welcomerdms.embedenabled"],
['w.dm.m', form['message'], False,
None, "welcomerdms.message"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
value = form['customembed']
loader_type = None
try:
yaml.load(value, Loader=yaml.SafeLoader)
loader_type = "y"
except BaseException:
pass
try:
json.loads(value)
loader_type = "j"
except BaseException:
pass
if loader_type:
oldvalue = rockutils.getvalue("w.dm.em", guild_info)[1]
rockutils.setvalue("w.dm.em", guild_info, [loader_type, value])
if oldvalue != value:
rockutils.setvalue(
"welcomerdms.customembed", update_payload, None)
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/punishments", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_punishments():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
_config = {
"forcereason": guild_info['m']['fr'],
"logmoderation": guild_info['lo']['m']
}
hasfile = os.path.exists(f"punishments/{guild_id}.csv")
return await render_template("dashboard/punishmentmanage.html", session=session, guild=guild, guilds=guilds, config=_config, has_file=hasfile)
if request.method == "POST":
form = dict(await request.form)
try:
update_payload = {}
replaces = [
['m.fr', form['forcereason'], True,
"bool", "moderation.forcereason"],
['lo.m', form['logmoderation'], True,
"bool", "logging.logmoderation"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/punishments/<ptype>")
@ valid_oauth_required
# @valid_dash_user
async def dashboard_punishments_view(ptype="recent"):
res = await is_valid_dash_user()
if res != True:
return res
if ptype not in ['recent', 'active']:
ptype = "recent"
if ptype == "active":
isactive = True
ptype = "true"
else:
isactive = False
ptype = "false"
ptype = f"/api/punishments/{ptype}"
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
guild_donations = await get_guild_donations(guild_info)
if not guild_info:
return redirect("/dashboard?missingdata")
return await render_template("dashboard/punishmentview.html", session=session, guild=guild, guilds=guilds, config=guild_info, donations=guild_donations, ptype=ptype, isactive=isactive)
@ app.route("/dashboard/timerole", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_timerole():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
roles = await get_guild_roles(guild_id)
setroles = {}
for role in roles:
role['enabled'] = False
role['seconds'] = ""
setroles[role['id']] = role
for role in guild_info['tr']['r']:
if role[0] in setroles:
setroles[role[0]]['enabled'] = True
setroles[role[0]]['seconds'] = str(role[1])
for id, value in setroles.items():
try:
setroles[id]['seconds'] = math.floor(
int(setroles[id]['seconds']) / 60)
except BaseException:
pass
if guild_id in setroles:
del setroles[str(guild_id)]
if request.method == "GET":
_config = {
"enabled": guild_info['tr']['e'],
"roles": setroles,
}
return await render_template("dashboard/timerole.html", session=session, guild=guild, guilds=guilds, config=_config, roles=roles)
if request.method == "POST":
form = json.loads(list(await request.form)[0])
try:
update_payload = {}
replaces = [
['tr.e', form['enabled'], True, "bool", "timerole.enable"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
timeroles = []
for id, role in form['roles'].items():
if role[0]:
try:
seconds = int(math.floor(float(role[1])) * 60)
if seconds > 0:
timeroles.append([str(id), str(seconds)])
except BaseException:
pass
oldvalue = rockutils.getvalue("tr.r", guild_info)
rockutils.setvalue("tr.r", guild_info, timeroles)
if timeroles != oldvalue:
# log added roles
# log removed roles
# log edited roles
rockutils.setvalue("freerole.roles", update_payload, "")
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/autorole", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_autorole():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
roles = await get_guild_roles(guild_id)
setroles = {}
for role in roles:
role['enabled'] = False
setroles[role['id']] = role
for role in guild_info['ar']['r']:
if role in setroles:
setroles[role]['enabled'] = True
if guild_id in setroles:
del setroles[str(guild_id)]
if request.method == "GET":
_config = {
"enabled": guild_info['ar']['e'],
"roles": setroles
}
return await render_template("dashboard/autorole.html", session=session, guild=guild, guilds=guilds, config=_config, roles=roles)
if request.method == "POST":
form = json.loads(list(await request.form)[0])
try:
update_payload = {}
replaces = [
['ar.e', form['enabled'], True, "bool", "autorole.enable"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
autorole = []
for id, role in form['roles'].items():
if role:
autorole.append(id)
oldvalue = rockutils.getvalue("ar.r", guild_info)
rockutils.setvalue("ar.r", guild_info, autorole)
if autorole != oldvalue:
# log added roles
# log removed roles
# log edited roles
rockutils.setvalue("autorole.roles", update_payload, "")
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/freerole", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_freerole():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
roles = await get_guild_roles(guild_id)
setroles = {}
for role in roles:
role['enabled'] = False
setroles[role['id']] = role
for role in guild_info['fr']['r']:
if role[0] in setroles:
setroles[role[0]]['enabled'] = True
if guild_id in setroles:
del setroles[str(guild_id)]
if request.method == "GET":
_config = {
"enabled": guild_info['fr']['e'],
"roles": setroles
}
return await render_template("dashboard/freerole.html", session=session, guild=guild, guilds=guilds, config=_config, roles=roles)
if request.method == "POST":
form = json.loads(list(await request.form)[0])
try:
update_payload = {}
replaces = [
['fr.e', form['enabled'], True, "bool", "freerole.enable"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
freerole = []
for id, role in form['roles'].items():
if role:
freerole.append(id)
oldvalue = rockutils.getvalue("fr.r", guild_info)
rockutils.setvalue("fr.r", guild_info, freerole)
if freerole != oldvalue:
# log added roles
# log removed roles
# log edited roles
rockutils.setvalue("freerole.roles", update_payload, "")
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/logs", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_logs():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
_config = {
"enabled": guild_info['lo']['e'],
"audit": guild_info['lo']['a'],
"moderation": guild_info['lo']['m'],
"joinleaves": guild_info['lo']['jl'],
}
hasfile = os.path.exists(f"logs/{guild_id}.csv")
return await render_template("dashboard/logs.html", session=session, guild=guild, guilds=guilds, config=_config, has_file=hasfile)
if request.method == "POST":
form = dict(await request.form)
try:
update_payload = {}
replaces = [
['lo.e', form['enabled'], True, "bool", "logging.enabled"],
['lo.a', form['audit'], True, "bool", "logging.audit"],
['lo.m', form['moderation'], True, "bool", "logging.moderation"],
['lo.jl', form['joinleaves'], True, "bool", "logging.joinleaves"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if replace[1]:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
if len(update_payload) > 0:
await rockutils.logcsv(
[
math.floor(time.time()),
'CONFIG_CHANGE',
int(session.get("user_id", 0)),
session.get("user", ""),
json.dumps(update_payload)
],
f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/leaver", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_leaver():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
channels = await get_guild_channels(guild_id)
_config = {
"enabled": guild_info['l']['e'],
"message": guild_info['l']['t'],
"embed": guild_info['l']['em'],
}
channellist = []
for channel in sorted(
channels['text'],
key=lambda o: o['position']):
channellist.append(f"{channel['name']} ({channel['id']})")
if guild_info['l']['c']:
_config['channel'] = f"deleted-channel ({guild_info['l']['c']})"
results = list(filter(lambda o, id=guild_info['l']['c']: str(
o['id']) == str(id), channels['text']))
if len(results) == 1:
_config['channel'] = f"{results[0]['name']} ({results[0]['id']})"
else:
_config['channel'] = ""
return await render_template("dashboard/leaver.html", session=session, guild=guild, guilds=guilds, config=_config, channellist=channellist)
if request.method == "POST":
channels = await get_guild_channels(guild_id)
form = dict(await request.form)
try:
update_payload = {}
replaces = [
['l.e', form['enabled'], True, "bool", "leaver.enabled"],
['l.t', form['message'], False, None, "leaver.text"],
['l.em', form['embed'], True, "bool", "leaver.embed"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
value = re.findall(r".+ \(([0-9]+)\)", form['channel'])
if len(value) == 1:
value = value[0]
results = list(filter(lambda o, id=value: str(
o['id']) == str(id), channels['text']))
if len(results) == 1:
oldvalue = rockutils.getvalue("l.c", guild_info)
rockutils.setvalue("l.c", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"leaver.channel", update_payload, [
oldvalue, value])
else:
value = None
oldvalue = rockutils.getvalue("l.c", guild_info)
rockutils.setvalue("l.c", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"leaver.channel", update_payload, [
oldvalue, value])
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/staff", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_staff():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
_config = {
"allowping": guild_info['st']['ap'],
}
ids = [v[0] for v in guild_info['st']['u']]
_config['staffids'] = ",".join(ids)
result_payload = await create_job(request=None, o="guildstaff", a=int(guild_id), r="*", timeout=2)
staff = []
for data in result_payload['d'].values():
if data['success']:
stafflist = data['data']
staff = []
for _staff in stafflist:
_staff['preferdms'] = True
for userid, preferdms in guild_info['st']['u']:
if str(userid) == str(_staff['id']):
_staff['preferdms'] = preferdms
staff.append(_staff)
return await render_template("dashboard/staff.html", session=session, guild=guild, guilds=guilds, config=_config, staff=staff)
if request.method == "POST":
form = dict(await request.form)
try:
update_payload = {}
replaces = [
['st.ap', form['allowping'], True, "bool", "staff.allowping"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
ids = form['staffids'].split(",")
staffids = [str(v[0]) for v in guild_info['st']['u']]
added, removed = [], []
for id in ids:
if id not in staffids:
added.append(id)
for id in staffids:
if id not in ids:
removed.append(id)
stafflist = {}
for staff_id in ids:
stafflist[staff_id] = True
for staff_id, prefer_ping in guild_info['st']['u']:
if staff_id in ids:
stafflist[str(staff_id)] = prefer_ping
staff_list = []
for staff_id, prefer_ping in stafflist.items():
staff_list.append([
staff_id, prefer_ping
])
if len(added) + len(removed) > 0:
rockutils.setvalue("st.u", guild_info, staff_list)
rockutils.setvalue(
"staff.staff", update_payload, [
added, removed])
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/rules", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_rules():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
_config = {
"enabled": guild_info['r']['e'],
"rules": "\n".join(guild_info['r']['r']),
}
return await render_template("dashboard/rules.html", session=session, guild=guild, guilds=guilds, config=_config)
if request.method == "POST":
form = dict(await request.form)
try:
update_payload = {}
replaces = [
['r.e', form['enabled'], True, "bool", "rules.enabled"],
['r.r', form['rules'].split("\n"), False, None, "rules.rules"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/automod", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_automod():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
_config = {
"enabled": guild_info['am']['e'],
"smartmod": guild_info['am']['sm'],
"automodfiltinvites": guild_info['am']['g']['i'],
"automodfilturlredir": guild_info['am']['g']['ur'],
"automodfilturls": guild_info['am']['g']['ul'],
"automodfiltipgrab": guild_info['am']['g']['ig'],
"automodfiltmasscap": guild_info['am']['g']['mc'],
"automodfiltmassmen": guild_info['am']['g']['mm'],
"automodfiltprofan": guild_info['am']['g']['p'],
"automodfiltfilter": guild_info['am']['g']['f'],
"thresholdmention": guild_info['am']['t']['m'],
"thresholdcaps": guild_info['am']['t']['c'],
"filter": "\n".join(guild_info['am']['f']),
"regex": "\n".join(guild_info['am']['r']),
}
return await render_template("dashboard/automod.html", session=session, guild=guild, guilds=guilds, config=_config)
if request.method == "POST":
form = dict(await request.form)
try:
update_payload = {}
replaces = [
['am.e', form['enabled'], True, "bool", "automod.enabled"],
['am.sm', form['smartmod'], True, "bool", "automod.smartmod"],
['am.g.i', form['automodfiltinvites'], True,
"bool", "automod.automodfiltinvites"],
['am.g.ur', form['automodfilturlredir'], True,
"bool", "automod.automodfilturlredir"],
['am.g.ul', form['automodfilturls'], True,
"bool", "automod.automodfilturls"],
['am.g.ig', form['automodfiltipgrab'], True,
"bool", "automod.automodfiltipgrab"],
['am.g.mc', form['automodfiltmasscap'], True,
"bool", "automod.automodfiltmasscap"],
['am.g.mm', form['automodfiltmassmen'], True,
"bool", "automod.automodfiltmassmen"],
['am.g.p', form['automodfiltprofan'], True,
"bool", "automod.automodfiltprofan"],
['am.g.f', form['automodfiltfilter'], True,
"bool", "automod.automodfiltfilter"],
['am.t.m', form['thresholdmention'], True,
"int", "automod.thresholdmention"],
['am.t.c', form['thresholdcaps'], True,
"int", "automod.thresholdcaps"],
['am.f', form['filter'].split(
"\n"), False, None, "automod.filter"],
['am.r', form['regex'].split(
"\n"), False, None, "automod.regex"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/borderwall", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_borderwall():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
roles = await get_guild_roles(guild_id)
setroles = {}
for role in roles:
role['enabled'] = False
setroles[role['id']] = role
_roles = guild_info['bw']['r']
if not isinstance(_roles, list):
_roles = [_roles]
for role in _roles:
if role in setroles:
setroles[role]['enabled'] = True
if guild_id in setroles:
del setroles[str(guild_id)]
if request.method == "GET":
channels = await get_guild_channels(guild_id)
_config = {
"channel": guild_info['bw']['c'],
"enabled": guild_info['bw']['e'],
"senddms": guild_info['bw']['d'],
"waittime": guild_info['bw']['w'],
"message": guild_info['bw']['m'],
"messageverify": guild_info['bw']['mv'],
"roles": setroles
}
channellist = []
for channel in sorted(
channels['text'],
key=lambda o: o['position']):
channellist.append(f"{channel['name']} ({channel['id']})")
if guild_info['bw']['c']:
_config['channel'] = f"deleted-channel ({guild_info['bw']['c']})"
results = list(filter(lambda o, id=guild_info['bw']['c']: str(
o['id']) == str(id), channels['text']))
if len(results) == 1:
_config['channel'] = f"{results[0]['name']} ({results[0]['id']})"
else:
_config['channel'] = ""
return await render_template("dashboard/borderwall.html", session=session, guild=guild, guilds=guilds, config=_config, channellist=channellist, roles=roles)
if request.method == "POST":
channels = await get_guild_channels(guild_id)
form = json.loads(list(await request.form)[0])
try:
update_payload = {}
replaces = [
['bw.e', form['enabled'], True, "bool", "borderwall.enabled"],
['bw.d', form['senddms'], True, "bool", "borderwall.senddms"],
# ['bw.w', form['waittime'], True, "int", "borderwall.waittime"],
['bw.m', form['message'], False, None, "borderwall.message"],
['bw.mv', form['messageverify'], False,
None, "borderwall.messageverify"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
value = re.findall(r".+ \(([0-9]+)\)", form['channel'])
if len(value) == 1:
value = value[0]
results = list(filter(lambda o, id=value: str(
o['id']) == str(id), channels['text']))
if len(results) == 1:
oldvalue = rockutils.getvalue("bw.c", guild_info)
rockutils.setvalue("bw.c", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"borderwall.channel", update_payload, [
oldvalue, value])
else:
value = None
oldvalue = rockutils.getvalue("bw.c", guild_info)
rockutils.setvalue("bw.c", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"borderwall.channel", update_payload, [
oldvalue, value])
bwroles = []
for id, role in form['roles'].items():
if role:
bwroles.append(str(id))
oldvalue = rockutils.getvalue("bw.r", guild_info)
rockutils.setvalue("bw.r", guild_info, bwroles)
if bwroles != oldvalue:
# log added roles
# log removed roles
# log edited roles
rockutils.setvalue("borderwall.roles", update_payload, "")
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/tempchannel", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_tempchannel():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
channels = await get_guild_channels(guild_id)
_config = {
"enabled": guild_info['tc']['e'],
"category": guild_info['tc']['c'],
"lobby": guild_info['tc']['l'],
"defaultlimit": guild_info['tc']['dl'],
"autopurge": guild_info['tc']['ap']
}
categorylist = []
for channel in sorted(
channels['categories'],
key=lambda o: o['position']):
categorylist.append(f"{channel['name']} ({channel['id']})")
channellist = []
for channel in sorted(
channels['voice'],
key=lambda o: o['position']):
channellist.append(f"{channel['name']} ({channel['id']})")
if guild_info['tc']['c']:
_config['category'] = f"deleted-category ({guild_info['tc']['c']})"
results = list(filter(lambda o, id=guild_info['tc']['c']: str(
o['id']) == str(id), channels['categories']))
if len(results) == 1:
_config['category'] = f"{results[0]['name']} ({results[0]['id']})"
else:
_config['category'] = ""
if guild_info['tc']['l']:
_config['lobby'] = f"deleted-channel ({guild_info['tc']['l']})"
results = list(filter(lambda o, id=guild_info['tc']['l']: str(
o['id']) == str(id), channels['voice']))
if len(results) == 1:
_config['lobby'] = f"{results[0]['name']} ({results[0]['id']})"
else:
_config['lobby'] = ""
return await render_template("dashboard/tempchannel.html", session=session, guild=guild, guilds=guilds, config=_config, channellist=channellist, categorylist=categorylist)
if request.method == "POST":
channels = await get_guild_channels(guild_id)
# form = json.loads(list(await request.form)[0])
form = dict(await request.form)
try:
update_payload = {}
replaces = [
['tc.e', form['enabled'], True, "bool", "tempchannel.enabled"],
['tc.ap', form['autopurge'], False, None, "tempchannel.autopurge"],
['tc.dl', form['defaultlimit'], True,
"int", "tempchannel.defaultlimit"]
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
value = re.findall(r".+ \(([0-9]+)\)", form['category'])
if len(value) == 1:
value = value[0]
results = list(filter(lambda o, id=value: str(
o['id']) == str(id), channels['categories']))
if len(results) == 1:
oldvalue = rockutils.getvalue("tc.c", guild_info)
rockutils.setvalue("tc.c", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"tempchannel.category", update_payload, [
oldvalue, value])
else:
value = None
oldvalue = rockutils.getvalue("tc.c", guild_info)
rockutils.setvalue("tc.c", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"tempchannel.category", update_payload, [
oldvalue, value])
value = re.findall(r".+ \(([0-9]+)\)", form['lobby'])
if len(value) == 1:
value = value[0]
results = list(filter(lambda o, id=value: str(
o['id']) == str(id), channels['voice']))
if len(results) == 1:
oldvalue = rockutils.getvalue("tc.l", guild_info)
rockutils.setvalue("tc.l", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"tempchannel.lobby", update_payload, [
oldvalue, value])
else:
value = None
oldvalue = rockutils.getvalue("tc.l", guild_info)
rockutils.setvalue("tc.l", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"tempchannel.lobby", update_payload, [
oldvalue, value])
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
# @app.route("/dashboard/namepurge", methods=['GET', 'POST'])
# @valid_oauth_required
# # @valid_dash_user
# async def dashboard_namepurge():
# res = await is_valid_dash_user()
# if res != True:
# return res
# guild_id = session.get("dashboard_guild", None)
# guilds = list(sorted(session.get("guild_data", []),
# key=lambda o: o.get("name", "")))
# guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
# if not guild_id:
# return redirect("/dashboard")
# guild_info = await get_guild_info(guild_id)
# if not guild_info:
# return redirect("/dashboard?missingdata")
# if request.method == "GET":
# _config = {
# "enabled": guild_info['np']['e'],
# "ignore": guild_info['np']['i'],
# "filter": "\n".join(guild_info['np']['f']),
# }
# return await render_template("dashboard/namepurge.html", session=session, guild=guild, guilds=guilds, config=_config)
# if request.method == "POST":
# form = dict(await request.form)
# try:
# update_payload = {}
# replaces = [
# ['np.e', form['enabled'], True, "bool", "namepurge.enabled"],
# ['np.i', form['ignore'], True, "bool", "namepurge.ignorebot"],
# ['np.f', form['filter'].split(
# "\n"), False, None, "namepurge.filter"]
# ]
# for replace in replaces:
# if replace[2] and replace[3] and expect(
# replace[1], replace[3]) or not replace[2]:
# if not replace[1] is None:
# value = normalize_form(replace[1])
# oldvalue = rockutils.getvalue(replace[0], guild_info)
# rockutils.setvalue(replace[0], guild_info, value)
# if oldvalue != value:
# rockutils.setvalue(
# replace[4], update_payload, [oldvalue, value])
# if len(update_payload) > 0:
# await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
# await update_guild_info(guild_id, guild_info)
# await create_job(o="cachereload", a=guild_id, r="*")
# return jsonify(success=True)
# except Exception as e:
# exc_info = sys.exc_info()
# traceback.print_exception(*exc_info)
# return jsonify(success=False, error=str(e))
@ app.route("/dashboard/music", methods=['GET', 'POST'])
@ valid_oauth_required
# @valid_dash_user
async def dashboard_music():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
_config = {
"djsenabled": guild_info['mu']['d']['e'],
"djs": ",".join(guild_info['mu']['d']['l']),
"skiptype": guild_info['mu']['st'],
"threshold": guild_info['mu']['t'],
}
return await render_template("dashboard/music.html", session=session, guild=guild, guilds=guilds, config=_config)
if request.method == "POST":
form = dict(await request.form)
try:
update_payload = {}
replaces = [
['mu.d.e', form['djsenabled'], True, "bool", "music.djsenabled"],
['mu.st', form['skiptype'], True, "int", "music.skiptype"],
['mu.t', form['threshold'], True, "int", "music.threshold"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
ids = form['djs'].split(",")
djids = guild_info['mu']['d']['l']
added, removed = [], []
for id in ids:
if id not in djids:
added.append(id)
for id in djids:
if id not in ids:
removed.append(id)
if len(added) + len(removed) > 0:
rockutils.setvalue("mu.d.l", guild_info, ids)
rockutils.setvalue(
"music.djslist", update_payload, [
added, removed])
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
@ app.route("/dashboard/serverstats/list")
@ valid_oauth_required
# @valid_dash_user
async def dashboard_serverstats_list():
res = await is_valid_dash_user()
if res != True:
return res
try:
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
return jsonify({"success": True, "config": guild_info['s']['c']})
except Exception as e:
return jsonify({"success": False, "error": str(e)})
@ app.route("/dashboard/serverstats", methods=['GET', 'POST'])
@ valid_oauth_required
async def dashboard_serverstats():
res = await is_valid_dash_user()
if res != True:
return res
guild_id = session.get("dashboard_guild", None)
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild = list(filter(lambda o, id=guild_id: o['id'] == guild_id, guilds))[0]
if not guild_id:
return redirect("/dashboard")
guild_info = await get_guild_info(guild_id)
if not guild_info:
return redirect("/dashboard?missingdata")
if request.method == "GET":
channels = await get_guild_channels(guild_id)
_config = {
"enabled": guild_info['s']['e'],
"category": guild_info['s']['ca'],
"channels": channels['categories'],
}
categorylist = []
for channel in sorted(
_config['channels'],
key=lambda o: o['position']):
categorylist.append(f"{channel['name']} ({channel['id']})")
if guild_info['s']['ca']:
_config['category'] = f"deleted-category ({guild_info['s']['ca']})"
results = list(filter(lambda o, id=guild_info['s']['ca']: str(
o['id']) == str(id), channels['categories']))
if len(results) == 1:
_config['category'] = f"{results[0]['name']} ({results[0]['id']})"
else:
_config['category'] = ""
return await render_template("dashboard/serverstats.html", session=session, guild=guild, guilds=guilds, config=_config, categorylist=categorylist)
if request.method == "POST":
channels = await get_guild_channels(guild_id)
form = json.loads(list(await request.form)[0])
try:
update_payload = {}
replaces = [
['s.e', form['enabled'], True, "bool", "serverstats.enabled"],
]
for replace in replaces:
if replace[2] and replace[3] and expect(
replace[1], replace[3]) or not replace[2]:
if not replace[1] is None:
value = normalize_form(replace[1])
oldvalue = rockutils.getvalue(replace[0], guild_info)
rockutils.setvalue(replace[0], guild_info, value)
if oldvalue != value:
rockutils.setvalue(
replace[4], update_payload, [oldvalue, value])
value = re.findall(r".+ \(([0-9]+)\)", form['category'])
if len(value) == 1:
value = value[0]
results = list(filter(lambda o, id=value: str(
o['id']) == str(id), channels['categories']))
if len(results) == 1:
oldvalue = rockutils.getvalue("s.ca", guild_info)
rockutils.setvalue("s.ca", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"serverstats.category", update_payload, [
oldvalue, value])
else:
value = None
oldvalue = rockutils.getvalue("s.ca", guild_info)
rockutils.setvalue("s.ca", guild_info, value)
if oldvalue != value:
rockutils.setvalue(
"serverstats.category", update_payload, [
oldvalue, value])
if len(update_payload) > 0:
await rockutils.logcsv([math.floor(time.time()), 'CONFIG_CHANGE', int(session.get("user_id", 0)), session.get("user", ""), json.dumps(update_payload)], f"{guild_id}.csv")
await update_guild_info(guild_id, guild_info)
await create_job(o="cachereload", a=guild_id, r="*")
return jsonify(success=True)
except Exception as e:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
return jsonify(success=False, error=str(e))
# /dashboard/serverstats
# configured stats
# /dashboard/analytics
# enabled
# analytics listing
# change by (5 minute, 30 minute, 1 hour, 6 hour, 12 hour, 1 day, 1 week, 1 month)
# members joined
# members left
# member count
# messages sent
# bot count
# user count
# reset
# export
# ????
# /dashboard/xp
# enabled
# reset
# (? may have xprole on the xp page or have it as a tab and have Manage and XPRole)
# /dashboard/xprole
# enabled
# roles (toggle then xp minimum)
# (? maybe a list saying how many users will have it)
# /formatting
# /customembeds
# /dashboard/logs/view
# /dashboard/api/xp/leaderboard
# /dashboard/api/xp/resetuser/<user id>
# /dashboard/api/xp/export
# /dashboard/api/xp/reset
# /profile
# /invite/<name>
# /guild/<id>
##########################################################################
async def post_no_wait(url, *args, **kwargs):
timeout = aiohttp.ClientTimeout(total=1)
try:
async with aiohttp.ClientSession(timeout=timeout) as session:
await session.post(
url,
*args,
**kwargs
)
await session.close()
except Exception as e:
print(e)
pass
@ app.route("/")
async def index():
guilds = sum(v.get('guilds', 0) for v in cluster_data.values())
members = sum(v.get('totalmembers', 0) for v in cluster_data.values())
_time = time.time()
global _lastpost
if _time - _lastpost >= 240:
tasks = [
post_no_wait(
"https://bots.ondiscord.xyz/bot-api/bots/330416853971107840/guilds",
headers={
"Authorization": "[removed]",
},
data={
"guildCount": guilds
}),
post_no_wait(
"https://api.discordextremelist.xyz/v1/bot/330416853971107840",
headers={
"Authorization": "[removed]"},
data={
"guildCount": guilds,
}),
post_no_wait(
"https://discordbots.org/api/bots/330416853971107840/stats",
headers={
"Authorization": "[removed]"},
data={
"server_count": guilds,
"shard_count": 50,
}),
post_no_wait(
"https://discord.boats/api/v2/bot/330416853971107840",
headers={
"Authorization": "[removed]",
},
data={
"server_count": guilds
}),
post_no_wait(
"https://botsfordiscord.com/api/bot/330416853971107840",
headers={
"Authorization": "[removed]"
},
data={
"server_count": guilds
}),
post_no_wait(
"https://discordsbestbots.xyz/api/bots/330416853971107840/stats",
headers={
"Authorization": "[removed]"
},
data={
"guilds": guilds
})
]
await asyncio.gather(*tasks)
_lastpost = _time
cdnpath = os.path.join(config['cdn']['location'], "Output")
total_images = len(os.listdir(cdnpath))
return await render_template("index.html", session=session, guild_count=guilds, member_count=members, stored_images=total_images)
@ app.route("/command-documentation")
async def command_documentation():
try:
with open("cfg/command-documentation.yaml", 'r') as stream:
data_loaded = yaml.load(stream, Loader=yaml.BaseLoader)
loaded = True
except BaseException:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
data_loaded = {}
loaded = False
return await render_template("command-documentation.html", session=session, loaded=loaded, docs=data_loaded)
@ app.route("/documentation")
async def documentation():
try:
with open("cfg/documentation.yaml", 'r') as stream:
data_loaded = yaml.load(stream, Loader=yaml.BaseLoader)
loaded = True
except BaseException:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
data_loaded = {}
loaded = False
return await render_template("documentation.html", session=session, loaded=loaded, docs=data_loaded)
@ app.route("/formatting")
async def formatting():
markdown_docs = {
"users": {
"user": "Alias of user.name",
"user.mention": "User mention",
"user.name": "The users name",
"user.discriminator": "The users discriminator tag",
"user.id": "The users id",
"user.avatar": "Url of users avatar",
"user.created.timestamp": "Timestamp for when the users account was created",
"user.created.since": "String for how long a user has been on discord",
"user.joined.timestamp": "Timestamp of how long a user has been on the server",
"user.joined.since": "String for how long a user has been on the server",
},
"server": {
"members": "Alias of server.members",
"server": "Alias of server.name",
"server.name": "The servers name",
"server.id": "The servers id",
"server.members": "Number of users and prefix of users on server",
"server.member.count": "Number of users who are on the server",
"server.member.prefix": "Count prefix for server.member.count",
"server.icon": "Url for the server icon",
"server.created.timestamp": "Timestamp for when server was created",
"server.created.since": "Stringh for how long the server has existed for",
"server.splash": "Url of splash the server has (if there is one)",
"server.shard_id": "Shard Id that the server is on",
},
"invite": {
"invite.code": "Code that the invite has been assigned to",
"invite.inviter": "Name of user who created the invite",
"invite.inviter.id": "Id of user who created the invite",
"invite.uses": "How many people have used the invite",
"invite.temporary": "Boolean that specifies if the invite is temporary",
"invite.created.timestamp": "Timestamp for when it was created",
"invite.created.since": "String for how long it has been since the invite was made",
"invite.max": "Max invites for an invite. Will return 0 if it is unlimited"
}
}
return await render_template("formatting.html", session=session, markdown_docs=markdown_docs)
@ app.route("/customembeds")
async def customembeds():
return await render_template("customembeds.html", session=session)
@ app.route("/status")
async def status():
_time = time.time()
clusters = {}
for i in list(["debug", "donator", "b"] + list(range(config['bot']['clusters']))):
clusters[str(i)] = {
"alive": False,
"pingalive": False,
"stats": {},
"lastping": 0
}
for cluster, ping in last_ping.items():
cluster = str(cluster)
clusters[cluster]['alive'] = True
if _time - ping < 70:
clusters[cluster]['pingalive'] = True
clusters[cluster]['lastping'] = _time - ping
for cluster, data in cluster_data.items():
cluster = str(cluster)
clusters[cluster]['stats'] = data
if clusters[cluster]['stats'].get('highest_latency'):
clusters[cluster]['stats']['highest_latency'] = max(
list(map(lambda o: o[1], data['latencies'])))
else:
clusters[cluster]['stats']['highest_latency'] = 0
clusters = list(sorted(clusters.items(), key=lambda o: str(o[0])))
online = list(
sorted(
filter(
lambda o: o[1]['alive'] and o[1]['pingalive'],
clusters),
key=lambda o: str(
o[0])))
degrade = list(
sorted(
filter(
lambda o: o[1]['alive'] and not o[1]['pingalive'],
clusters),
key=lambda o: str(
o[0])))
offline = list(
sorted(
filter(
lambda o: not o[1]['alive'],
clusters),
key=lambda o: str(
o[0])))
clusters = list(online + degrade + offline)
clusters = dict(
zip(map(lambda o: o[0], clusters), map(lambda o: o[1], clusters)))
return await render_template("status.html", session=session, clusters=clusters, botconfig=config['bot'])
@ app.route("/search")
async def search():
return await render_template("search.html", session=session)
@ app.route("/searchemojis")
async def searchemoji():
return await render_template("searchemojis.html", session=session)
@ app.route("/guild/<id>")
@ app.route("/g/<id>")
async def guild(id):
is_guild = False
staff = []
guild_donations = []
if id.isnumeric():
guild_info = await get_guild_info(id)
if guild_info:
is_guild = True
if rockutils.hasvalue("d.b.sw", guild_info) and not guild_info['d']['b'].get('sw', False):
return abort(403)
if is_guild:
result_payload = await create_job(request=None, o="guildstaff", a=int(id), r="*", timeout=1)
guild_donations = await get_guild_donations(guild_info)
for data in result_payload['d'].values():
if data['success']:
staff = data['data']
return await render_template("guild.html", session=session, valid_guild=is_guild, id=id, guildinfo=guild_info, donations=guild_donations, staff=staff)
@ app.route("/invite/<id>")
@ app.route("/i/<id>")
async def invite(id):
invite_id = id
# temporary
vanity = {
"biffa": 136759842948907008,
"welcomer": 341685098468343822,
"lust": 440255430271434763
}
if invite_id in vanity:
id = vanity[invite_id]
guild_info = await get_guild_info(id)
return await render_template("invite.html", session=session, id=invite_id, guild_id=id, guild_info=guild_info)
@ app.route("/borderwall")
@ app.route("/borderwall/<id>")
@ valid_oauth_required
async def borderwall(id=""):
error = ""
# borderwall_details = r.table("borderwall").get(id).run(rethink) or {}
borderwall_details = await get_value(connection, "borderwall", id, default={})
if borderwall_details:
if borderwall_details['a']:
valid_borderwall = False
error = '<div class="success success-fill" role="info"><i class="mdi mdi-check"></i> This borderwall id has already been validated </div>'
else:
valid_borderwall = True
else:
valid_borderwall = False
error = '<div class="primary primary-fill" role="info">The borderwall id specified is not valid </div>'
ip = "Unknown"
for _h in ['CF-Connecting-IP', 'CF_CONNECTING_IP', 'X_FORWARDED_FOR', 'REMOTE_ADDR']:
_ip = request.headers.get(_h, False)
if _ip:
ip = _ip
break
return await render_template("borderwall.html", headers=request.headers, session=session, data=borderwall_details, borderwall_id=id, ip=ip, error=error, show_bw=valid_borderwall)
@ app.route("/borderwall/<id>/authorize", methods=['POST', 'GET'])
@ valid_oauth_required
async def borderwall_authorize(id):
form = dict(await request.form)
token = form.get("token", False)
# borderwall_details = r.table("borderwall").get(id).run(rethink)
borderwall_details = await get_value(connection, "borderwall", id)
if not token:
return jsonify(success=False, error="Invalid token given")
if not borderwall_details:
return jsonify(success=False, error="Invalid borderwall code given")
user_id = session.get('user_id')
if not user_id:
return jsonify(
success=False,
error="An error occured. Log out and log back in"
)
else:
if str(user_id) != str(borderwall_details.get("ui", "")):
return jsonify(
success=False,
error="You are authorized on a different users account. Please log out"
)
data = {
"secret": config['keys']['recaptcha-server'],
"response": token
}
ip = "Unknown"
for _h in ['CF-Connecting-IP', 'CF_CONNECTING_IP', 'X_FORWARDED_FOR', 'REMOTE_ADDR']:
_ip = request.headers.get(_h, False)
if _ip:
data['remoteip'] = _ip
ip = _ip
break
if ip != "Unknown":
user_id = session.get('user_id')
if user_id:
user_info = await get_user_info(str(user_id))
if user_info:
if "ip" not in user_info:
user_info['ip'] = []
user_info['ip'].append(ip)
# r.table("users").get(str(user_id)).update(
# user_info).run(rethink)
await set_value(connection, "users", str(user_id), user_info)
async with aiohttp.ClientSession() as _session:
async with _session.post("https://www.google.com/recaptcha/api/siteverify", data=data) as res:
gpayload = await res.json()
getipintelcheck = False
if gpayload['success']:
if getipintelcheck and ip != "Unknown":
url = f"http://check.getipintel.net/check.php?ip={ip}&contact=[removed]&oflags=b&format=json"
async with _session.post(url) as res:
ipayload = await res.json()
if ipayload['status'] == "success":
if ipayload['BadIP'] == 1:
pass
return jsonify(
success=False,
error="Your IP score was too low to verify. Please disable a VPN or Proxy if you are using one.")
if gpayload.get('score', 1) > 0.5:
borderwall_details['a'] = True
borderwall_details['ip'] = ip
# r.table("borderwall").get(id).update(
# borderwall_details).run(rethink)
await set_value(connection, "borderwall", id, borderwall_details)
await create_job(o="borderwallverify", a=[borderwall_details['gi'], borderwall_details['ui'], id], r="*")
return jsonify(success=True)
else:
return jsonify(
success=False,
error="Your IP score was too low to verify. Please disable a VPN or Proxy if you are using one.")
return jsonify(success=False, error="Recaptcha failed")
return jsonify(success=True)
@ app.route("/invitebot")
@ app.route("/invitebot/<btype>")
async def invitebot(btype="bot"):
if btype == "bot":
id = config['ids']['main']
elif btype == "beta":
id = config['ids']['debug']
elif btype == "donator":
id = config['ids']['donator']
elif btype == "fallback":
id = config['ids']['bcomer']
else:
return redirect("/")
return redirect(
f"https://discordapp.com/oauth2/authorize?client_id={id}&scope=bot&permissions=8")
@ app.route("/backgrounds")
async def backgrounds():
path = os.path.join(config['cdn']['location'], "Images")
backgrounds = sorted(os.listdir(path))
return await render_template("backgrounds.html", session=session, backgrounds=backgrounds, background_count=len(backgrounds))
@ app.route("/donate")
async def donate():
error = ""
_args = list(dict(request.args).keys())
# error = '<div class="alert alert-fill-danger" role="info"><i class="mdi mdi-do-not-disturb"></i> Paypal donations are temporarily disabled. Please use patreon instead. You may remove your pledge once you start to still receive the rewards. Please make sure to bind your discord account to patreon.</div>'
if len(_args) == 1:
arg = _args[0]
if arg == "disabled":
error = '<div class="alert alert-fill-danger" role="info"><i class="mdi mdi-do-not-disturb"></i> Paypal donations are temporarily disabled. Please use patreon instead. You may remove your pledge once you start to still receive the rewards. Please make sure to bind your discord account to patreon.</div>'
if arg == "invaliddonation":
error = '<div class="alert alert-fill" role="info"><i class="mdi mdi-do-not-disturb"></i> An invalid donation type was specified in your request. If you have changed the donation url manually, change it back. </div>'
if arg == "paymentcreateerror":
error = '<div class="alert alert-fill-alert" role="alert"><i class="mdi mdi-do-not-disturb"></i> We were unable to create a payment for you to be able to use. Please try again. </div>'
if arg == "userinfogone":
error = '<div class="alert alert-fill-alert" role="alert"><i class="mdi mdi-do-not-disturb"></i> We were unable to retrieve your user information. Please try again. </div>'
if arg == "invalidpaymentid":
error = '<div class="alert alert-fill" role="info"><i class="mdi mdi-do-not-disturb"></i> Your request has returned an invalid payment id. Please attempt this again. Please note you have not been charged. </div>'
if arg == "invalidprice":
error = '<div class="alert alert-fill" role="info"><i class="mdi mdi-do-not-disturb"></i> Invalid price was specified in your request. If you have changed the donation url manually, change it back. </div>'
if arg == "invalidmonth":
error = '<div class="alert alert-fill" role="info"><i class="mdi mdi-do-not-disturb"></i> Invalid month was specified in your request. If you have changed the donation url manually, change it back. </div>'
if arg == "invalidarg":
error = '<div class="alert alert-fill-alert" role="alert"><i class="mdi mdi-do-not-disturb"></i> Your request is missing arguments. If you have changed the donation url manually, change it back. </div>'
if arg == "fatalexception":
error = '<div class="alert alert-fill-danger" role="danger"><i class="mdi mdi-do-not-disturb"></i> There was a problem assigning your donation role. Please visit the support server to fix this immediately as the payment has been processed </div>'
if arg == "success":
error = '<div class="alert alert-fill-success" role="alert"><i class="mdi mdi-check"></i> Thank you for donating! Your donation has gone through and been processed automatically. If you have not blocked your direct messages, you should receive a message from the bot and it should show on the support server under #donations </div>'
if blackfriday:
return await render_template("donate-blackfriday.html", session=session, error=error)
return await render_template("donate.html", session=session, error=error)
@ app.route("/dashboard")
@ valid_oauth_required
async def dashboard():
error = ""
errortype = 0
_args = list(dict(request.args).keys())
if len(_args) == 1:
arg = _args[0]
if arg == "missingpermission":
error = '<div class="alert alert-fill-danger" role="alert"><i class="mdi mdi-do-not-disturb"></i> You do not have permission to view the dashboard of this server </div>'
errortype = 1
elif arg == "invalidguild":
error = '<div class="alert alert-fill-danger" role="alert"><i class="mdi mdi-alert-circle"></i> The selected guild could not be found </div>'
errortype = 2
elif arg == "missingdata":
error = '<div class="alert alert-fill-danger" role="alert"><i class="mdi mdi-database-remove"></i> Could not locate any data for this guild. <b>Please run a command on the server</b> </div>'
errortype = 3
guilddata = None
if isinstance(session.get("guild_data", []), list):
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
else:
guilds = []
guild_id = session.get("dashboard_guild", 0)
for item in guilds:
if str(item.get("id")) == str(guild_id):
guilddata = item
if guilddata:
guildinfo = await get_guild_info(guild_id)
else:
guildinfo = {}
# return jsonify(guilds, guild_id, guilddata, guildinfo)
return await render_template("dashboard/guilddetails.html", session=session, error=error, errortype=errortype, guilds=guilds, guild=guilddata, guildinfo=guildinfo)
@ app.route("/dashboard/changeguild/<id>")
@ valid_oauth_required
async def change_dashboard_guild(id):
guilds = list(sorted(session.get("guild_data", []),
key=lambda o: o.get("name", "")))
guild_id = id
guilddata = None
for item in guilds:
if str(item.get("id")) == str(guild_id):
guilddata = item
if guilddata:
if await has_elevation(guild_id, session.get("user_id"), guild_info=None, bot_type="main"):
session['dashboard_guild'] = id
return redirect("/dashboard")
return redirect("/dashboard?missingpermission")
else:
return redirect("/dashboard?invalidguild")
@ app.route("/errors/<id>", methods=['GET', 'POST'])
async def error_view(id):
# error = r.table("errors").get(id).run(rethink) or {}
error = await get_value(connection, "errors", id, default={})
if request.method == "POST":
session['previous_path'] = request.path
if session.get("oauth2_token") is None:
return redirect("/login")
should_check = False
if sum(
1 if not session.get(c) else 0 for c in [
'user_id',
'user_data',
'guild_data',
'oauth2_check']) > 0:
should_check = True
if session.get("oauth2_check") is None or time.time() - \
session.get("oauth2_check") > 604800:
should_check = True
if should_check:
return redirect("/login")
_config = rockutils.load_json("cfg/config.json")
user_id = int(session['user_id'])
elevated = False
if user_id in _config['roles']['support']:
elevated = True
if user_id in _config['roles']['developer']:
elevated = True
if user_id in _config['roles']['admins']:
elevated = True
if user_id in _config['roles']['trusted']:
elevated = True
if elevated and error != {}:
if error['status'] == "not handled":
error['status'] = "handled"
else:
error['status'] = "not handled"
# r.table("errors").get(id).update(error).run(rethink)
await set_value(connection, "errors", id, error)
return await render_template("command_error.html", error=error)
@ app.route("/errors")
async def error_list():
# _config = rockutils.load_json("cfg/config.json")
# user_id = int(session['user_id'])
# elevated = False
# if user_id in _config['roles']['support']:
# elevated = True
# if user_id in _config['roles']['developer']:
# elevated = True
# if user_id in _config['roles']['admins']:
# elevated = True
# if user_id in _config['roles']['trusted']:
# elevated = True
# if not elevated:
# return "", 401
results = []
# values = r.table("errors").run(rethink)
async with connection.acquire() as pconnection:
vals = pconnection.fetch("SELECT * FROM errors")
for val in vals:
results.append(json.loads(val["value"]))
# while True:
# try:
# _val = values.next()
# results.append(_val)
# except Exception:
# break
not_handled = list(filter(lambda o: o['status'] == "not handled", results))
handled = list(filter(lambda o: o['status'] == "handled", results))
return await render_template("command_error_list.html", not_handled=not_handled, handled=handled)
app.run(host="0.0.0.0", port=config['ipc']['port'],
use_reloader=False, loop=asyncio.get_event_loop())
# :comfy:
| []
| []
| [
"OAUTHLIB_INSECURE_TRANSPORT"
]
| [] | ["OAUTHLIB_INSECURE_TRANSPORT"] | python | 1 | 0 | |
clients/google-api-services-container/v1beta1/1.31.0/com/google/api/services/container/v1beta1/Container.java | /*
* 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 code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.container.v1beta1;
/**
* Service definition for Container (v1beta1).
*
* <p>
* Builds and manages container-based applications, powered by the open source Kubernetes technology.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://cloud.google.com/container-engine/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link ContainerRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class Container extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
(com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 32 ||
(com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION == 31 &&
com.google.api.client.googleapis.GoogleUtils.BUGFIX_VERSION >= 1)),
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.31.1 of google-api-client to run version " +
"1.32.1 of the Kubernetes Engine API library.", com.google.api.client.googleapis.GoogleUtils.VERSION);
}
/**
* The default encoded root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_ROOT_URL = "https://container.googleapis.com/";
/**
* The default encoded mTLS root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.31
*/
public static final String DEFAULT_MTLS_ROOT_URL = "https://container.mtls.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Container(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
this(new Builder(transport, jsonFactory, httpRequestInitializer));
}
/**
* @param builder builder
*/
Container(Builder builder) {
super(builder);
}
@Override
protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException {
super.initialize(httpClientRequest);
}
/**
* An accessor for creating requests from the Projects collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.Projects.List request = container.projects().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Projects projects() {
return new Projects();
}
/**
* The "projects" collection of methods.
*/
public class Projects {
/**
* An accessor for creating requests from the Aggregated collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.Aggregated.List request = container.aggregated().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Aggregated aggregated() {
return new Aggregated();
}
/**
* The "aggregated" collection of methods.
*/
public class Aggregated {
/**
* An accessor for creating requests from the UsableSubnetworks collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.UsableSubnetworks.List request = container.usableSubnetworks().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public UsableSubnetworks usableSubnetworks() {
return new UsableSubnetworks();
}
/**
* The "usableSubnetworks" collection of methods.
*/
public class UsableSubnetworks {
/**
* Lists subnetworks that can be used for creating clusters in a project.
*
* Create a request for the method "usableSubnetworks.list".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param parent Required. The parent project where subnetworks are usable. Specified in the format `projects`.
* @return the request
*/
public List list(java.lang.String parent) throws java.io.IOException {
List result = new List(parent);
initialize(result);
return result;
}
public class List extends ContainerRequest<com.google.api.services.container.v1beta1.model.ListUsableSubnetworksResponse> {
private static final String REST_PATH = "v1beta1/{+parent}/aggregated/usableSubnetworks";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+$");
/**
* Lists subnetworks that can be used for creating clusters in a project.
*
* Create a request for the method "usableSubnetworks.list".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p>
* {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param parent Required. The parent project where subnetworks are usable. Specified in the format `projects`.
* @since 1.13
*/
protected List(java.lang.String parent) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.ListUsableSubnetworksResponse.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. The parent project where subnetworks are usable. Specified in the format
* `projects`.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** Required. The parent project where subnetworks are usable. Specified in the format `projects`.
*/
public java.lang.String getParent() {
return parent;
}
/**
* Required. The parent project where subnetworks are usable. Specified in the format
* `projects`.
*/
public List setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
this.parent = parent;
return this;
}
/**
* Filtering currently only supports equality on the networkProjectId and must be in the
* form: "networkProjectId=[PROJECTID]", where `networkProjectId` is the project which
* owns the listed subnetworks. This defaults to the parent project ID.
*/
@com.google.api.client.util.Key
private java.lang.String filter;
/** Filtering currently only supports equality on the networkProjectId and must be in the form:
"networkProjectId=[PROJECTID]", where `networkProjectId` is the project which owns the listed
subnetworks. This defaults to the parent project ID.
*/
public java.lang.String getFilter() {
return filter;
}
/**
* Filtering currently only supports equality on the networkProjectId and must be in the
* form: "networkProjectId=[PROJECTID]", where `networkProjectId` is the project which
* owns the listed subnetworks. This defaults to the parent project ID.
*/
public List setFilter(java.lang.String filter) {
this.filter = filter;
return this;
}
/**
* The max number of results per page that should be returned. If the number of available
* results is larger than `page_size`, a `next_page_token` is returned which can be used
* to get the next page of results in subsequent requests. Acceptable values are 0 to 500,
* inclusive. (Default: 500)
*/
@com.google.api.client.util.Key
private java.lang.Integer pageSize;
/** The max number of results per page that should be returned. If the number of available results is
larger than `page_size`, a `next_page_token` is returned which can be used to get the next page of
results in subsequent requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
*/
public java.lang.Integer getPageSize() {
return pageSize;
}
/**
* The max number of results per page that should be returned. If the number of available
* results is larger than `page_size`, a `next_page_token` is returned which can be used
* to get the next page of results in subsequent requests. Acceptable values are 0 to 500,
* inclusive. (Default: 500)
*/
public List setPageSize(java.lang.Integer pageSize) {
this.pageSize = pageSize;
return this;
}
/**
* Specifies a page token to use. Set this to the nextPageToken returned by previous list
* requests to get the next page of results.
*/
@com.google.api.client.util.Key
private java.lang.String pageToken;
/** Specifies a page token to use. Set this to the nextPageToken returned by previous list requests to
get the next page of results.
*/
public java.lang.String getPageToken() {
return pageToken;
}
/**
* Specifies a page token to use. Set this to the nextPageToken returned by previous list
* requests to get the next page of results.
*/
public List setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
}
}
/**
* An accessor for creating requests from the Locations collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.Locations.List request = container.locations().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Locations locations() {
return new Locations();
}
/**
* The "locations" collection of methods.
*/
public class Locations {
/**
* Returns configuration info about the Google Kubernetes Engine service.
*
* Create a request for the method "locations.getServerConfig".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link GetServerConfig#execute()} method to invoke the remote operation.
*
* @param name The name (project and location) of the server config to get, specified in the format
* `projects/locations`.
* @return the request
*/
public GetServerConfig getServerConfig(java.lang.String name) throws java.io.IOException {
GetServerConfig result = new GetServerConfig(name);
initialize(result);
return result;
}
public class GetServerConfig extends ContainerRequest<com.google.api.services.container.v1beta1.model.ServerConfig> {
private static final String REST_PATH = "v1beta1/{+name}/serverConfig";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$");
/**
* Returns configuration info about the Google Kubernetes Engine service.
*
* Create a request for the method "locations.getServerConfig".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link GetServerConfig#execute()} method to invoke the remote
* operation. <p> {@link GetServerConfig#initialize(com.google.api.client.googleapis.services.Abst
* ractGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param name The name (project and location) of the server config to get, specified in the format
* `projects/locations`.
* @since 1.13
*/
protected GetServerConfig(java.lang.String name) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.ServerConfig.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public GetServerConfig set$Xgafv(java.lang.String $Xgafv) {
return (GetServerConfig) super.set$Xgafv($Xgafv);
}
@Override
public GetServerConfig setAccessToken(java.lang.String accessToken) {
return (GetServerConfig) super.setAccessToken(accessToken);
}
@Override
public GetServerConfig setAlt(java.lang.String alt) {
return (GetServerConfig) super.setAlt(alt);
}
@Override
public GetServerConfig setCallback(java.lang.String callback) {
return (GetServerConfig) super.setCallback(callback);
}
@Override
public GetServerConfig setFields(java.lang.String fields) {
return (GetServerConfig) super.setFields(fields);
}
@Override
public GetServerConfig setKey(java.lang.String key) {
return (GetServerConfig) super.setKey(key);
}
@Override
public GetServerConfig setOauthToken(java.lang.String oauthToken) {
return (GetServerConfig) super.setOauthToken(oauthToken);
}
@Override
public GetServerConfig setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetServerConfig) super.setPrettyPrint(prettyPrint);
}
@Override
public GetServerConfig setQuotaUser(java.lang.String quotaUser) {
return (GetServerConfig) super.setQuotaUser(quotaUser);
}
@Override
public GetServerConfig setUploadType(java.lang.String uploadType) {
return (GetServerConfig) super.setUploadType(uploadType);
}
@Override
public GetServerConfig setUploadProtocol(java.lang.String uploadProtocol) {
return (GetServerConfig) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project and location) of the server config to get, specified in the format
* `projects/locations`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project and location) of the server config to get, specified in the format
`projects/locations`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project and location) of the server config to get, specified in the format
* `projects/locations`.
*/
public GetServerConfig setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+$");
}
this.name = name;
return this;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
*/
public GetServerConfig setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for.
* This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) to return operations for. This field
has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for.
* This field has been deprecated and replaced by the name field.
*/
public GetServerConfig setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
@Override
public GetServerConfig set(String parameterName, Object value) {
return (GetServerConfig) super.set(parameterName, value);
}
}
/**
* Fetches locations that offer Google Kubernetes Engine.
*
* Create a request for the method "locations.list".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param parent Required. Contains the name of the resource requested. Specified in the format `projects`.
* @return the request
*/
public List list(java.lang.String parent) throws java.io.IOException {
List result = new List(parent);
initialize(result);
return result;
}
public class List extends ContainerRequest<com.google.api.services.container.v1beta1.model.ListLocationsResponse> {
private static final String REST_PATH = "v1beta1/{+parent}/locations";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+$");
/**
* Fetches locations that offer Google Kubernetes Engine.
*
* Create a request for the method "locations.list".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p>
* {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param parent Required. Contains the name of the resource requested. Specified in the format `projects`.
* @since 1.13
*/
protected List(java.lang.String parent) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.ListLocationsResponse.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Contains the name of the resource requested. Specified in the format
* `projects`.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** Required. Contains the name of the resource requested. Specified in the format `projects`.
*/
public java.lang.String getParent() {
return parent;
}
/**
* Required. Contains the name of the resource requested. Specified in the format
* `projects`.
*/
public List setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
this.parent = parent;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
/**
* An accessor for creating requests from the Clusters collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.Clusters.List request = container.clusters().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Clusters clusters() {
return new Clusters();
}
/**
* The "clusters" collection of methods.
*/
public class Clusters {
/**
* Completes master IP rotation.
*
* Create a request for the method "clusters.completeIpRotation".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link CompleteIpRotation#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster name) of the cluster to complete IP rotation. Specified in the
* format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.CompleteIPRotationRequest}
* @return the request
*/
public CompleteIpRotation completeIpRotation(java.lang.String name, com.google.api.services.container.v1beta1.model.CompleteIPRotationRequest content) throws java.io.IOException {
CompleteIpRotation result = new CompleteIpRotation(name, content);
initialize(result);
return result;
}
public class CompleteIpRotation extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:completeIpRotation";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Completes master IP rotation.
*
* Create a request for the method "clusters.completeIpRotation".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link CompleteIpRotation#execute()} method to invoke the remote
* operation. <p> {@link CompleteIpRotation#initialize(com.google.api.client.googleapis.services.A
* bstractGoogleClientRequest)} must be called to initialize this instance immediately after
* invoking the constructor. </p>
*
* @param name The name (project, location, cluster name) of the cluster to complete IP rotation. Specified in the
* format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.CompleteIPRotationRequest}
* @since 1.13
*/
protected CompleteIpRotation(java.lang.String name, com.google.api.services.container.v1beta1.model.CompleteIPRotationRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public CompleteIpRotation set$Xgafv(java.lang.String $Xgafv) {
return (CompleteIpRotation) super.set$Xgafv($Xgafv);
}
@Override
public CompleteIpRotation setAccessToken(java.lang.String accessToken) {
return (CompleteIpRotation) super.setAccessToken(accessToken);
}
@Override
public CompleteIpRotation setAlt(java.lang.String alt) {
return (CompleteIpRotation) super.setAlt(alt);
}
@Override
public CompleteIpRotation setCallback(java.lang.String callback) {
return (CompleteIpRotation) super.setCallback(callback);
}
@Override
public CompleteIpRotation setFields(java.lang.String fields) {
return (CompleteIpRotation) super.setFields(fields);
}
@Override
public CompleteIpRotation setKey(java.lang.String key) {
return (CompleteIpRotation) super.setKey(key);
}
@Override
public CompleteIpRotation setOauthToken(java.lang.String oauthToken) {
return (CompleteIpRotation) super.setOauthToken(oauthToken);
}
@Override
public CompleteIpRotation setPrettyPrint(java.lang.Boolean prettyPrint) {
return (CompleteIpRotation) super.setPrettyPrint(prettyPrint);
}
@Override
public CompleteIpRotation setQuotaUser(java.lang.String quotaUser) {
return (CompleteIpRotation) super.setQuotaUser(quotaUser);
}
@Override
public CompleteIpRotation setUploadType(java.lang.String uploadType) {
return (CompleteIpRotation) super.setUploadType(uploadType);
}
@Override
public CompleteIpRotation setUploadProtocol(java.lang.String uploadProtocol) {
return (CompleteIpRotation) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster name) of the cluster to complete IP rotation.
* Specified in the format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster name) of the cluster to complete IP rotation. Specified in the
format `projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster name) of the cluster to complete IP rotation.
* Specified in the format `projects/locations/clusters`.
*/
public CompleteIpRotation setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public CompleteIpRotation set(String parameterName, Object value) {
return (CompleteIpRotation) super.set(parameterName, value);
}
}
/**
* Creates a cluster, consisting of the specified number and type of Google Compute Engine
* instances. By default, the cluster is created in the project's [default
* network](https://cloud.google.com/compute/docs/networks-and-firewalls#networks). One firewall is
* added for the cluster. After cluster creation, the Kubelet creates routes for each node to allow
* the containers on that node to communicate with all other instances in the cluster. Finally, an
* entry is added to the project's global metadata indicating which CIDR range the cluster is using.
*
* Create a request for the method "clusters.create".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation.
*
* @param parent The parent (project and location) where the cluster will be created. Specified in the format
* `projects/locations`.
* @param content the {@link com.google.api.services.container.v1beta1.model.CreateClusterRequest}
* @return the request
*/
public Create create(java.lang.String parent, com.google.api.services.container.v1beta1.model.CreateClusterRequest content) throws java.io.IOException {
Create result = new Create(parent, content);
initialize(result);
return result;
}
public class Create extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+parent}/clusters";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$");
/**
* Creates a cluster, consisting of the specified number and type of Google Compute Engine
* instances. By default, the cluster is created in the project's [default
* network](https://cloud.google.com/compute/docs/networks-and-firewalls#networks). One firewall
* is added for the cluster. After cluster creation, the Kubelet creates routes for each node to
* allow the containers on that node to communicate with all other instances in the cluster.
* Finally, an entry is added to the project's global metadata indicating which CIDR range the
* cluster is using.
*
* Create a request for the method "clusters.create".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Create#execute()} method to invoke the remote operation.
* <p> {@link
* Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param parent The parent (project and location) where the cluster will be created. Specified in the format
* `projects/locations`.
* @param content the {@link com.google.api.services.container.v1beta1.model.CreateClusterRequest}
* @since 1.13
*/
protected Create(java.lang.String parent, com.google.api.services.container.v1beta1.model.CreateClusterRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+$");
}
}
@Override
public Create set$Xgafv(java.lang.String $Xgafv) {
return (Create) super.set$Xgafv($Xgafv);
}
@Override
public Create setAccessToken(java.lang.String accessToken) {
return (Create) super.setAccessToken(accessToken);
}
@Override
public Create setAlt(java.lang.String alt) {
return (Create) super.setAlt(alt);
}
@Override
public Create setCallback(java.lang.String callback) {
return (Create) super.setCallback(callback);
}
@Override
public Create setFields(java.lang.String fields) {
return (Create) super.setFields(fields);
}
@Override
public Create setKey(java.lang.String key) {
return (Create) super.setKey(key);
}
@Override
public Create setOauthToken(java.lang.String oauthToken) {
return (Create) super.setOauthToken(oauthToken);
}
@Override
public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Create) super.setPrettyPrint(prettyPrint);
}
@Override
public Create setQuotaUser(java.lang.String quotaUser) {
return (Create) super.setQuotaUser(quotaUser);
}
@Override
public Create setUploadType(java.lang.String uploadType) {
return (Create) super.setUploadType(uploadType);
}
@Override
public Create setUploadProtocol(java.lang.String uploadProtocol) {
return (Create) super.setUploadProtocol(uploadProtocol);
}
/**
* The parent (project and location) where the cluster will be created. Specified in the
* format `projects/locations`.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** The parent (project and location) where the cluster will be created. Specified in the format
`projects/locations`.
*/
public java.lang.String getParent() {
return parent;
}
/**
* The parent (project and location) where the cluster will be created. Specified in the
* format `projects/locations`.
*/
public Create setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+$");
}
this.parent = parent;
return this;
}
@Override
public Create set(String parameterName, Object value) {
return (Create) super.set(parameterName, value);
}
}
/**
* Deletes the cluster, including the Kubernetes endpoint and all worker nodes. Firewalls and routes
* that were configured during cluster creation are also deleted. Other Google Compute Engine
* resources that might be in use by the cluster, such as load balancer resources, are not deleted
* if they weren't present when the cluster was initially created.
*
* Create a request for the method "clusters.delete".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Delete#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster) of the cluster to delete. Specified in the format
* `projects/locations/clusters`.
* @return the request
*/
public Delete delete(java.lang.String name) throws java.io.IOException {
Delete result = new Delete(name);
initialize(result);
return result;
}
public class Delete extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Deletes the cluster, including the Kubernetes endpoint and all worker nodes. Firewalls and
* routes that were configured during cluster creation are also deleted. Other Google Compute
* Engine resources that might be in use by the cluster, such as load balancer resources, are not
* deleted if they weren't present when the cluster was initially created.
*
* Create a request for the method "clusters.delete".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Delete#execute()} method to invoke the remote operation.
* <p> {@link
* Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster) of the cluster to delete. Specified in the format
* `projects/locations/clusters`.
* @since 1.13
*/
protected Delete(java.lang.String name) {
super(Container.this, "DELETE", REST_PATH, null, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public Delete set$Xgafv(java.lang.String $Xgafv) {
return (Delete) super.set$Xgafv($Xgafv);
}
@Override
public Delete setAccessToken(java.lang.String accessToken) {
return (Delete) super.setAccessToken(accessToken);
}
@Override
public Delete setAlt(java.lang.String alt) {
return (Delete) super.setAlt(alt);
}
@Override
public Delete setCallback(java.lang.String callback) {
return (Delete) super.setCallback(callback);
}
@Override
public Delete setFields(java.lang.String fields) {
return (Delete) super.setFields(fields);
}
@Override
public Delete setKey(java.lang.String key) {
return (Delete) super.setKey(key);
}
@Override
public Delete setOauthToken(java.lang.String oauthToken) {
return (Delete) super.setOauthToken(oauthToken);
}
@Override
public Delete setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Delete) super.setPrettyPrint(prettyPrint);
}
@Override
public Delete setQuotaUser(java.lang.String quotaUser) {
return (Delete) super.setQuotaUser(quotaUser);
}
@Override
public Delete setUploadType(java.lang.String uploadType) {
return (Delete) super.setUploadType(uploadType);
}
@Override
public Delete setUploadProtocol(java.lang.String uploadProtocol) {
return (Delete) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster) of the cluster to delete. Specified in the format
* `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster) of the cluster to delete. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster) of the cluster to delete. Specified in the format
* `projects/locations/clusters`.
*/
public Delete setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
/**
* Required. Deprecated. The name of the cluster to delete. This field has been deprecated
* and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to delete. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to delete. This field has been deprecated
* and replaced by the name field.
*/
public Delete setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Delete setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Delete setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
@Override
public Delete set(String parameterName, Object value) {
return (Delete) super.set(parameterName, value);
}
}
/**
* Gets the details for a specific cluster.
*
* Create a request for the method "clusters.get".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster) of the cluster to retrieve. Specified in the format
* `projects/locations/clusters`.
* @return the request
*/
public Get get(java.lang.String name) throws java.io.IOException {
Get result = new Get(name);
initialize(result);
return result;
}
public class Get extends ContainerRequest<com.google.api.services.container.v1beta1.model.Cluster> {
private static final String REST_PATH = "v1beta1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Gets the details for a specific cluster.
*
* Create a request for the method "clusters.get".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p>
* {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster) of the cluster to retrieve. Specified in the format
* `projects/locations/clusters`.
* @since 1.13
*/
protected Get(java.lang.String name) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.Cluster.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster) of the cluster to retrieve. Specified in the
* format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster) of the cluster to retrieve. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster) of the cluster to retrieve. Specified in the
* format `projects/locations/clusters`.
*/
public Get setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
/**
* Required. Deprecated. The name of the cluster to retrieve. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to retrieve. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to retrieve. This field has been
* deprecated and replaced by the name field.
*/
public Get setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Get setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Gets the public component of the cluster signing keys in JSON Web Key format. This API is not yet
* intended for general use, and is not available for all clusters.
*
* Create a request for the method "clusters.getJwks".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link GetJwks#execute()} method to invoke the remote operation.
*
* @param parent The cluster (project, location, cluster name) to get keys for. Specified in the format
* `projects/locations/clusters`.
* @return the request
*/
public GetJwks getJwks(java.lang.String parent) throws java.io.IOException {
GetJwks result = new GetJwks(parent);
initialize(result);
return result;
}
public class GetJwks extends ContainerRequest<com.google.api.services.container.v1beta1.model.GetJSONWebKeysResponse> {
private static final String REST_PATH = "v1beta1/{+parent}/jwks";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Gets the public component of the cluster signing keys in JSON Web Key format. This API is not
* yet intended for general use, and is not available for all clusters.
*
* Create a request for the method "clusters.getJwks".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link GetJwks#execute()} method to invoke the remote operation.
* <p> {@link
* GetJwks#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param parent The cluster (project, location, cluster name) to get keys for. Specified in the format
* `projects/locations/clusters`.
* @since 1.13
*/
protected GetJwks(java.lang.String parent) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.GetJSONWebKeysResponse.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public GetJwks set$Xgafv(java.lang.String $Xgafv) {
return (GetJwks) super.set$Xgafv($Xgafv);
}
@Override
public GetJwks setAccessToken(java.lang.String accessToken) {
return (GetJwks) super.setAccessToken(accessToken);
}
@Override
public GetJwks setAlt(java.lang.String alt) {
return (GetJwks) super.setAlt(alt);
}
@Override
public GetJwks setCallback(java.lang.String callback) {
return (GetJwks) super.setCallback(callback);
}
@Override
public GetJwks setFields(java.lang.String fields) {
return (GetJwks) super.setFields(fields);
}
@Override
public GetJwks setKey(java.lang.String key) {
return (GetJwks) super.setKey(key);
}
@Override
public GetJwks setOauthToken(java.lang.String oauthToken) {
return (GetJwks) super.setOauthToken(oauthToken);
}
@Override
public GetJwks setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetJwks) super.setPrettyPrint(prettyPrint);
}
@Override
public GetJwks setQuotaUser(java.lang.String quotaUser) {
return (GetJwks) super.setQuotaUser(quotaUser);
}
@Override
public GetJwks setUploadType(java.lang.String uploadType) {
return (GetJwks) super.setUploadType(uploadType);
}
@Override
public GetJwks setUploadProtocol(java.lang.String uploadProtocol) {
return (GetJwks) super.setUploadProtocol(uploadProtocol);
}
/**
* The cluster (project, location, cluster name) to get keys for. Specified in the format
* `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** The cluster (project, location, cluster name) to get keys for. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getParent() {
return parent;
}
/**
* The cluster (project, location, cluster name) to get keys for. Specified in the format
* `projects/locations/clusters`.
*/
public GetJwks setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.parent = parent;
return this;
}
@Override
public GetJwks set(String parameterName, Object value) {
return (GetJwks) super.set(parameterName, value);
}
}
/**
* Lists all clusters owned by a project in either the specified zone or all zones.
*
* Create a request for the method "clusters.list".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param parent The parent (project and location) where the clusters will be listed. Specified in the format
* `projects/locations`. Location "-" matches all zones and all regions.
* @return the request
*/
public List list(java.lang.String parent) throws java.io.IOException {
List result = new List(parent);
initialize(result);
return result;
}
public class List extends ContainerRequest<com.google.api.services.container.v1beta1.model.ListClustersResponse> {
private static final String REST_PATH = "v1beta1/{+parent}/clusters";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$");
/**
* Lists all clusters owned by a project in either the specified zone or all zones.
*
* Create a request for the method "clusters.list".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p>
* {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param parent The parent (project and location) where the clusters will be listed. Specified in the format
* `projects/locations`. Location "-" matches all zones and all regions.
* @since 1.13
*/
protected List(java.lang.String parent) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.ListClustersResponse.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
/**
* The parent (project and location) where the clusters will be listed. Specified in the
* format `projects/locations`. Location "-" matches all zones and all regions.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** The parent (project and location) where the clusters will be listed. Specified in the format
`projects/locations`. Location "-" matches all zones and all regions.
*/
public java.lang.String getParent() {
return parent;
}
/**
* The parent (project and location) where the clusters will be listed. Specified in the
* format `projects/locations`. Location "-" matches all zones and all regions.
*/
public List setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+$");
}
this.parent = parent;
return this;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the parent field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the parent field.
*/
public List setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides, or "-" for all zones. This field has been deprecated and replaced by the
* parent field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides, or "-"
for all zones. This field has been deprecated and replaced by the parent field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides, or "-" for all zones. This field has been deprecated and replaced by the
* parent field.
*/
public List setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
/**
* Sets the addons for a specific cluster.
*
* Create a request for the method "clusters.setAddons".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetAddons#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster) of the cluster to set addons. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetAddonsConfigRequest}
* @return the request
*/
public SetAddons setAddons(java.lang.String name, com.google.api.services.container.v1beta1.model.SetAddonsConfigRequest content) throws java.io.IOException {
SetAddons result = new SetAddons(name, content);
initialize(result);
return result;
}
public class SetAddons extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setAddons";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Sets the addons for a specific cluster.
*
* Create a request for the method "clusters.setAddons".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetAddons#execute()} method to invoke the remote
* operation. <p> {@link
* SetAddons#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster) of the cluster to set addons. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetAddonsConfigRequest}
* @since 1.13
*/
protected SetAddons(java.lang.String name, com.google.api.services.container.v1beta1.model.SetAddonsConfigRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public SetAddons set$Xgafv(java.lang.String $Xgafv) {
return (SetAddons) super.set$Xgafv($Xgafv);
}
@Override
public SetAddons setAccessToken(java.lang.String accessToken) {
return (SetAddons) super.setAccessToken(accessToken);
}
@Override
public SetAddons setAlt(java.lang.String alt) {
return (SetAddons) super.setAlt(alt);
}
@Override
public SetAddons setCallback(java.lang.String callback) {
return (SetAddons) super.setCallback(callback);
}
@Override
public SetAddons setFields(java.lang.String fields) {
return (SetAddons) super.setFields(fields);
}
@Override
public SetAddons setKey(java.lang.String key) {
return (SetAddons) super.setKey(key);
}
@Override
public SetAddons setOauthToken(java.lang.String oauthToken) {
return (SetAddons) super.setOauthToken(oauthToken);
}
@Override
public SetAddons setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetAddons) super.setPrettyPrint(prettyPrint);
}
@Override
public SetAddons setQuotaUser(java.lang.String quotaUser) {
return (SetAddons) super.setQuotaUser(quotaUser);
}
@Override
public SetAddons setUploadType(java.lang.String uploadType) {
return (SetAddons) super.setUploadType(uploadType);
}
@Override
public SetAddons setUploadProtocol(java.lang.String uploadProtocol) {
return (SetAddons) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster) of the cluster to set addons. Specified in the
* format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster) of the cluster to set addons. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster) of the cluster to set addons. Specified in the
* format `projects/locations/clusters`.
*/
public SetAddons setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetAddons set(String parameterName, Object value) {
return (SetAddons) super.set(parameterName, value);
}
}
/**
* Enables or disables the ABAC authorization mechanism on a cluster.
*
* Create a request for the method "clusters.setLegacyAbac".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetLegacyAbac#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster name) of the cluster to set legacy abac. Specified in the
* format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLegacyAbacRequest}
* @return the request
*/
public SetLegacyAbac setLegacyAbac(java.lang.String name, com.google.api.services.container.v1beta1.model.SetLegacyAbacRequest content) throws java.io.IOException {
SetLegacyAbac result = new SetLegacyAbac(name, content);
initialize(result);
return result;
}
public class SetLegacyAbac extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setLegacyAbac";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Enables or disables the ABAC authorization mechanism on a cluster.
*
* Create a request for the method "clusters.setLegacyAbac".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetLegacyAbac#execute()} method to invoke the remote
* operation. <p> {@link SetLegacyAbac#initialize(com.google.api.client.googleapis.services.Abstra
* ctGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param name The name (project, location, cluster name) of the cluster to set legacy abac. Specified in the
* format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLegacyAbacRequest}
* @since 1.13
*/
protected SetLegacyAbac(java.lang.String name, com.google.api.services.container.v1beta1.model.SetLegacyAbacRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public SetLegacyAbac set$Xgafv(java.lang.String $Xgafv) {
return (SetLegacyAbac) super.set$Xgafv($Xgafv);
}
@Override
public SetLegacyAbac setAccessToken(java.lang.String accessToken) {
return (SetLegacyAbac) super.setAccessToken(accessToken);
}
@Override
public SetLegacyAbac setAlt(java.lang.String alt) {
return (SetLegacyAbac) super.setAlt(alt);
}
@Override
public SetLegacyAbac setCallback(java.lang.String callback) {
return (SetLegacyAbac) super.setCallback(callback);
}
@Override
public SetLegacyAbac setFields(java.lang.String fields) {
return (SetLegacyAbac) super.setFields(fields);
}
@Override
public SetLegacyAbac setKey(java.lang.String key) {
return (SetLegacyAbac) super.setKey(key);
}
@Override
public SetLegacyAbac setOauthToken(java.lang.String oauthToken) {
return (SetLegacyAbac) super.setOauthToken(oauthToken);
}
@Override
public SetLegacyAbac setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetLegacyAbac) super.setPrettyPrint(prettyPrint);
}
@Override
public SetLegacyAbac setQuotaUser(java.lang.String quotaUser) {
return (SetLegacyAbac) super.setQuotaUser(quotaUser);
}
@Override
public SetLegacyAbac setUploadType(java.lang.String uploadType) {
return (SetLegacyAbac) super.setUploadType(uploadType);
}
@Override
public SetLegacyAbac setUploadProtocol(java.lang.String uploadProtocol) {
return (SetLegacyAbac) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster name) of the cluster to set legacy abac. Specified
* in the format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster name) of the cluster to set legacy abac. Specified in the
format `projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster name) of the cluster to set legacy abac. Specified
* in the format `projects/locations/clusters`.
*/
public SetLegacyAbac setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetLegacyAbac set(String parameterName, Object value) {
return (SetLegacyAbac) super.set(parameterName, value);
}
}
/**
* Sets the locations for a specific cluster. Deprecated. Use
* [projects.locations.clusters.update](https://cloud.google.com/kubernetes-
* engine/docs/reference/rest/v1beta1/projects.locations.clusters/update) instead.
*
* Create a request for the method "clusters.setLocations".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetLocations#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster) of the cluster to set locations. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLocationsRequest}
* @return the request
*/
public SetLocations setLocations(java.lang.String name, com.google.api.services.container.v1beta1.model.SetLocationsRequest content) throws java.io.IOException {
SetLocations result = new SetLocations(name, content);
initialize(result);
return result;
}
public class SetLocations extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setLocations";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Sets the locations for a specific cluster. Deprecated. Use
* [projects.locations.clusters.update](https://cloud.google.com/kubernetes-
* engine/docs/reference/rest/v1beta1/projects.locations.clusters/update) instead.
*
* Create a request for the method "clusters.setLocations".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetLocations#execute()} method to invoke the remote
* operation. <p> {@link
* SetLocations#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster) of the cluster to set locations. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLocationsRequest}
* @since 1.13
*/
protected SetLocations(java.lang.String name, com.google.api.services.container.v1beta1.model.SetLocationsRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public SetLocations set$Xgafv(java.lang.String $Xgafv) {
return (SetLocations) super.set$Xgafv($Xgafv);
}
@Override
public SetLocations setAccessToken(java.lang.String accessToken) {
return (SetLocations) super.setAccessToken(accessToken);
}
@Override
public SetLocations setAlt(java.lang.String alt) {
return (SetLocations) super.setAlt(alt);
}
@Override
public SetLocations setCallback(java.lang.String callback) {
return (SetLocations) super.setCallback(callback);
}
@Override
public SetLocations setFields(java.lang.String fields) {
return (SetLocations) super.setFields(fields);
}
@Override
public SetLocations setKey(java.lang.String key) {
return (SetLocations) super.setKey(key);
}
@Override
public SetLocations setOauthToken(java.lang.String oauthToken) {
return (SetLocations) super.setOauthToken(oauthToken);
}
@Override
public SetLocations setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetLocations) super.setPrettyPrint(prettyPrint);
}
@Override
public SetLocations setQuotaUser(java.lang.String quotaUser) {
return (SetLocations) super.setQuotaUser(quotaUser);
}
@Override
public SetLocations setUploadType(java.lang.String uploadType) {
return (SetLocations) super.setUploadType(uploadType);
}
@Override
public SetLocations setUploadProtocol(java.lang.String uploadProtocol) {
return (SetLocations) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster) of the cluster to set locations. Specified in the
* format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster) of the cluster to set locations. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster) of the cluster to set locations. Specified in the
* format `projects/locations/clusters`.
*/
public SetLocations setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetLocations set(String parameterName, Object value) {
return (SetLocations) super.set(parameterName, value);
}
}
/**
* Sets the logging service for a specific cluster.
*
* Create a request for the method "clusters.setLogging".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetLogging#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster) of the cluster to set logging. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLoggingServiceRequest}
* @return the request
*/
public SetLogging setLogging(java.lang.String name, com.google.api.services.container.v1beta1.model.SetLoggingServiceRequest content) throws java.io.IOException {
SetLogging result = new SetLogging(name, content);
initialize(result);
return result;
}
public class SetLogging extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setLogging";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Sets the logging service for a specific cluster.
*
* Create a request for the method "clusters.setLogging".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetLogging#execute()} method to invoke the remote
* operation. <p> {@link
* SetLogging#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster) of the cluster to set logging. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLoggingServiceRequest}
* @since 1.13
*/
protected SetLogging(java.lang.String name, com.google.api.services.container.v1beta1.model.SetLoggingServiceRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public SetLogging set$Xgafv(java.lang.String $Xgafv) {
return (SetLogging) super.set$Xgafv($Xgafv);
}
@Override
public SetLogging setAccessToken(java.lang.String accessToken) {
return (SetLogging) super.setAccessToken(accessToken);
}
@Override
public SetLogging setAlt(java.lang.String alt) {
return (SetLogging) super.setAlt(alt);
}
@Override
public SetLogging setCallback(java.lang.String callback) {
return (SetLogging) super.setCallback(callback);
}
@Override
public SetLogging setFields(java.lang.String fields) {
return (SetLogging) super.setFields(fields);
}
@Override
public SetLogging setKey(java.lang.String key) {
return (SetLogging) super.setKey(key);
}
@Override
public SetLogging setOauthToken(java.lang.String oauthToken) {
return (SetLogging) super.setOauthToken(oauthToken);
}
@Override
public SetLogging setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetLogging) super.setPrettyPrint(prettyPrint);
}
@Override
public SetLogging setQuotaUser(java.lang.String quotaUser) {
return (SetLogging) super.setQuotaUser(quotaUser);
}
@Override
public SetLogging setUploadType(java.lang.String uploadType) {
return (SetLogging) super.setUploadType(uploadType);
}
@Override
public SetLogging setUploadProtocol(java.lang.String uploadProtocol) {
return (SetLogging) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster) of the cluster to set logging. Specified in the
* format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster) of the cluster to set logging. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster) of the cluster to set logging. Specified in the
* format `projects/locations/clusters`.
*/
public SetLogging setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetLogging set(String parameterName, Object value) {
return (SetLogging) super.set(parameterName, value);
}
}
/**
* Sets the maintenance policy for a cluster.
*
* Create a request for the method "clusters.setMaintenancePolicy".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetMaintenancePolicy#execute()} method to invoke the remote
* operation.
*
* @param name The name (project, location, cluster name) of the cluster to set maintenance policy. Specified in
* the format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMaintenancePolicyRequest}
* @return the request
*/
public SetMaintenancePolicy setMaintenancePolicy(java.lang.String name, com.google.api.services.container.v1beta1.model.SetMaintenancePolicyRequest content) throws java.io.IOException {
SetMaintenancePolicy result = new SetMaintenancePolicy(name, content);
initialize(result);
return result;
}
public class SetMaintenancePolicy extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setMaintenancePolicy";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Sets the maintenance policy for a cluster.
*
* Create a request for the method "clusters.setMaintenancePolicy".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetMaintenancePolicy#execute()} method to invoke the
* remote operation. <p> {@link SetMaintenancePolicy#initialize(com.google.api.client.googleapis.s
* ervices.AbstractGoogleClientRequest)} must be called to initialize this instance immediately
* after invoking the constructor. </p>
*
* @param name The name (project, location, cluster name) of the cluster to set maintenance policy. Specified in
* the format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMaintenancePolicyRequest}
* @since 1.13
*/
protected SetMaintenancePolicy(java.lang.String name, com.google.api.services.container.v1beta1.model.SetMaintenancePolicyRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public SetMaintenancePolicy set$Xgafv(java.lang.String $Xgafv) {
return (SetMaintenancePolicy) super.set$Xgafv($Xgafv);
}
@Override
public SetMaintenancePolicy setAccessToken(java.lang.String accessToken) {
return (SetMaintenancePolicy) super.setAccessToken(accessToken);
}
@Override
public SetMaintenancePolicy setAlt(java.lang.String alt) {
return (SetMaintenancePolicy) super.setAlt(alt);
}
@Override
public SetMaintenancePolicy setCallback(java.lang.String callback) {
return (SetMaintenancePolicy) super.setCallback(callback);
}
@Override
public SetMaintenancePolicy setFields(java.lang.String fields) {
return (SetMaintenancePolicy) super.setFields(fields);
}
@Override
public SetMaintenancePolicy setKey(java.lang.String key) {
return (SetMaintenancePolicy) super.setKey(key);
}
@Override
public SetMaintenancePolicy setOauthToken(java.lang.String oauthToken) {
return (SetMaintenancePolicy) super.setOauthToken(oauthToken);
}
@Override
public SetMaintenancePolicy setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetMaintenancePolicy) super.setPrettyPrint(prettyPrint);
}
@Override
public SetMaintenancePolicy setQuotaUser(java.lang.String quotaUser) {
return (SetMaintenancePolicy) super.setQuotaUser(quotaUser);
}
@Override
public SetMaintenancePolicy setUploadType(java.lang.String uploadType) {
return (SetMaintenancePolicy) super.setUploadType(uploadType);
}
@Override
public SetMaintenancePolicy setUploadProtocol(java.lang.String uploadProtocol) {
return (SetMaintenancePolicy) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster name) of the cluster to set maintenance policy.
* Specified in the format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster name) of the cluster to set maintenance policy. Specified in
the format `projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster name) of the cluster to set maintenance policy.
* Specified in the format `projects/locations/clusters`.
*/
public SetMaintenancePolicy setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetMaintenancePolicy set(String parameterName, Object value) {
return (SetMaintenancePolicy) super.set(parameterName, value);
}
}
/**
* Sets master auth materials. Currently supports changing the admin password or a specific cluster,
* either via password generation or explicitly setting the password.
*
* Create a request for the method "clusters.setMasterAuth".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetMasterAuth#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster) of the cluster to set auth. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMasterAuthRequest}
* @return the request
*/
public SetMasterAuth setMasterAuth(java.lang.String name, com.google.api.services.container.v1beta1.model.SetMasterAuthRequest content) throws java.io.IOException {
SetMasterAuth result = new SetMasterAuth(name, content);
initialize(result);
return result;
}
public class SetMasterAuth extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setMasterAuth";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Sets master auth materials. Currently supports changing the admin password or a specific
* cluster, either via password generation or explicitly setting the password.
*
* Create a request for the method "clusters.setMasterAuth".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetMasterAuth#execute()} method to invoke the remote
* operation. <p> {@link SetMasterAuth#initialize(com.google.api.client.googleapis.services.Abstra
* ctGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param name The name (project, location, cluster) of the cluster to set auth. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMasterAuthRequest}
* @since 1.13
*/
protected SetMasterAuth(java.lang.String name, com.google.api.services.container.v1beta1.model.SetMasterAuthRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public SetMasterAuth set$Xgafv(java.lang.String $Xgafv) {
return (SetMasterAuth) super.set$Xgafv($Xgafv);
}
@Override
public SetMasterAuth setAccessToken(java.lang.String accessToken) {
return (SetMasterAuth) super.setAccessToken(accessToken);
}
@Override
public SetMasterAuth setAlt(java.lang.String alt) {
return (SetMasterAuth) super.setAlt(alt);
}
@Override
public SetMasterAuth setCallback(java.lang.String callback) {
return (SetMasterAuth) super.setCallback(callback);
}
@Override
public SetMasterAuth setFields(java.lang.String fields) {
return (SetMasterAuth) super.setFields(fields);
}
@Override
public SetMasterAuth setKey(java.lang.String key) {
return (SetMasterAuth) super.setKey(key);
}
@Override
public SetMasterAuth setOauthToken(java.lang.String oauthToken) {
return (SetMasterAuth) super.setOauthToken(oauthToken);
}
@Override
public SetMasterAuth setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetMasterAuth) super.setPrettyPrint(prettyPrint);
}
@Override
public SetMasterAuth setQuotaUser(java.lang.String quotaUser) {
return (SetMasterAuth) super.setQuotaUser(quotaUser);
}
@Override
public SetMasterAuth setUploadType(java.lang.String uploadType) {
return (SetMasterAuth) super.setUploadType(uploadType);
}
@Override
public SetMasterAuth setUploadProtocol(java.lang.String uploadProtocol) {
return (SetMasterAuth) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster) of the cluster to set auth. Specified in the
* format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster) of the cluster to set auth. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster) of the cluster to set auth. Specified in the
* format `projects/locations/clusters`.
*/
public SetMasterAuth setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetMasterAuth set(String parameterName, Object value) {
return (SetMasterAuth) super.set(parameterName, value);
}
}
/**
* Sets the monitoring service for a specific cluster.
*
* Create a request for the method "clusters.setMonitoring".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetMonitoring#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster) of the cluster to set monitoring. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMonitoringServiceRequest}
* @return the request
*/
public SetMonitoring setMonitoring(java.lang.String name, com.google.api.services.container.v1beta1.model.SetMonitoringServiceRequest content) throws java.io.IOException {
SetMonitoring result = new SetMonitoring(name, content);
initialize(result);
return result;
}
public class SetMonitoring extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setMonitoring";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Sets the monitoring service for a specific cluster.
*
* Create a request for the method "clusters.setMonitoring".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetMonitoring#execute()} method to invoke the remote
* operation. <p> {@link SetMonitoring#initialize(com.google.api.client.googleapis.services.Abstra
* ctGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param name The name (project, location, cluster) of the cluster to set monitoring. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMonitoringServiceRequest}
* @since 1.13
*/
protected SetMonitoring(java.lang.String name, com.google.api.services.container.v1beta1.model.SetMonitoringServiceRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public SetMonitoring set$Xgafv(java.lang.String $Xgafv) {
return (SetMonitoring) super.set$Xgafv($Xgafv);
}
@Override
public SetMonitoring setAccessToken(java.lang.String accessToken) {
return (SetMonitoring) super.setAccessToken(accessToken);
}
@Override
public SetMonitoring setAlt(java.lang.String alt) {
return (SetMonitoring) super.setAlt(alt);
}
@Override
public SetMonitoring setCallback(java.lang.String callback) {
return (SetMonitoring) super.setCallback(callback);
}
@Override
public SetMonitoring setFields(java.lang.String fields) {
return (SetMonitoring) super.setFields(fields);
}
@Override
public SetMonitoring setKey(java.lang.String key) {
return (SetMonitoring) super.setKey(key);
}
@Override
public SetMonitoring setOauthToken(java.lang.String oauthToken) {
return (SetMonitoring) super.setOauthToken(oauthToken);
}
@Override
public SetMonitoring setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetMonitoring) super.setPrettyPrint(prettyPrint);
}
@Override
public SetMonitoring setQuotaUser(java.lang.String quotaUser) {
return (SetMonitoring) super.setQuotaUser(quotaUser);
}
@Override
public SetMonitoring setUploadType(java.lang.String uploadType) {
return (SetMonitoring) super.setUploadType(uploadType);
}
@Override
public SetMonitoring setUploadProtocol(java.lang.String uploadProtocol) {
return (SetMonitoring) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster) of the cluster to set monitoring. Specified in
* the format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster) of the cluster to set monitoring. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster) of the cluster to set monitoring. Specified in
* the format `projects/locations/clusters`.
*/
public SetMonitoring setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetMonitoring set(String parameterName, Object value) {
return (SetMonitoring) super.set(parameterName, value);
}
}
/**
* Enables or disables Network Policy for a cluster.
*
* Create a request for the method "clusters.setNetworkPolicy".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetNetworkPolicy#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster name) of the cluster to set networking policy. Specified in the
* format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNetworkPolicyRequest}
* @return the request
*/
public SetNetworkPolicy setNetworkPolicy(java.lang.String name, com.google.api.services.container.v1beta1.model.SetNetworkPolicyRequest content) throws java.io.IOException {
SetNetworkPolicy result = new SetNetworkPolicy(name, content);
initialize(result);
return result;
}
public class SetNetworkPolicy extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setNetworkPolicy";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Enables or disables Network Policy for a cluster.
*
* Create a request for the method "clusters.setNetworkPolicy".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetNetworkPolicy#execute()} method to invoke the remote
* operation. <p> {@link SetNetworkPolicy#initialize(com.google.api.client.googleapis.services.Abs
* tractGoogleClientRequest)} must be called to initialize this instance immediately after
* invoking the constructor. </p>
*
* @param name The name (project, location, cluster name) of the cluster to set networking policy. Specified in the
* format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNetworkPolicyRequest}
* @since 1.13
*/
protected SetNetworkPolicy(java.lang.String name, com.google.api.services.container.v1beta1.model.SetNetworkPolicyRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public SetNetworkPolicy set$Xgafv(java.lang.String $Xgafv) {
return (SetNetworkPolicy) super.set$Xgafv($Xgafv);
}
@Override
public SetNetworkPolicy setAccessToken(java.lang.String accessToken) {
return (SetNetworkPolicy) super.setAccessToken(accessToken);
}
@Override
public SetNetworkPolicy setAlt(java.lang.String alt) {
return (SetNetworkPolicy) super.setAlt(alt);
}
@Override
public SetNetworkPolicy setCallback(java.lang.String callback) {
return (SetNetworkPolicy) super.setCallback(callback);
}
@Override
public SetNetworkPolicy setFields(java.lang.String fields) {
return (SetNetworkPolicy) super.setFields(fields);
}
@Override
public SetNetworkPolicy setKey(java.lang.String key) {
return (SetNetworkPolicy) super.setKey(key);
}
@Override
public SetNetworkPolicy setOauthToken(java.lang.String oauthToken) {
return (SetNetworkPolicy) super.setOauthToken(oauthToken);
}
@Override
public SetNetworkPolicy setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetNetworkPolicy) super.setPrettyPrint(prettyPrint);
}
@Override
public SetNetworkPolicy setQuotaUser(java.lang.String quotaUser) {
return (SetNetworkPolicy) super.setQuotaUser(quotaUser);
}
@Override
public SetNetworkPolicy setUploadType(java.lang.String uploadType) {
return (SetNetworkPolicy) super.setUploadType(uploadType);
}
@Override
public SetNetworkPolicy setUploadProtocol(java.lang.String uploadProtocol) {
return (SetNetworkPolicy) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster name) of the cluster to set networking policy.
* Specified in the format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster name) of the cluster to set networking policy. Specified in
the format `projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster name) of the cluster to set networking policy.
* Specified in the format `projects/locations/clusters`.
*/
public SetNetworkPolicy setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetNetworkPolicy set(String parameterName, Object value) {
return (SetNetworkPolicy) super.set(parameterName, value);
}
}
/**
* Sets labels on a cluster.
*
* Create a request for the method "clusters.setResourceLabels".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetResourceLabels#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster name) of the cluster to set labels. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLabelsRequest}
* @return the request
*/
public SetResourceLabels setResourceLabels(java.lang.String name, com.google.api.services.container.v1beta1.model.SetLabelsRequest content) throws java.io.IOException {
SetResourceLabels result = new SetResourceLabels(name, content);
initialize(result);
return result;
}
public class SetResourceLabels extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setResourceLabels";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Sets labels on a cluster.
*
* Create a request for the method "clusters.setResourceLabels".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetResourceLabels#execute()} method to invoke the remote
* operation. <p> {@link SetResourceLabels#initialize(com.google.api.client.googleapis.services.Ab
* stractGoogleClientRequest)} must be called to initialize this instance immediately after
* invoking the constructor. </p>
*
* @param name The name (project, location, cluster name) of the cluster to set labels. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLabelsRequest}
* @since 1.13
*/
protected SetResourceLabels(java.lang.String name, com.google.api.services.container.v1beta1.model.SetLabelsRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public SetResourceLabels set$Xgafv(java.lang.String $Xgafv) {
return (SetResourceLabels) super.set$Xgafv($Xgafv);
}
@Override
public SetResourceLabels setAccessToken(java.lang.String accessToken) {
return (SetResourceLabels) super.setAccessToken(accessToken);
}
@Override
public SetResourceLabels setAlt(java.lang.String alt) {
return (SetResourceLabels) super.setAlt(alt);
}
@Override
public SetResourceLabels setCallback(java.lang.String callback) {
return (SetResourceLabels) super.setCallback(callback);
}
@Override
public SetResourceLabels setFields(java.lang.String fields) {
return (SetResourceLabels) super.setFields(fields);
}
@Override
public SetResourceLabels setKey(java.lang.String key) {
return (SetResourceLabels) super.setKey(key);
}
@Override
public SetResourceLabels setOauthToken(java.lang.String oauthToken) {
return (SetResourceLabels) super.setOauthToken(oauthToken);
}
@Override
public SetResourceLabels setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetResourceLabels) super.setPrettyPrint(prettyPrint);
}
@Override
public SetResourceLabels setQuotaUser(java.lang.String quotaUser) {
return (SetResourceLabels) super.setQuotaUser(quotaUser);
}
@Override
public SetResourceLabels setUploadType(java.lang.String uploadType) {
return (SetResourceLabels) super.setUploadType(uploadType);
}
@Override
public SetResourceLabels setUploadProtocol(java.lang.String uploadProtocol) {
return (SetResourceLabels) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster name) of the cluster to set labels. Specified in
* the format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster name) of the cluster to set labels. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster name) of the cluster to set labels. Specified in
* the format `projects/locations/clusters`.
*/
public SetResourceLabels setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetResourceLabels set(String parameterName, Object value) {
return (SetResourceLabels) super.set(parameterName, value);
}
}
/**
* Starts master IP rotation.
*
* Create a request for the method "clusters.startIpRotation".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link StartIpRotation#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster name) of the cluster to start IP rotation. Specified in the
* format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.StartIPRotationRequest}
* @return the request
*/
public StartIpRotation startIpRotation(java.lang.String name, com.google.api.services.container.v1beta1.model.StartIPRotationRequest content) throws java.io.IOException {
StartIpRotation result = new StartIpRotation(name, content);
initialize(result);
return result;
}
public class StartIpRotation extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:startIpRotation";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Starts master IP rotation.
*
* Create a request for the method "clusters.startIpRotation".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link StartIpRotation#execute()} method to invoke the remote
* operation. <p> {@link StartIpRotation#initialize(com.google.api.client.googleapis.services.Abst
* ractGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param name The name (project, location, cluster name) of the cluster to start IP rotation. Specified in the
* format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.StartIPRotationRequest}
* @since 1.13
*/
protected StartIpRotation(java.lang.String name, com.google.api.services.container.v1beta1.model.StartIPRotationRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public StartIpRotation set$Xgafv(java.lang.String $Xgafv) {
return (StartIpRotation) super.set$Xgafv($Xgafv);
}
@Override
public StartIpRotation setAccessToken(java.lang.String accessToken) {
return (StartIpRotation) super.setAccessToken(accessToken);
}
@Override
public StartIpRotation setAlt(java.lang.String alt) {
return (StartIpRotation) super.setAlt(alt);
}
@Override
public StartIpRotation setCallback(java.lang.String callback) {
return (StartIpRotation) super.setCallback(callback);
}
@Override
public StartIpRotation setFields(java.lang.String fields) {
return (StartIpRotation) super.setFields(fields);
}
@Override
public StartIpRotation setKey(java.lang.String key) {
return (StartIpRotation) super.setKey(key);
}
@Override
public StartIpRotation setOauthToken(java.lang.String oauthToken) {
return (StartIpRotation) super.setOauthToken(oauthToken);
}
@Override
public StartIpRotation setPrettyPrint(java.lang.Boolean prettyPrint) {
return (StartIpRotation) super.setPrettyPrint(prettyPrint);
}
@Override
public StartIpRotation setQuotaUser(java.lang.String quotaUser) {
return (StartIpRotation) super.setQuotaUser(quotaUser);
}
@Override
public StartIpRotation setUploadType(java.lang.String uploadType) {
return (StartIpRotation) super.setUploadType(uploadType);
}
@Override
public StartIpRotation setUploadProtocol(java.lang.String uploadProtocol) {
return (StartIpRotation) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster name) of the cluster to start IP rotation.
* Specified in the format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster name) of the cluster to start IP rotation. Specified in the
format `projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster name) of the cluster to start IP rotation.
* Specified in the format `projects/locations/clusters`.
*/
public StartIpRotation setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public StartIpRotation set(String parameterName, Object value) {
return (StartIpRotation) super.set(parameterName, value);
}
}
/**
* Updates the settings for a specific cluster.
*
* Create a request for the method "clusters.update".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Update#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster) of the cluster to update. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateClusterRequest}
* @return the request
*/
public Update update(java.lang.String name, com.google.api.services.container.v1beta1.model.UpdateClusterRequest content) throws java.io.IOException {
Update result = new Update(name, content);
initialize(result);
return result;
}
public class Update extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Updates the settings for a specific cluster.
*
* Create a request for the method "clusters.update".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Update#execute()} method to invoke the remote operation.
* <p> {@link
* Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster) of the cluster to update. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateClusterRequest}
* @since 1.13
*/
protected Update(java.lang.String name, com.google.api.services.container.v1beta1.model.UpdateClusterRequest content) {
super(Container.this, "PUT", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public Update set$Xgafv(java.lang.String $Xgafv) {
return (Update) super.set$Xgafv($Xgafv);
}
@Override
public Update setAccessToken(java.lang.String accessToken) {
return (Update) super.setAccessToken(accessToken);
}
@Override
public Update setAlt(java.lang.String alt) {
return (Update) super.setAlt(alt);
}
@Override
public Update setCallback(java.lang.String callback) {
return (Update) super.setCallback(callback);
}
@Override
public Update setFields(java.lang.String fields) {
return (Update) super.setFields(fields);
}
@Override
public Update setKey(java.lang.String key) {
return (Update) super.setKey(key);
}
@Override
public Update setOauthToken(java.lang.String oauthToken) {
return (Update) super.setOauthToken(oauthToken);
}
@Override
public Update setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Update) super.setPrettyPrint(prettyPrint);
}
@Override
public Update setQuotaUser(java.lang.String quotaUser) {
return (Update) super.setQuotaUser(quotaUser);
}
@Override
public Update setUploadType(java.lang.String uploadType) {
return (Update) super.setUploadType(uploadType);
}
@Override
public Update setUploadProtocol(java.lang.String uploadProtocol) {
return (Update) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster) of the cluster to update. Specified in the format
* `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster) of the cluster to update. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster) of the cluster to update. Specified in the format
* `projects/locations/clusters`.
*/
public Update setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public Update set(String parameterName, Object value) {
return (Update) super.set(parameterName, value);
}
}
/**
* Updates the master for a specific cluster.
*
* Create a request for the method "clusters.updateMaster".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link UpdateMaster#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster) of the cluster to update. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateMasterRequest}
* @return the request
*/
public UpdateMaster updateMaster(java.lang.String name, com.google.api.services.container.v1beta1.model.UpdateMasterRequest content) throws java.io.IOException {
UpdateMaster result = new UpdateMaster(name, content);
initialize(result);
return result;
}
public class UpdateMaster extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:updateMaster";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Updates the master for a specific cluster.
*
* Create a request for the method "clusters.updateMaster".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link UpdateMaster#execute()} method to invoke the remote
* operation. <p> {@link
* UpdateMaster#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster) of the cluster to update. Specified in the format
* `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateMasterRequest}
* @since 1.13
*/
protected UpdateMaster(java.lang.String name, com.google.api.services.container.v1beta1.model.UpdateMasterRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public UpdateMaster set$Xgafv(java.lang.String $Xgafv) {
return (UpdateMaster) super.set$Xgafv($Xgafv);
}
@Override
public UpdateMaster setAccessToken(java.lang.String accessToken) {
return (UpdateMaster) super.setAccessToken(accessToken);
}
@Override
public UpdateMaster setAlt(java.lang.String alt) {
return (UpdateMaster) super.setAlt(alt);
}
@Override
public UpdateMaster setCallback(java.lang.String callback) {
return (UpdateMaster) super.setCallback(callback);
}
@Override
public UpdateMaster setFields(java.lang.String fields) {
return (UpdateMaster) super.setFields(fields);
}
@Override
public UpdateMaster setKey(java.lang.String key) {
return (UpdateMaster) super.setKey(key);
}
@Override
public UpdateMaster setOauthToken(java.lang.String oauthToken) {
return (UpdateMaster) super.setOauthToken(oauthToken);
}
@Override
public UpdateMaster setPrettyPrint(java.lang.Boolean prettyPrint) {
return (UpdateMaster) super.setPrettyPrint(prettyPrint);
}
@Override
public UpdateMaster setQuotaUser(java.lang.String quotaUser) {
return (UpdateMaster) super.setQuotaUser(quotaUser);
}
@Override
public UpdateMaster setUploadType(java.lang.String uploadType) {
return (UpdateMaster) super.setUploadType(uploadType);
}
@Override
public UpdateMaster setUploadProtocol(java.lang.String uploadProtocol) {
return (UpdateMaster) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster) of the cluster to update. Specified in the format
* `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster) of the cluster to update. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster) of the cluster to update. Specified in the format
* `projects/locations/clusters`.
*/
public UpdateMaster setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.name = name;
return this;
}
@Override
public UpdateMaster set(String parameterName, Object value) {
return (UpdateMaster) super.set(parameterName, value);
}
}
/**
* An accessor for creating requests from the NodePools collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.NodePools.List request = container.nodePools().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public NodePools nodePools() {
return new NodePools();
}
/**
* The "nodePools" collection of methods.
*/
public class NodePools {
/**
* Creates a node pool for a cluster.
*
* Create a request for the method "nodePools.create".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation.
*
* @param parent The parent (project, location, cluster name) where the node pool will be created. Specified in the
* format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.CreateNodePoolRequest}
* @return the request
*/
public Create create(java.lang.String parent, com.google.api.services.container.v1beta1.model.CreateNodePoolRequest content) throws java.io.IOException {
Create result = new Create(parent, content);
initialize(result);
return result;
}
public class Create extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+parent}/nodePools";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Creates a node pool for a cluster.
*
* Create a request for the method "nodePools.create".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Create#execute()} method to invoke the remote operation.
* <p> {@link
* Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param parent The parent (project, location, cluster name) where the node pool will be created. Specified in the
* format `projects/locations/clusters`.
* @param content the {@link com.google.api.services.container.v1beta1.model.CreateNodePoolRequest}
* @since 1.13
*/
protected Create(java.lang.String parent, com.google.api.services.container.v1beta1.model.CreateNodePoolRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public Create set$Xgafv(java.lang.String $Xgafv) {
return (Create) super.set$Xgafv($Xgafv);
}
@Override
public Create setAccessToken(java.lang.String accessToken) {
return (Create) super.setAccessToken(accessToken);
}
@Override
public Create setAlt(java.lang.String alt) {
return (Create) super.setAlt(alt);
}
@Override
public Create setCallback(java.lang.String callback) {
return (Create) super.setCallback(callback);
}
@Override
public Create setFields(java.lang.String fields) {
return (Create) super.setFields(fields);
}
@Override
public Create setKey(java.lang.String key) {
return (Create) super.setKey(key);
}
@Override
public Create setOauthToken(java.lang.String oauthToken) {
return (Create) super.setOauthToken(oauthToken);
}
@Override
public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Create) super.setPrettyPrint(prettyPrint);
}
@Override
public Create setQuotaUser(java.lang.String quotaUser) {
return (Create) super.setQuotaUser(quotaUser);
}
@Override
public Create setUploadType(java.lang.String uploadType) {
return (Create) super.setUploadType(uploadType);
}
@Override
public Create setUploadProtocol(java.lang.String uploadProtocol) {
return (Create) super.setUploadProtocol(uploadProtocol);
}
/**
* The parent (project, location, cluster name) where the node pool will be created.
* Specified in the format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** The parent (project, location, cluster name) where the node pool will be created. Specified in the
format `projects/locations/clusters`.
*/
public java.lang.String getParent() {
return parent;
}
/**
* The parent (project, location, cluster name) where the node pool will be created.
* Specified in the format `projects/locations/clusters`.
*/
public Create setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.parent = parent;
return this;
}
@Override
public Create set(String parameterName, Object value) {
return (Create) super.set(parameterName, value);
}
}
/**
* Deletes a node pool from a cluster.
*
* Create a request for the method "nodePools.delete".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Delete#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster, node pool id) of the node pool to delete. Specified in the
* format `projects/locations/clusters/nodePools`.
* @return the request
*/
public Delete delete(java.lang.String name) throws java.io.IOException {
Delete result = new Delete(name);
initialize(result);
return result;
}
public class Delete extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
/**
* Deletes a node pool from a cluster.
*
* Create a request for the method "nodePools.delete".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Delete#execute()} method to invoke the remote operation.
* <p> {@link
* Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster, node pool id) of the node pool to delete. Specified in the
* format `projects/locations/clusters/nodePools`.
* @since 1.13
*/
protected Delete(java.lang.String name) {
super(Container.this, "DELETE", REST_PATH, null, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
}
@Override
public Delete set$Xgafv(java.lang.String $Xgafv) {
return (Delete) super.set$Xgafv($Xgafv);
}
@Override
public Delete setAccessToken(java.lang.String accessToken) {
return (Delete) super.setAccessToken(accessToken);
}
@Override
public Delete setAlt(java.lang.String alt) {
return (Delete) super.setAlt(alt);
}
@Override
public Delete setCallback(java.lang.String callback) {
return (Delete) super.setCallback(callback);
}
@Override
public Delete setFields(java.lang.String fields) {
return (Delete) super.setFields(fields);
}
@Override
public Delete setKey(java.lang.String key) {
return (Delete) super.setKey(key);
}
@Override
public Delete setOauthToken(java.lang.String oauthToken) {
return (Delete) super.setOauthToken(oauthToken);
}
@Override
public Delete setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Delete) super.setPrettyPrint(prettyPrint);
}
@Override
public Delete setQuotaUser(java.lang.String quotaUser) {
return (Delete) super.setQuotaUser(quotaUser);
}
@Override
public Delete setUploadType(java.lang.String uploadType) {
return (Delete) super.setUploadType(uploadType);
}
@Override
public Delete setUploadProtocol(java.lang.String uploadProtocol) {
return (Delete) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster, node pool id) of the node pool to delete.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster, node pool id) of the node pool to delete. Specified in the
format `projects/locations/clusters/nodePools`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster, node pool id) of the node pool to delete.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
public Delete setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
this.name = name;
return this;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
public Delete setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The name of the node pool to delete. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String nodePoolId;
/** Required. Deprecated. The name of the node pool to delete. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getNodePoolId() {
return nodePoolId;
}
/**
* Required. Deprecated. The name of the node pool to delete. This field has been
* deprecated and replaced by the name field.
*/
public Delete setNodePoolId(java.lang.String nodePoolId) {
this.nodePoolId = nodePoolId;
return this;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://developers.google.com/console/help/new/#projectnumber). This field has been
deprecated and replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the name field.
*/
public Delete setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Delete setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
@Override
public Delete set(String parameterName, Object value) {
return (Delete) super.set(parameterName, value);
}
}
/**
* Retrieves the requested node pool.
*
* Create a request for the method "nodePools.get".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster, node pool id) of the node pool to get. Specified in the format
* `projects/locations/clusters/nodePools`.
* @return the request
*/
public Get get(java.lang.String name) throws java.io.IOException {
Get result = new Get(name);
initialize(result);
return result;
}
public class Get extends ContainerRequest<com.google.api.services.container.v1beta1.model.NodePool> {
private static final String REST_PATH = "v1beta1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
/**
* Retrieves the requested node pool.
*
* Create a request for the method "nodePools.get".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p>
* {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster, node pool id) of the node pool to get. Specified in the format
* `projects/locations/clusters/nodePools`.
* @since 1.13
*/
protected Get(java.lang.String name) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.NodePool.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster, node pool id) of the node pool to get.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster, node pool id) of the node pool to get. Specified in the
format `projects/locations/clusters/nodePools`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster, node pool id) of the node pool to get.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
public Get setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
this.name = name;
return this;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
public Get setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The name of the node pool. This field has been deprecated and
* replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String nodePoolId;
/** Required. Deprecated. The name of the node pool. This field has been deprecated and replaced by the
name field.
*/
public java.lang.String getNodePoolId() {
return nodePoolId;
}
/**
* Required. Deprecated. The name of the node pool. This field has been deprecated and
* replaced by the name field.
*/
public Get setNodePoolId(java.lang.String nodePoolId) {
this.nodePoolId = nodePoolId;
return this;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://developers.google.com/console/help/new/#projectnumber). This field has been
deprecated and replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the name field.
*/
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Get setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Lists the node pools for a cluster.
*
* Create a request for the method "nodePools.list".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param parent The parent (project, location, cluster name) where the node pools will be listed. Specified in the
* format `projects/locations/clusters`.
* @return the request
*/
public List list(java.lang.String parent) throws java.io.IOException {
List result = new List(parent);
initialize(result);
return result;
}
public class List extends ContainerRequest<com.google.api.services.container.v1beta1.model.ListNodePoolsResponse> {
private static final String REST_PATH = "v1beta1/{+parent}/nodePools";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Lists the node pools for a cluster.
*
* Create a request for the method "nodePools.list".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p>
* {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param parent The parent (project, location, cluster name) where the node pools will be listed. Specified in the
* format `projects/locations/clusters`.
* @since 1.13
*/
protected List(java.lang.String parent) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.ListNodePoolsResponse.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
/**
* The parent (project, location, cluster name) where the node pools will be listed.
* Specified in the format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** The parent (project, location, cluster name) where the node pools will be listed. Specified in the
format `projects/locations/clusters`.
*/
public java.lang.String getParent() {
return parent;
}
/**
* The parent (project, location, cluster name) where the node pools will be listed.
* Specified in the format `projects/locations/clusters`.
*/
public List setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.parent = parent;
return this;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
parent field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the parent field.
*/
public List setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://developers.google.com/console/help/new/#projectnumber). This field has been
deprecated and replaced by the parent field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the parent field.
*/
public List setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the parent field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
*/
public List setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
/**
* Rolls back a previously Aborted or Failed NodePool upgrade. This makes no changes if the last
* upgrade successfully completed.
*
* Create a request for the method "nodePools.rollback".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Rollback#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster, node pool id) of the node poll to rollback upgrade. Specified
* in the format `projects/locations/clusters/nodePools`.
* @param content the {@link com.google.api.services.container.v1beta1.model.RollbackNodePoolUpgradeRequest}
* @return the request
*/
public Rollback rollback(java.lang.String name, com.google.api.services.container.v1beta1.model.RollbackNodePoolUpgradeRequest content) throws java.io.IOException {
Rollback result = new Rollback(name, content);
initialize(result);
return result;
}
public class Rollback extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:rollback";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
/**
* Rolls back a previously Aborted or Failed NodePool upgrade. This makes no changes if the last
* upgrade successfully completed.
*
* Create a request for the method "nodePools.rollback".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Rollback#execute()} method to invoke the remote operation.
* <p> {@link
* Rollback#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster, node pool id) of the node poll to rollback upgrade. Specified
* in the format `projects/locations/clusters/nodePools`.
* @param content the {@link com.google.api.services.container.v1beta1.model.RollbackNodePoolUpgradeRequest}
* @since 1.13
*/
protected Rollback(java.lang.String name, com.google.api.services.container.v1beta1.model.RollbackNodePoolUpgradeRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
}
@Override
public Rollback set$Xgafv(java.lang.String $Xgafv) {
return (Rollback) super.set$Xgafv($Xgafv);
}
@Override
public Rollback setAccessToken(java.lang.String accessToken) {
return (Rollback) super.setAccessToken(accessToken);
}
@Override
public Rollback setAlt(java.lang.String alt) {
return (Rollback) super.setAlt(alt);
}
@Override
public Rollback setCallback(java.lang.String callback) {
return (Rollback) super.setCallback(callback);
}
@Override
public Rollback setFields(java.lang.String fields) {
return (Rollback) super.setFields(fields);
}
@Override
public Rollback setKey(java.lang.String key) {
return (Rollback) super.setKey(key);
}
@Override
public Rollback setOauthToken(java.lang.String oauthToken) {
return (Rollback) super.setOauthToken(oauthToken);
}
@Override
public Rollback setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Rollback) super.setPrettyPrint(prettyPrint);
}
@Override
public Rollback setQuotaUser(java.lang.String quotaUser) {
return (Rollback) super.setQuotaUser(quotaUser);
}
@Override
public Rollback setUploadType(java.lang.String uploadType) {
return (Rollback) super.setUploadType(uploadType);
}
@Override
public Rollback setUploadProtocol(java.lang.String uploadProtocol) {
return (Rollback) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster, node pool id) of the node poll to rollback
* upgrade. Specified in the format `projects/locations/clusters/nodePools`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster, node pool id) of the node poll to rollback upgrade. Specified
in the format `projects/locations/clusters/nodePools`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster, node pool id) of the node poll to rollback
* upgrade. Specified in the format `projects/locations/clusters/nodePools`.
*/
public Rollback setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
this.name = name;
return this;
}
@Override
public Rollback set(String parameterName, Object value) {
return (Rollback) super.set(parameterName, value);
}
}
/**
* Sets the autoscaling settings of a specific node pool.
*
* Create a request for the method "nodePools.setAutoscaling".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetAutoscaling#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster, node pool) of the node pool to set autoscaler settings.
* Specified in the format `projects/locations/clusters/nodePools`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolAutoscalingRequest}
* @return the request
*/
public SetAutoscaling setAutoscaling(java.lang.String name, com.google.api.services.container.v1beta1.model.SetNodePoolAutoscalingRequest content) throws java.io.IOException {
SetAutoscaling result = new SetAutoscaling(name, content);
initialize(result);
return result;
}
public class SetAutoscaling extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setAutoscaling";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
/**
* Sets the autoscaling settings of a specific node pool.
*
* Create a request for the method "nodePools.setAutoscaling".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetAutoscaling#execute()} method to invoke the remote
* operation. <p> {@link SetAutoscaling#initialize(com.google.api.client.googleapis.services.Abstr
* actGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param name The name (project, location, cluster, node pool) of the node pool to set autoscaler settings.
* Specified in the format `projects/locations/clusters/nodePools`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolAutoscalingRequest}
* @since 1.13
*/
protected SetAutoscaling(java.lang.String name, com.google.api.services.container.v1beta1.model.SetNodePoolAutoscalingRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
}
@Override
public SetAutoscaling set$Xgafv(java.lang.String $Xgafv) {
return (SetAutoscaling) super.set$Xgafv($Xgafv);
}
@Override
public SetAutoscaling setAccessToken(java.lang.String accessToken) {
return (SetAutoscaling) super.setAccessToken(accessToken);
}
@Override
public SetAutoscaling setAlt(java.lang.String alt) {
return (SetAutoscaling) super.setAlt(alt);
}
@Override
public SetAutoscaling setCallback(java.lang.String callback) {
return (SetAutoscaling) super.setCallback(callback);
}
@Override
public SetAutoscaling setFields(java.lang.String fields) {
return (SetAutoscaling) super.setFields(fields);
}
@Override
public SetAutoscaling setKey(java.lang.String key) {
return (SetAutoscaling) super.setKey(key);
}
@Override
public SetAutoscaling setOauthToken(java.lang.String oauthToken) {
return (SetAutoscaling) super.setOauthToken(oauthToken);
}
@Override
public SetAutoscaling setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetAutoscaling) super.setPrettyPrint(prettyPrint);
}
@Override
public SetAutoscaling setQuotaUser(java.lang.String quotaUser) {
return (SetAutoscaling) super.setQuotaUser(quotaUser);
}
@Override
public SetAutoscaling setUploadType(java.lang.String uploadType) {
return (SetAutoscaling) super.setUploadType(uploadType);
}
@Override
public SetAutoscaling setUploadProtocol(java.lang.String uploadProtocol) {
return (SetAutoscaling) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster, node pool) of the node pool to set autoscaler
* settings. Specified in the format `projects/locations/clusters/nodePools`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster, node pool) of the node pool to set autoscaler settings.
Specified in the format `projects/locations/clusters/nodePools`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster, node pool) of the node pool to set autoscaler
* settings. Specified in the format `projects/locations/clusters/nodePools`.
*/
public SetAutoscaling setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetAutoscaling set(String parameterName, Object value) {
return (SetAutoscaling) super.set(parameterName, value);
}
}
/**
* Sets the NodeManagement options for a node pool.
*
* Create a request for the method "nodePools.setManagement".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetManagement#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster, node pool id) of the node pool to set management properties.
* Specified in the format `projects/locations/clusters/nodePools`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolManagementRequest}
* @return the request
*/
public SetManagement setManagement(java.lang.String name, com.google.api.services.container.v1beta1.model.SetNodePoolManagementRequest content) throws java.io.IOException {
SetManagement result = new SetManagement(name, content);
initialize(result);
return result;
}
public class SetManagement extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setManagement";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
/**
* Sets the NodeManagement options for a node pool.
*
* Create a request for the method "nodePools.setManagement".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetManagement#execute()} method to invoke the remote
* operation. <p> {@link SetManagement#initialize(com.google.api.client.googleapis.services.Abstra
* ctGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param name The name (project, location, cluster, node pool id) of the node pool to set management properties.
* Specified in the format `projects/locations/clusters/nodePools`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolManagementRequest}
* @since 1.13
*/
protected SetManagement(java.lang.String name, com.google.api.services.container.v1beta1.model.SetNodePoolManagementRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
}
@Override
public SetManagement set$Xgafv(java.lang.String $Xgafv) {
return (SetManagement) super.set$Xgafv($Xgafv);
}
@Override
public SetManagement setAccessToken(java.lang.String accessToken) {
return (SetManagement) super.setAccessToken(accessToken);
}
@Override
public SetManagement setAlt(java.lang.String alt) {
return (SetManagement) super.setAlt(alt);
}
@Override
public SetManagement setCallback(java.lang.String callback) {
return (SetManagement) super.setCallback(callback);
}
@Override
public SetManagement setFields(java.lang.String fields) {
return (SetManagement) super.setFields(fields);
}
@Override
public SetManagement setKey(java.lang.String key) {
return (SetManagement) super.setKey(key);
}
@Override
public SetManagement setOauthToken(java.lang.String oauthToken) {
return (SetManagement) super.setOauthToken(oauthToken);
}
@Override
public SetManagement setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetManagement) super.setPrettyPrint(prettyPrint);
}
@Override
public SetManagement setQuotaUser(java.lang.String quotaUser) {
return (SetManagement) super.setQuotaUser(quotaUser);
}
@Override
public SetManagement setUploadType(java.lang.String uploadType) {
return (SetManagement) super.setUploadType(uploadType);
}
@Override
public SetManagement setUploadProtocol(java.lang.String uploadProtocol) {
return (SetManagement) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster, node pool id) of the node pool to set
* management properties. Specified in the format
* `projects/locations/clusters/nodePools`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster, node pool id) of the node pool to set management properties.
Specified in the format `projects/locations/clusters/nodePools`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster, node pool id) of the node pool to set
* management properties. Specified in the format
* `projects/locations/clusters/nodePools`.
*/
public SetManagement setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetManagement set(String parameterName, Object value) {
return (SetManagement) super.set(parameterName, value);
}
}
/**
* SetNodePoolSizeRequest sets the size of a node pool. The new size will be used for all replicas,
* including future replicas created by modifying NodePool.locations.
*
* Create a request for the method "nodePools.setSize".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetSize#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster, node pool id) of the node pool to set size. Specified in the
* format `projects/locations/clusters/nodePools`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolSizeRequest}
* @return the request
*/
public SetSize setSize(java.lang.String name, com.google.api.services.container.v1beta1.model.SetNodePoolSizeRequest content) throws java.io.IOException {
SetSize result = new SetSize(name, content);
initialize(result);
return result;
}
public class SetSize extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}:setSize";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
/**
* SetNodePoolSizeRequest sets the size of a node pool. The new size will be used for all
* replicas, including future replicas created by modifying NodePool.locations.
*
* Create a request for the method "nodePools.setSize".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetSize#execute()} method to invoke the remote operation.
* <p> {@link
* SetSize#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster, node pool id) of the node pool to set size. Specified in the
* format `projects/locations/clusters/nodePools`.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolSizeRequest}
* @since 1.13
*/
protected SetSize(java.lang.String name, com.google.api.services.container.v1beta1.model.SetNodePoolSizeRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
}
@Override
public SetSize set$Xgafv(java.lang.String $Xgafv) {
return (SetSize) super.set$Xgafv($Xgafv);
}
@Override
public SetSize setAccessToken(java.lang.String accessToken) {
return (SetSize) super.setAccessToken(accessToken);
}
@Override
public SetSize setAlt(java.lang.String alt) {
return (SetSize) super.setAlt(alt);
}
@Override
public SetSize setCallback(java.lang.String callback) {
return (SetSize) super.setCallback(callback);
}
@Override
public SetSize setFields(java.lang.String fields) {
return (SetSize) super.setFields(fields);
}
@Override
public SetSize setKey(java.lang.String key) {
return (SetSize) super.setKey(key);
}
@Override
public SetSize setOauthToken(java.lang.String oauthToken) {
return (SetSize) super.setOauthToken(oauthToken);
}
@Override
public SetSize setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetSize) super.setPrettyPrint(prettyPrint);
}
@Override
public SetSize setQuotaUser(java.lang.String quotaUser) {
return (SetSize) super.setQuotaUser(quotaUser);
}
@Override
public SetSize setUploadType(java.lang.String uploadType) {
return (SetSize) super.setUploadType(uploadType);
}
@Override
public SetSize setUploadProtocol(java.lang.String uploadProtocol) {
return (SetSize) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster, node pool id) of the node pool to set size.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster, node pool id) of the node pool to set size. Specified in the
format `projects/locations/clusters/nodePools`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster, node pool id) of the node pool to set size.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
public SetSize setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
this.name = name;
return this;
}
@Override
public SetSize set(String parameterName, Object value) {
return (SetSize) super.set(parameterName, value);
}
}
/**
* Updates the version and/or image type of a specific node pool.
*
* Create a request for the method "nodePools.update".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Update#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, cluster, node pool) of the node pool to update. Specified in the format
* `projects/locations/clusters/nodePools`.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateNodePoolRequest}
* @return the request
*/
public Update update(java.lang.String name, com.google.api.services.container.v1beta1.model.UpdateNodePoolRequest content) throws java.io.IOException {
Update result = new Update(name, content);
initialize(result);
return result;
}
public class Update extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
/**
* Updates the version and/or image type of a specific node pool.
*
* Create a request for the method "nodePools.update".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Update#execute()} method to invoke the remote operation.
* <p> {@link
* Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, cluster, node pool) of the node pool to update. Specified in the format
* `projects/locations/clusters/nodePools`.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateNodePoolRequest}
* @since 1.13
*/
protected Update(java.lang.String name, com.google.api.services.container.v1beta1.model.UpdateNodePoolRequest content) {
super(Container.this, "PUT", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
}
@Override
public Update set$Xgafv(java.lang.String $Xgafv) {
return (Update) super.set$Xgafv($Xgafv);
}
@Override
public Update setAccessToken(java.lang.String accessToken) {
return (Update) super.setAccessToken(accessToken);
}
@Override
public Update setAlt(java.lang.String alt) {
return (Update) super.setAlt(alt);
}
@Override
public Update setCallback(java.lang.String callback) {
return (Update) super.setCallback(callback);
}
@Override
public Update setFields(java.lang.String fields) {
return (Update) super.setFields(fields);
}
@Override
public Update setKey(java.lang.String key) {
return (Update) super.setKey(key);
}
@Override
public Update setOauthToken(java.lang.String oauthToken) {
return (Update) super.setOauthToken(oauthToken);
}
@Override
public Update setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Update) super.setPrettyPrint(prettyPrint);
}
@Override
public Update setQuotaUser(java.lang.String quotaUser) {
return (Update) super.setQuotaUser(quotaUser);
}
@Override
public Update setUploadType(java.lang.String uploadType) {
return (Update) super.setUploadType(uploadType);
}
@Override
public Update setUploadProtocol(java.lang.String uploadProtocol) {
return (Update) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, cluster, node pool) of the node pool to update.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster, node pool) of the node pool to update. Specified in the
format `projects/locations/clusters/nodePools`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster, node pool) of the node pool to update.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
public Update setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+/nodePools/[^/]+$");
}
this.name = name;
return this;
}
@Override
public Update set(String parameterName, Object value) {
return (Update) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the WellKnown collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.WellKnown.List request = container.wellKnown().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public WellKnown wellKnown() {
return new WellKnown();
}
/**
* The "well-known" collection of methods.
*/
public class WellKnown {
/**
* Gets the OIDC discovery document for the cluster. See the [OpenID Connect Discovery 1.0
* specification](https://openid.net/specs/openid-connect-discovery-1_0.html) for details. This API
* is not yet intended for general use, and is not available for all clusters.
*
* Create a request for the method "well-known.getOpenid-configuration".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link GetOpenidConfiguration#execute()} method to invoke the remote
* operation.
*
* @param parent The cluster (project, location, cluster name) to get the discovery document for. Specified in the
* format `projects/locations/clusters`.
* @return the request
*/
public GetOpenidConfiguration getOpenidConfiguration(java.lang.String parent) throws java.io.IOException {
GetOpenidConfiguration result = new GetOpenidConfiguration(parent);
initialize(result);
return result;
}
public class GetOpenidConfiguration extends ContainerRequest<com.google.api.services.container.v1beta1.model.GetOpenIDConfigResponse> {
private static final String REST_PATH = "v1beta1/{+parent}/.well-known/openid-configuration";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
/**
* Gets the OIDC discovery document for the cluster. See the [OpenID Connect Discovery 1.0
* specification](https://openid.net/specs/openid-connect-discovery-1_0.html) for details. This
* API is not yet intended for general use, and is not available for all clusters.
*
* Create a request for the method "well-known.getOpenid-configuration".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link GetOpenidConfiguration#execute()} method to invoke the
* remote operation. <p> {@link GetOpenidConfiguration#initialize(com.google.api.client.googleapis
* .services.AbstractGoogleClientRequest)} must be called to initialize this instance immediately
* after invoking the constructor. </p>
*
* @param parent The cluster (project, location, cluster name) to get the discovery document for. Specified in the
* format `projects/locations/clusters`.
* @since 1.13
*/
protected GetOpenidConfiguration(java.lang.String parent) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.GetOpenIDConfigResponse.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public GetOpenidConfiguration set$Xgafv(java.lang.String $Xgafv) {
return (GetOpenidConfiguration) super.set$Xgafv($Xgafv);
}
@Override
public GetOpenidConfiguration setAccessToken(java.lang.String accessToken) {
return (GetOpenidConfiguration) super.setAccessToken(accessToken);
}
@Override
public GetOpenidConfiguration setAlt(java.lang.String alt) {
return (GetOpenidConfiguration) super.setAlt(alt);
}
@Override
public GetOpenidConfiguration setCallback(java.lang.String callback) {
return (GetOpenidConfiguration) super.setCallback(callback);
}
@Override
public GetOpenidConfiguration setFields(java.lang.String fields) {
return (GetOpenidConfiguration) super.setFields(fields);
}
@Override
public GetOpenidConfiguration setKey(java.lang.String key) {
return (GetOpenidConfiguration) super.setKey(key);
}
@Override
public GetOpenidConfiguration setOauthToken(java.lang.String oauthToken) {
return (GetOpenidConfiguration) super.setOauthToken(oauthToken);
}
@Override
public GetOpenidConfiguration setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetOpenidConfiguration) super.setPrettyPrint(prettyPrint);
}
@Override
public GetOpenidConfiguration setQuotaUser(java.lang.String quotaUser) {
return (GetOpenidConfiguration) super.setQuotaUser(quotaUser);
}
@Override
public GetOpenidConfiguration setUploadType(java.lang.String uploadType) {
return (GetOpenidConfiguration) super.setUploadType(uploadType);
}
@Override
public GetOpenidConfiguration setUploadProtocol(java.lang.String uploadProtocol) {
return (GetOpenidConfiguration) super.setUploadProtocol(uploadProtocol);
}
/**
* The cluster (project, location, cluster name) to get the discovery document for.
* Specified in the format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** The cluster (project, location, cluster name) to get the discovery document for. Specified in the
format `projects/locations/clusters`.
*/
public java.lang.String getParent() {
return parent;
}
/**
* The cluster (project, location, cluster name) to get the discovery document for.
* Specified in the format `projects/locations/clusters`.
*/
public GetOpenidConfiguration setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/clusters/[^/]+$");
}
this.parent = parent;
return this;
}
@Override
public GetOpenidConfiguration set(String parameterName, Object value) {
return (GetOpenidConfiguration) super.set(parameterName, value);
}
}
}
}
/**
* An accessor for creating requests from the Operations collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.Operations.List request = container.operations().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Operations operations() {
return new Operations();
}
/**
* The "operations" collection of methods.
*/
public class Operations {
/**
* Cancels the specified operation.
*
* Create a request for the method "operations.cancel".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Cancel#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, operation id) of the operation to cancel. Specified in the format
* `projects/locations/operations`.
* @param content the {@link com.google.api.services.container.v1beta1.model.CancelOperationRequest}
* @return the request
*/
public Cancel cancel(java.lang.String name, com.google.api.services.container.v1beta1.model.CancelOperationRequest content) throws java.io.IOException {
Cancel result = new Cancel(name, content);
initialize(result);
return result;
}
public class Cancel extends ContainerRequest<com.google.api.services.container.v1beta1.model.Empty> {
private static final String REST_PATH = "v1beta1/{+name}:cancel";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/operations/[^/]+$");
/**
* Cancels the specified operation.
*
* Create a request for the method "operations.cancel".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Cancel#execute()} method to invoke the remote operation.
* <p> {@link
* Cancel#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, operation id) of the operation to cancel. Specified in the format
* `projects/locations/operations`.
* @param content the {@link com.google.api.services.container.v1beta1.model.CancelOperationRequest}
* @since 1.13
*/
protected Cancel(java.lang.String name, com.google.api.services.container.v1beta1.model.CancelOperationRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Empty.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/operations/[^/]+$");
}
}
@Override
public Cancel set$Xgafv(java.lang.String $Xgafv) {
return (Cancel) super.set$Xgafv($Xgafv);
}
@Override
public Cancel setAccessToken(java.lang.String accessToken) {
return (Cancel) super.setAccessToken(accessToken);
}
@Override
public Cancel setAlt(java.lang.String alt) {
return (Cancel) super.setAlt(alt);
}
@Override
public Cancel setCallback(java.lang.String callback) {
return (Cancel) super.setCallback(callback);
}
@Override
public Cancel setFields(java.lang.String fields) {
return (Cancel) super.setFields(fields);
}
@Override
public Cancel setKey(java.lang.String key) {
return (Cancel) super.setKey(key);
}
@Override
public Cancel setOauthToken(java.lang.String oauthToken) {
return (Cancel) super.setOauthToken(oauthToken);
}
@Override
public Cancel setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Cancel) super.setPrettyPrint(prettyPrint);
}
@Override
public Cancel setQuotaUser(java.lang.String quotaUser) {
return (Cancel) super.setQuotaUser(quotaUser);
}
@Override
public Cancel setUploadType(java.lang.String uploadType) {
return (Cancel) super.setUploadType(uploadType);
}
@Override
public Cancel setUploadProtocol(java.lang.String uploadProtocol) {
return (Cancel) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, operation id) of the operation to cancel. Specified in the
* format `projects/locations/operations`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, operation id) of the operation to cancel. Specified in the format
`projects/locations/operations`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, operation id) of the operation to cancel. Specified in the
* format `projects/locations/operations`.
*/
public Cancel setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/operations/[^/]+$");
}
this.name = name;
return this;
}
@Override
public Cancel set(String parameterName, Object value) {
return (Cancel) super.set(parameterName, value);
}
}
/**
* Gets the specified operation.
*
* Create a request for the method "operations.get".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param name The name (project, location, operation id) of the operation to get. Specified in the format
* `projects/locations/operations`.
* @return the request
*/
public Get get(java.lang.String name) throws java.io.IOException {
Get result = new Get(name);
initialize(result);
return result;
}
public class Get extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/operations/[^/]+$");
/**
* Gets the specified operation.
*
* Create a request for the method "operations.get".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p>
* {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The name (project, location, operation id) of the operation to get. Specified in the format
* `projects/locations/operations`.
* @since 1.13
*/
protected Get(java.lang.String name) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.Operation.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/operations/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/**
* The name (project, location, operation id) of the operation to get. Specified in the
* format `projects/locations/operations`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, operation id) of the operation to get. Specified in the format
`projects/locations/operations`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, operation id) of the operation to get. Specified in the
* format `projects/locations/operations`.
*/
public Get setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+/operations/[^/]+$");
}
this.name = name;
return this;
}
/**
* Required. Deprecated. The server-assigned `name` of the operation. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String operationId;
/** Required. Deprecated. The server-assigned `name` of the operation. This field has been deprecated
and replaced by the name field.
*/
public java.lang.String getOperationId() {
return operationId;
}
/**
* Required. Deprecated. The server-assigned `name` of the operation. This field has been
* deprecated and replaced by the name field.
*/
public Get setOperationId(java.lang.String operationId) {
this.operationId = operationId;
return this;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Get setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Lists all operations in a project in the specified zone or all zones.
*
* Create a request for the method "operations.list".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param parent The parent (project and location) where the operations will be listed. Specified in the format
* `projects/locations`. Location "-" matches all zones and all regions.
* @return the request
*/
public List list(java.lang.String parent) throws java.io.IOException {
List result = new List(parent);
initialize(result);
return result;
}
public class List extends ContainerRequest<com.google.api.services.container.v1beta1.model.ListOperationsResponse> {
private static final String REST_PATH = "v1beta1/{+parent}/operations";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$");
/**
* Lists all operations in a project in the specified zone or all zones.
*
* Create a request for the method "operations.list".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p>
* {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param parent The parent (project and location) where the operations will be listed. Specified in the format
* `projects/locations`. Location "-" matches all zones and all regions.
* @since 1.13
*/
protected List(java.lang.String parent) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.ListOperationsResponse.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
/**
* The parent (project and location) where the operations will be listed. Specified in the
* format `projects/locations`. Location "-" matches all zones and all regions.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** The parent (project and location) where the operations will be listed. Specified in the format
`projects/locations`. Location "-" matches all zones and all regions.
*/
public java.lang.String getParent() {
return parent;
}
/**
* The parent (project and location) where the operations will be listed. Specified in the
* format `projects/locations`. Location "-" matches all zones and all regions.
*/
public List setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+/locations/[^/]+$");
}
this.parent = parent;
return this;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the parent field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the parent field.
*/
public List setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for,
* or `-` for all zones. This field has been deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) to return operations for, or `-` for
all zones. This field has been deprecated and replaced by the parent field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for,
* or `-` for all zones. This field has been deprecated and replaced by the parent field.
*/
public List setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
}
}
/**
* An accessor for creating requests from the Zones collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.Zones.List request = container.zones().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Zones zones() {
return new Zones();
}
/**
* The "zones" collection of methods.
*/
public class Zones {
/**
* Returns configuration info about the Google Kubernetes Engine service.
*
* Create a request for the method "zones.getServerconfig".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link GetServerconfig#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for.
* This field has been deprecated and replaced by the name field.
* @return the request
*/
public GetServerconfig getServerconfig(java.lang.String projectId, java.lang.String zone) throws java.io.IOException {
GetServerconfig result = new GetServerconfig(projectId, zone);
initialize(result);
return result;
}
public class GetServerconfig extends ContainerRequest<com.google.api.services.container.v1beta1.model.ServerConfig> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/serverconfig";
/**
* Returns configuration info about the Google Kubernetes Engine service.
*
* Create a request for the method "zones.getServerconfig".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link GetServerconfig#execute()} method to invoke the remote
* operation. <p> {@link GetServerconfig#initialize(com.google.api.client.googleapis.services.Abst
* ractGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for.
* This field has been deprecated and replaced by the name field.
* @since 1.13
*/
protected GetServerconfig(java.lang.String projectId, java.lang.String zone) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.ServerConfig.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public GetServerconfig set$Xgafv(java.lang.String $Xgafv) {
return (GetServerconfig) super.set$Xgafv($Xgafv);
}
@Override
public GetServerconfig setAccessToken(java.lang.String accessToken) {
return (GetServerconfig) super.setAccessToken(accessToken);
}
@Override
public GetServerconfig setAlt(java.lang.String alt) {
return (GetServerconfig) super.setAlt(alt);
}
@Override
public GetServerconfig setCallback(java.lang.String callback) {
return (GetServerconfig) super.setCallback(callback);
}
@Override
public GetServerconfig setFields(java.lang.String fields) {
return (GetServerconfig) super.setFields(fields);
}
@Override
public GetServerconfig setKey(java.lang.String key) {
return (GetServerconfig) super.setKey(key);
}
@Override
public GetServerconfig setOauthToken(java.lang.String oauthToken) {
return (GetServerconfig) super.setOauthToken(oauthToken);
}
@Override
public GetServerconfig setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetServerconfig) super.setPrettyPrint(prettyPrint);
}
@Override
public GetServerconfig setQuotaUser(java.lang.String quotaUser) {
return (GetServerconfig) super.setQuotaUser(quotaUser);
}
@Override
public GetServerconfig setUploadType(java.lang.String uploadType) {
return (GetServerconfig) super.setUploadType(uploadType);
}
@Override
public GetServerconfig setUploadProtocol(java.lang.String uploadProtocol) {
return (GetServerconfig) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
*/
public GetServerconfig setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for.
* This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) to return operations for. This field
has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for.
* This field has been deprecated and replaced by the name field.
*/
public GetServerconfig setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* The name (project and location) of the server config to get, specified in the format
* `projects/locations`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project and location) of the server config to get, specified in the format
`projects/locations`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project and location) of the server config to get, specified in the format
* `projects/locations`.
*/
public GetServerconfig setName(java.lang.String name) {
this.name = name;
return this;
}
@Override
public GetServerconfig set(String parameterName, Object value) {
return (GetServerconfig) super.set(parameterName, value);
}
}
/**
* An accessor for creating requests from the Clusters collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.Clusters.List request = container.clusters().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Clusters clusters() {
return new Clusters();
}
/**
* The "clusters" collection of methods.
*/
public class Clusters {
/**
* Sets the addons for a specific cluster.
*
* Create a request for the method "clusters.addons".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Addons#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetAddonsConfigRequest}
* @return the request
*/
public Addons addons(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetAddonsConfigRequest content) throws java.io.IOException {
Addons result = new Addons(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class Addons extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/addons";
/**
* Sets the addons for a specific cluster.
*
* Create a request for the method "clusters.addons".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Addons#execute()} method to invoke the remote operation.
* <p> {@link
* Addons#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetAddonsConfigRequest}
* @since 1.13
*/
protected Addons(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetAddonsConfigRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public Addons set$Xgafv(java.lang.String $Xgafv) {
return (Addons) super.set$Xgafv($Xgafv);
}
@Override
public Addons setAccessToken(java.lang.String accessToken) {
return (Addons) super.setAccessToken(accessToken);
}
@Override
public Addons setAlt(java.lang.String alt) {
return (Addons) super.setAlt(alt);
}
@Override
public Addons setCallback(java.lang.String callback) {
return (Addons) super.setCallback(callback);
}
@Override
public Addons setFields(java.lang.String fields) {
return (Addons) super.setFields(fields);
}
@Override
public Addons setKey(java.lang.String key) {
return (Addons) super.setKey(key);
}
@Override
public Addons setOauthToken(java.lang.String oauthToken) {
return (Addons) super.setOauthToken(oauthToken);
}
@Override
public Addons setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Addons) super.setPrettyPrint(prettyPrint);
}
@Override
public Addons setQuotaUser(java.lang.String quotaUser) {
return (Addons) super.setQuotaUser(quotaUser);
}
@Override
public Addons setUploadType(java.lang.String uploadType) {
return (Addons) super.setUploadType(uploadType);
}
@Override
public Addons setUploadProtocol(java.lang.String uploadProtocol) {
return (Addons) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Addons setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Addons setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
public Addons setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public Addons set(String parameterName, Object value) {
return (Addons) super.set(parameterName, value);
}
}
/**
* Completes master IP rotation.
*
* Create a request for the method "clusters.completeIpRotation".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link CompleteIpRotation#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.CompleteIPRotationRequest}
* @return the request
*/
public CompleteIpRotation completeIpRotation(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.CompleteIPRotationRequest content) throws java.io.IOException {
CompleteIpRotation result = new CompleteIpRotation(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class CompleteIpRotation extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}:completeIpRotation";
/**
* Completes master IP rotation.
*
* Create a request for the method "clusters.completeIpRotation".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link CompleteIpRotation#execute()} method to invoke the remote
* operation. <p> {@link CompleteIpRotation#initialize(com.google.api.client.googleapis.services.A
* bstractGoogleClientRequest)} must be called to initialize this instance immediately after
* invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.CompleteIPRotationRequest}
* @since 1.13
*/
protected CompleteIpRotation(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.CompleteIPRotationRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public CompleteIpRotation set$Xgafv(java.lang.String $Xgafv) {
return (CompleteIpRotation) super.set$Xgafv($Xgafv);
}
@Override
public CompleteIpRotation setAccessToken(java.lang.String accessToken) {
return (CompleteIpRotation) super.setAccessToken(accessToken);
}
@Override
public CompleteIpRotation setAlt(java.lang.String alt) {
return (CompleteIpRotation) super.setAlt(alt);
}
@Override
public CompleteIpRotation setCallback(java.lang.String callback) {
return (CompleteIpRotation) super.setCallback(callback);
}
@Override
public CompleteIpRotation setFields(java.lang.String fields) {
return (CompleteIpRotation) super.setFields(fields);
}
@Override
public CompleteIpRotation setKey(java.lang.String key) {
return (CompleteIpRotation) super.setKey(key);
}
@Override
public CompleteIpRotation setOauthToken(java.lang.String oauthToken) {
return (CompleteIpRotation) super.setOauthToken(oauthToken);
}
@Override
public CompleteIpRotation setPrettyPrint(java.lang.Boolean prettyPrint) {
return (CompleteIpRotation) super.setPrettyPrint(prettyPrint);
}
@Override
public CompleteIpRotation setQuotaUser(java.lang.String quotaUser) {
return (CompleteIpRotation) super.setQuotaUser(quotaUser);
}
@Override
public CompleteIpRotation setUploadType(java.lang.String uploadType) {
return (CompleteIpRotation) super.setUploadType(uploadType);
}
@Override
public CompleteIpRotation setUploadProtocol(java.lang.String uploadProtocol) {
return (CompleteIpRotation) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://developers.google.com/console/help/new/#projectnumber). This field has been
deprecated and replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
*/
public CompleteIpRotation setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public CompleteIpRotation setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
public CompleteIpRotation setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public CompleteIpRotation set(String parameterName, Object value) {
return (CompleteIpRotation) super.set(parameterName, value);
}
}
/**
* Creates a cluster, consisting of the specified number and type of Google Compute Engine
* instances. By default, the cluster is created in the project's [default
* network](https://cloud.google.com/compute/docs/networks-and-firewalls#networks). One firewall is
* added for the cluster. After cluster creation, the Kubelet creates routes for each node to allow
* the containers on that node to communicate with all other instances in the cluster. Finally, an
* entry is added to the project's global metadata indicating which CIDR range the cluster is using.
*
* Create a request for the method "clusters.create".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the parent field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
* @param content the {@link com.google.api.services.container.v1beta1.model.CreateClusterRequest}
* @return the request
*/
public Create create(java.lang.String projectId, java.lang.String zone, com.google.api.services.container.v1beta1.model.CreateClusterRequest content) throws java.io.IOException {
Create result = new Create(projectId, zone, content);
initialize(result);
return result;
}
public class Create extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters";
/**
* Creates a cluster, consisting of the specified number and type of Google Compute Engine
* instances. By default, the cluster is created in the project's [default
* network](https://cloud.google.com/compute/docs/networks-and-firewalls#networks). One firewall
* is added for the cluster. After cluster creation, the Kubelet creates routes for each node to
* allow the containers on that node to communicate with all other instances in the cluster.
* Finally, an entry is added to the project's global metadata indicating which CIDR range the
* cluster is using.
*
* Create a request for the method "clusters.create".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Create#execute()} method to invoke the remote operation.
* <p> {@link
* Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the parent field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
* @param content the {@link com.google.api.services.container.v1beta1.model.CreateClusterRequest}
* @since 1.13
*/
protected Create(java.lang.String projectId, java.lang.String zone, com.google.api.services.container.v1beta1.model.CreateClusterRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
}
@Override
public Create set$Xgafv(java.lang.String $Xgafv) {
return (Create) super.set$Xgafv($Xgafv);
}
@Override
public Create setAccessToken(java.lang.String accessToken) {
return (Create) super.setAccessToken(accessToken);
}
@Override
public Create setAlt(java.lang.String alt) {
return (Create) super.setAlt(alt);
}
@Override
public Create setCallback(java.lang.String callback) {
return (Create) super.setCallback(callback);
}
@Override
public Create setFields(java.lang.String fields) {
return (Create) super.setFields(fields);
}
@Override
public Create setKey(java.lang.String key) {
return (Create) super.setKey(key);
}
@Override
public Create setOauthToken(java.lang.String oauthToken) {
return (Create) super.setOauthToken(oauthToken);
}
@Override
public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Create) super.setPrettyPrint(prettyPrint);
}
@Override
public Create setQuotaUser(java.lang.String quotaUser) {
return (Create) super.setQuotaUser(quotaUser);
}
@Override
public Create setUploadType(java.lang.String uploadType) {
return (Create) super.setUploadType(uploadType);
}
@Override
public Create setUploadProtocol(java.lang.String uploadProtocol) {
return (Create) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the parent field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the parent field.
*/
public Create setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the parent field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
*/
public Create setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
@Override
public Create set(String parameterName, Object value) {
return (Create) super.set(parameterName, value);
}
}
/**
* Deletes the cluster, including the Kubernetes endpoint and all worker nodes. Firewalls and routes
* that were configured during cluster creation are also deleted. Other Google Compute Engine
* resources that might be in use by the cluster, such as load balancer resources, are not deleted
* if they weren't present when the cluster was initially created.
*
* Create a request for the method "clusters.delete".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Delete#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to delete. This field has been deprecated and replaced
* by the name field.
* @return the request
*/
public Delete delete(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId) throws java.io.IOException {
Delete result = new Delete(projectId, zone, clusterId);
initialize(result);
return result;
}
public class Delete extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}";
/**
* Deletes the cluster, including the Kubernetes endpoint and all worker nodes. Firewalls and
* routes that were configured during cluster creation are also deleted. Other Google Compute
* Engine resources that might be in use by the cluster, such as load balancer resources, are not
* deleted if they weren't present when the cluster was initially created.
*
* Create a request for the method "clusters.delete".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Delete#execute()} method to invoke the remote operation.
* <p> {@link
* Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to delete. This field has been deprecated and replaced
* by the name field.
* @since 1.13
*/
protected Delete(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId) {
super(Container.this, "DELETE", REST_PATH, null, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public Delete set$Xgafv(java.lang.String $Xgafv) {
return (Delete) super.set$Xgafv($Xgafv);
}
@Override
public Delete setAccessToken(java.lang.String accessToken) {
return (Delete) super.setAccessToken(accessToken);
}
@Override
public Delete setAlt(java.lang.String alt) {
return (Delete) super.setAlt(alt);
}
@Override
public Delete setCallback(java.lang.String callback) {
return (Delete) super.setCallback(callback);
}
@Override
public Delete setFields(java.lang.String fields) {
return (Delete) super.setFields(fields);
}
@Override
public Delete setKey(java.lang.String key) {
return (Delete) super.setKey(key);
}
@Override
public Delete setOauthToken(java.lang.String oauthToken) {
return (Delete) super.setOauthToken(oauthToken);
}
@Override
public Delete setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Delete) super.setPrettyPrint(prettyPrint);
}
@Override
public Delete setQuotaUser(java.lang.String quotaUser) {
return (Delete) super.setQuotaUser(quotaUser);
}
@Override
public Delete setUploadType(java.lang.String uploadType) {
return (Delete) super.setUploadType(uploadType);
}
@Override
public Delete setUploadProtocol(java.lang.String uploadProtocol) {
return (Delete) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Delete setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Delete setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to delete. This field has been deprecated
* and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to delete. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to delete. This field has been deprecated
* and replaced by the name field.
*/
public Delete setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* The name (project, location, cluster) of the cluster to delete. Specified in the format
* `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster) of the cluster to delete. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster) of the cluster to delete. Specified in the format
* `projects/locations/clusters`.
*/
public Delete setName(java.lang.String name) {
this.name = name;
return this;
}
@Override
public Delete set(String parameterName, Object value) {
return (Delete) super.set(parameterName, value);
}
}
/**
* Gets the details for a specific cluster.
*
* Create a request for the method "clusters.get".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to retrieve. This field has been deprecated and
* replaced by the name field.
* @return the request
*/
public Get get(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId) throws java.io.IOException {
Get result = new Get(projectId, zone, clusterId);
initialize(result);
return result;
}
public class Get extends ContainerRequest<com.google.api.services.container.v1beta1.model.Cluster> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}";
/**
* Gets the details for a specific cluster.
*
* Create a request for the method "clusters.get".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p>
* {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to retrieve. This field has been deprecated and
* replaced by the name field.
* @since 1.13
*/
protected Get(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.Cluster.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Get setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to retrieve. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to retrieve. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to retrieve. This field has been
* deprecated and replaced by the name field.
*/
public Get setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* The name (project, location, cluster) of the cluster to retrieve. Specified in the
* format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster) of the cluster to retrieve. Specified in the format
`projects/locations/clusters`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster) of the cluster to retrieve. Specified in the
* format `projects/locations/clusters`.
*/
public Get setName(java.lang.String name) {
this.name = name;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Enables or disables the ABAC authorization mechanism on a cluster.
*
* Create a request for the method "clusters.legacyAbac".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link LegacyAbac#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to update. This field has been deprecated and replaced
* by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLegacyAbacRequest}
* @return the request
*/
public LegacyAbac legacyAbac(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetLegacyAbacRequest content) throws java.io.IOException {
LegacyAbac result = new LegacyAbac(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class LegacyAbac extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/legacyAbac";
/**
* Enables or disables the ABAC authorization mechanism on a cluster.
*
* Create a request for the method "clusters.legacyAbac".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link LegacyAbac#execute()} method to invoke the remote
* operation. <p> {@link
* LegacyAbac#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to update. This field has been deprecated and replaced
* by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLegacyAbacRequest}
* @since 1.13
*/
protected LegacyAbac(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetLegacyAbacRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public LegacyAbac set$Xgafv(java.lang.String $Xgafv) {
return (LegacyAbac) super.set$Xgafv($Xgafv);
}
@Override
public LegacyAbac setAccessToken(java.lang.String accessToken) {
return (LegacyAbac) super.setAccessToken(accessToken);
}
@Override
public LegacyAbac setAlt(java.lang.String alt) {
return (LegacyAbac) super.setAlt(alt);
}
@Override
public LegacyAbac setCallback(java.lang.String callback) {
return (LegacyAbac) super.setCallback(callback);
}
@Override
public LegacyAbac setFields(java.lang.String fields) {
return (LegacyAbac) super.setFields(fields);
}
@Override
public LegacyAbac setKey(java.lang.String key) {
return (LegacyAbac) super.setKey(key);
}
@Override
public LegacyAbac setOauthToken(java.lang.String oauthToken) {
return (LegacyAbac) super.setOauthToken(oauthToken);
}
@Override
public LegacyAbac setPrettyPrint(java.lang.Boolean prettyPrint) {
return (LegacyAbac) super.setPrettyPrint(prettyPrint);
}
@Override
public LegacyAbac setQuotaUser(java.lang.String quotaUser) {
return (LegacyAbac) super.setQuotaUser(quotaUser);
}
@Override
public LegacyAbac setUploadType(java.lang.String uploadType) {
return (LegacyAbac) super.setUploadType(uploadType);
}
@Override
public LegacyAbac setUploadProtocol(java.lang.String uploadProtocol) {
return (LegacyAbac) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public LegacyAbac setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public LegacyAbac setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to update. This field has been deprecated
* and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to update. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to update. This field has been deprecated
* and replaced by the name field.
*/
public LegacyAbac setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public LegacyAbac set(String parameterName, Object value) {
return (LegacyAbac) super.set(parameterName, value);
}
}
/**
* Lists all clusters owned by a project in either the specified zone or all zones.
*
* Create a request for the method "clusters.list".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the parent field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides, or "-" for all zones. This field has been deprecated and replaced by the parent
* field.
* @return the request
*/
public List list(java.lang.String projectId, java.lang.String zone) throws java.io.IOException {
List result = new List(projectId, zone);
initialize(result);
return result;
}
public class List extends ContainerRequest<com.google.api.services.container.v1beta1.model.ListClustersResponse> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters";
/**
* Lists all clusters owned by a project in either the specified zone or all zones.
*
* Create a request for the method "clusters.list".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p>
* {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the parent field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides, or "-" for all zones. This field has been deprecated and replaced by the parent
* field.
* @since 1.13
*/
protected List(java.lang.String projectId, java.lang.String zone) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.ListClustersResponse.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the parent field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the parent field.
*/
public List setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides, or "-" for all zones. This field has been deprecated and replaced by the
* parent field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides, or "-"
for all zones. This field has been deprecated and replaced by the parent field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides, or "-" for all zones. This field has been deprecated and replaced by the
* parent field.
*/
public List setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* The parent (project and location) where the clusters will be listed. Specified in the
* format `projects/locations`. Location "-" matches all zones and all regions.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** The parent (project and location) where the clusters will be listed. Specified in the format
`projects/locations`. Location "-" matches all zones and all regions.
*/
public java.lang.String getParent() {
return parent;
}
/**
* The parent (project and location) where the clusters will be listed. Specified in the
* format `projects/locations`. Location "-" matches all zones and all regions.
*/
public List setParent(java.lang.String parent) {
this.parent = parent;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
/**
* Sets the locations for a specific cluster. Deprecated. Use
* [projects.locations.clusters.update](https://cloud.google.com/kubernetes-
* engine/docs/reference/rest/v1beta1/projects.locations.clusters/update) instead.
*
* Create a request for the method "clusters.locations".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Locations#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLocationsRequest}
* @return the request
*/
public Locations locations(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetLocationsRequest content) throws java.io.IOException {
Locations result = new Locations(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class Locations extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/locations";
/**
* Sets the locations for a specific cluster. Deprecated. Use
* [projects.locations.clusters.update](https://cloud.google.com/kubernetes-
* engine/docs/reference/rest/v1beta1/projects.locations.clusters/update) instead.
*
* Create a request for the method "clusters.locations".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Locations#execute()} method to invoke the remote
* operation. <p> {@link
* Locations#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLocationsRequest}
* @since 1.13
*/
protected Locations(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetLocationsRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public Locations set$Xgafv(java.lang.String $Xgafv) {
return (Locations) super.set$Xgafv($Xgafv);
}
@Override
public Locations setAccessToken(java.lang.String accessToken) {
return (Locations) super.setAccessToken(accessToken);
}
@Override
public Locations setAlt(java.lang.String alt) {
return (Locations) super.setAlt(alt);
}
@Override
public Locations setCallback(java.lang.String callback) {
return (Locations) super.setCallback(callback);
}
@Override
public Locations setFields(java.lang.String fields) {
return (Locations) super.setFields(fields);
}
@Override
public Locations setKey(java.lang.String key) {
return (Locations) super.setKey(key);
}
@Override
public Locations setOauthToken(java.lang.String oauthToken) {
return (Locations) super.setOauthToken(oauthToken);
}
@Override
public Locations setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Locations) super.setPrettyPrint(prettyPrint);
}
@Override
public Locations setQuotaUser(java.lang.String quotaUser) {
return (Locations) super.setQuotaUser(quotaUser);
}
@Override
public Locations setUploadType(java.lang.String uploadType) {
return (Locations) super.setUploadType(uploadType);
}
@Override
public Locations setUploadProtocol(java.lang.String uploadProtocol) {
return (Locations) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Locations setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Locations setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
public Locations setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public Locations set(String parameterName, Object value) {
return (Locations) super.set(parameterName, value);
}
}
/**
* Sets the logging service for a specific cluster.
*
* Create a request for the method "clusters.logging".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Logging#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLoggingServiceRequest}
* @return the request
*/
public Logging logging(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetLoggingServiceRequest content) throws java.io.IOException {
Logging result = new Logging(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class Logging extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/logging";
/**
* Sets the logging service for a specific cluster.
*
* Create a request for the method "clusters.logging".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Logging#execute()} method to invoke the remote operation.
* <p> {@link
* Logging#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLoggingServiceRequest}
* @since 1.13
*/
protected Logging(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetLoggingServiceRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public Logging set$Xgafv(java.lang.String $Xgafv) {
return (Logging) super.set$Xgafv($Xgafv);
}
@Override
public Logging setAccessToken(java.lang.String accessToken) {
return (Logging) super.setAccessToken(accessToken);
}
@Override
public Logging setAlt(java.lang.String alt) {
return (Logging) super.setAlt(alt);
}
@Override
public Logging setCallback(java.lang.String callback) {
return (Logging) super.setCallback(callback);
}
@Override
public Logging setFields(java.lang.String fields) {
return (Logging) super.setFields(fields);
}
@Override
public Logging setKey(java.lang.String key) {
return (Logging) super.setKey(key);
}
@Override
public Logging setOauthToken(java.lang.String oauthToken) {
return (Logging) super.setOauthToken(oauthToken);
}
@Override
public Logging setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Logging) super.setPrettyPrint(prettyPrint);
}
@Override
public Logging setQuotaUser(java.lang.String quotaUser) {
return (Logging) super.setQuotaUser(quotaUser);
}
@Override
public Logging setUploadType(java.lang.String uploadType) {
return (Logging) super.setUploadType(uploadType);
}
@Override
public Logging setUploadProtocol(java.lang.String uploadProtocol) {
return (Logging) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Logging setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Logging setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
public Logging setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public Logging set(String parameterName, Object value) {
return (Logging) super.set(parameterName, value);
}
}
/**
* Updates the master for a specific cluster.
*
* Create a request for the method "clusters.master".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Master#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateMasterRequest}
* @return the request
*/
public Master master(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.UpdateMasterRequest content) throws java.io.IOException {
Master result = new Master(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class Master extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/master";
/**
* Updates the master for a specific cluster.
*
* Create a request for the method "clusters.master".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Master#execute()} method to invoke the remote operation.
* <p> {@link
* Master#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateMasterRequest}
* @since 1.13
*/
protected Master(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.UpdateMasterRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public Master set$Xgafv(java.lang.String $Xgafv) {
return (Master) super.set$Xgafv($Xgafv);
}
@Override
public Master setAccessToken(java.lang.String accessToken) {
return (Master) super.setAccessToken(accessToken);
}
@Override
public Master setAlt(java.lang.String alt) {
return (Master) super.setAlt(alt);
}
@Override
public Master setCallback(java.lang.String callback) {
return (Master) super.setCallback(callback);
}
@Override
public Master setFields(java.lang.String fields) {
return (Master) super.setFields(fields);
}
@Override
public Master setKey(java.lang.String key) {
return (Master) super.setKey(key);
}
@Override
public Master setOauthToken(java.lang.String oauthToken) {
return (Master) super.setOauthToken(oauthToken);
}
@Override
public Master setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Master) super.setPrettyPrint(prettyPrint);
}
@Override
public Master setQuotaUser(java.lang.String quotaUser) {
return (Master) super.setQuotaUser(quotaUser);
}
@Override
public Master setUploadType(java.lang.String uploadType) {
return (Master) super.setUploadType(uploadType);
}
@Override
public Master setUploadProtocol(java.lang.String uploadProtocol) {
return (Master) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Master setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Master setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
public Master setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public Master set(String parameterName, Object value) {
return (Master) super.set(parameterName, value);
}
}
/**
* Sets the monitoring service for a specific cluster.
*
* Create a request for the method "clusters.monitoring".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Monitoring#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMonitoringServiceRequest}
* @return the request
*/
public Monitoring monitoring(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetMonitoringServiceRequest content) throws java.io.IOException {
Monitoring result = new Monitoring(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class Monitoring extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/monitoring";
/**
* Sets the monitoring service for a specific cluster.
*
* Create a request for the method "clusters.monitoring".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Monitoring#execute()} method to invoke the remote
* operation. <p> {@link
* Monitoring#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMonitoringServiceRequest}
* @since 1.13
*/
protected Monitoring(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetMonitoringServiceRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public Monitoring set$Xgafv(java.lang.String $Xgafv) {
return (Monitoring) super.set$Xgafv($Xgafv);
}
@Override
public Monitoring setAccessToken(java.lang.String accessToken) {
return (Monitoring) super.setAccessToken(accessToken);
}
@Override
public Monitoring setAlt(java.lang.String alt) {
return (Monitoring) super.setAlt(alt);
}
@Override
public Monitoring setCallback(java.lang.String callback) {
return (Monitoring) super.setCallback(callback);
}
@Override
public Monitoring setFields(java.lang.String fields) {
return (Monitoring) super.setFields(fields);
}
@Override
public Monitoring setKey(java.lang.String key) {
return (Monitoring) super.setKey(key);
}
@Override
public Monitoring setOauthToken(java.lang.String oauthToken) {
return (Monitoring) super.setOauthToken(oauthToken);
}
@Override
public Monitoring setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Monitoring) super.setPrettyPrint(prettyPrint);
}
@Override
public Monitoring setQuotaUser(java.lang.String quotaUser) {
return (Monitoring) super.setQuotaUser(quotaUser);
}
@Override
public Monitoring setUploadType(java.lang.String uploadType) {
return (Monitoring) super.setUploadType(uploadType);
}
@Override
public Monitoring setUploadProtocol(java.lang.String uploadProtocol) {
return (Monitoring) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Monitoring setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Monitoring setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
public Monitoring setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public Monitoring set(String parameterName, Object value) {
return (Monitoring) super.set(parameterName, value);
}
}
/**
* Sets labels on a cluster.
*
* Create a request for the method "clusters.resourceLabels".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link ResourceLabels#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLabelsRequest}
* @return the request
*/
public ResourceLabels resourceLabels(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetLabelsRequest content) throws java.io.IOException {
ResourceLabels result = new ResourceLabels(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class ResourceLabels extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/resourceLabels";
/**
* Sets labels on a cluster.
*
* Create a request for the method "clusters.resourceLabels".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link ResourceLabels#execute()} method to invoke the remote
* operation. <p> {@link ResourceLabels#initialize(com.google.api.client.googleapis.services.Abstr
* actGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetLabelsRequest}
* @since 1.13
*/
protected ResourceLabels(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetLabelsRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public ResourceLabels set$Xgafv(java.lang.String $Xgafv) {
return (ResourceLabels) super.set$Xgafv($Xgafv);
}
@Override
public ResourceLabels setAccessToken(java.lang.String accessToken) {
return (ResourceLabels) super.setAccessToken(accessToken);
}
@Override
public ResourceLabels setAlt(java.lang.String alt) {
return (ResourceLabels) super.setAlt(alt);
}
@Override
public ResourceLabels setCallback(java.lang.String callback) {
return (ResourceLabels) super.setCallback(callback);
}
@Override
public ResourceLabels setFields(java.lang.String fields) {
return (ResourceLabels) super.setFields(fields);
}
@Override
public ResourceLabels setKey(java.lang.String key) {
return (ResourceLabels) super.setKey(key);
}
@Override
public ResourceLabels setOauthToken(java.lang.String oauthToken) {
return (ResourceLabels) super.setOauthToken(oauthToken);
}
@Override
public ResourceLabels setPrettyPrint(java.lang.Boolean prettyPrint) {
return (ResourceLabels) super.setPrettyPrint(prettyPrint);
}
@Override
public ResourceLabels setQuotaUser(java.lang.String quotaUser) {
return (ResourceLabels) super.setQuotaUser(quotaUser);
}
@Override
public ResourceLabels setUploadType(java.lang.String uploadType) {
return (ResourceLabels) super.setUploadType(uploadType);
}
@Override
public ResourceLabels setUploadProtocol(java.lang.String uploadProtocol) {
return (ResourceLabels) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://developers.google.com/console/help/new/#projectnumber). This field has been
deprecated and replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
*/
public ResourceLabels setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public ResourceLabels setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
public ResourceLabels setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public ResourceLabels set(String parameterName, Object value) {
return (ResourceLabels) super.set(parameterName, value);
}
}
/**
* Sets the maintenance policy for a cluster.
*
* Create a request for the method "clusters.setMaintenancePolicy".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetMaintenancePolicy#execute()} method to invoke the remote
* operation.
*
* @param projectId Required. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840).
* @param zone Required. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides.
* @param clusterId Required. The name of the cluster to update.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMaintenancePolicyRequest}
* @return the request
*/
public SetMaintenancePolicy setMaintenancePolicy(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetMaintenancePolicyRequest content) throws java.io.IOException {
SetMaintenancePolicy result = new SetMaintenancePolicy(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class SetMaintenancePolicy extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}:setMaintenancePolicy";
/**
* Sets the maintenance policy for a cluster.
*
* Create a request for the method "clusters.setMaintenancePolicy".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetMaintenancePolicy#execute()} method to invoke the
* remote operation. <p> {@link SetMaintenancePolicy#initialize(com.google.api.client.googleapis.s
* ervices.AbstractGoogleClientRequest)} must be called to initialize this instance immediately
* after invoking the constructor. </p>
*
* @param projectId Required. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840).
* @param zone Required. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides.
* @param clusterId Required. The name of the cluster to update.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMaintenancePolicyRequest}
* @since 1.13
*/
protected SetMaintenancePolicy(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetMaintenancePolicyRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public SetMaintenancePolicy set$Xgafv(java.lang.String $Xgafv) {
return (SetMaintenancePolicy) super.set$Xgafv($Xgafv);
}
@Override
public SetMaintenancePolicy setAccessToken(java.lang.String accessToken) {
return (SetMaintenancePolicy) super.setAccessToken(accessToken);
}
@Override
public SetMaintenancePolicy setAlt(java.lang.String alt) {
return (SetMaintenancePolicy) super.setAlt(alt);
}
@Override
public SetMaintenancePolicy setCallback(java.lang.String callback) {
return (SetMaintenancePolicy) super.setCallback(callback);
}
@Override
public SetMaintenancePolicy setFields(java.lang.String fields) {
return (SetMaintenancePolicy) super.setFields(fields);
}
@Override
public SetMaintenancePolicy setKey(java.lang.String key) {
return (SetMaintenancePolicy) super.setKey(key);
}
@Override
public SetMaintenancePolicy setOauthToken(java.lang.String oauthToken) {
return (SetMaintenancePolicy) super.setOauthToken(oauthToken);
}
@Override
public SetMaintenancePolicy setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetMaintenancePolicy) super.setPrettyPrint(prettyPrint);
}
@Override
public SetMaintenancePolicy setQuotaUser(java.lang.String quotaUser) {
return (SetMaintenancePolicy) super.setQuotaUser(quotaUser);
}
@Override
public SetMaintenancePolicy setUploadType(java.lang.String uploadType) {
return (SetMaintenancePolicy) super.setUploadType(uploadType);
}
@Override
public SetMaintenancePolicy setUploadProtocol(java.lang.String uploadProtocol) {
return (SetMaintenancePolicy) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840).
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840).
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840).
*/
public SetMaintenancePolicy setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides.
*/
public SetMaintenancePolicy setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/** Required. The name of the cluster to update. */
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. The name of the cluster to update.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/** Required. The name of the cluster to update. */
public SetMaintenancePolicy setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public SetMaintenancePolicy set(String parameterName, Object value) {
return (SetMaintenancePolicy) super.set(parameterName, value);
}
}
/**
* Sets master auth materials. Currently supports changing the admin password or a specific cluster,
* either via password generation or explicitly setting the password.
*
* Create a request for the method "clusters.setMasterAuth".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetMasterAuth#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMasterAuthRequest}
* @return the request
*/
public SetMasterAuth setMasterAuth(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetMasterAuthRequest content) throws java.io.IOException {
SetMasterAuth result = new SetMasterAuth(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class SetMasterAuth extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}:setMasterAuth";
/**
* Sets master auth materials. Currently supports changing the admin password or a specific
* cluster, either via password generation or explicitly setting the password.
*
* Create a request for the method "clusters.setMasterAuth".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetMasterAuth#execute()} method to invoke the remote
* operation. <p> {@link SetMasterAuth#initialize(com.google.api.client.googleapis.services.Abstra
* ctGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetMasterAuthRequest}
* @since 1.13
*/
protected SetMasterAuth(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetMasterAuthRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public SetMasterAuth set$Xgafv(java.lang.String $Xgafv) {
return (SetMasterAuth) super.set$Xgafv($Xgafv);
}
@Override
public SetMasterAuth setAccessToken(java.lang.String accessToken) {
return (SetMasterAuth) super.setAccessToken(accessToken);
}
@Override
public SetMasterAuth setAlt(java.lang.String alt) {
return (SetMasterAuth) super.setAlt(alt);
}
@Override
public SetMasterAuth setCallback(java.lang.String callback) {
return (SetMasterAuth) super.setCallback(callback);
}
@Override
public SetMasterAuth setFields(java.lang.String fields) {
return (SetMasterAuth) super.setFields(fields);
}
@Override
public SetMasterAuth setKey(java.lang.String key) {
return (SetMasterAuth) super.setKey(key);
}
@Override
public SetMasterAuth setOauthToken(java.lang.String oauthToken) {
return (SetMasterAuth) super.setOauthToken(oauthToken);
}
@Override
public SetMasterAuth setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetMasterAuth) super.setPrettyPrint(prettyPrint);
}
@Override
public SetMasterAuth setQuotaUser(java.lang.String quotaUser) {
return (SetMasterAuth) super.setQuotaUser(quotaUser);
}
@Override
public SetMasterAuth setUploadType(java.lang.String uploadType) {
return (SetMasterAuth) super.setUploadType(uploadType);
}
@Override
public SetMasterAuth setUploadProtocol(java.lang.String uploadProtocol) {
return (SetMasterAuth) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public SetMasterAuth setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public SetMasterAuth setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
public SetMasterAuth setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public SetMasterAuth set(String parameterName, Object value) {
return (SetMasterAuth) super.set(parameterName, value);
}
}
/**
* Enables or disables Network Policy for a cluster.
*
* Create a request for the method "clusters.setNetworkPolicy".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetNetworkPolicy#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNetworkPolicyRequest}
* @return the request
*/
public SetNetworkPolicy setNetworkPolicy(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetNetworkPolicyRequest content) throws java.io.IOException {
SetNetworkPolicy result = new SetNetworkPolicy(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class SetNetworkPolicy extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}:setNetworkPolicy";
/**
* Enables or disables Network Policy for a cluster.
*
* Create a request for the method "clusters.setNetworkPolicy".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetNetworkPolicy#execute()} method to invoke the remote
* operation. <p> {@link SetNetworkPolicy#initialize(com.google.api.client.googleapis.services.Abs
* tractGoogleClientRequest)} must be called to initialize this instance immediately after
* invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNetworkPolicyRequest}
* @since 1.13
*/
protected SetNetworkPolicy(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.SetNetworkPolicyRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public SetNetworkPolicy set$Xgafv(java.lang.String $Xgafv) {
return (SetNetworkPolicy) super.set$Xgafv($Xgafv);
}
@Override
public SetNetworkPolicy setAccessToken(java.lang.String accessToken) {
return (SetNetworkPolicy) super.setAccessToken(accessToken);
}
@Override
public SetNetworkPolicy setAlt(java.lang.String alt) {
return (SetNetworkPolicy) super.setAlt(alt);
}
@Override
public SetNetworkPolicy setCallback(java.lang.String callback) {
return (SetNetworkPolicy) super.setCallback(callback);
}
@Override
public SetNetworkPolicy setFields(java.lang.String fields) {
return (SetNetworkPolicy) super.setFields(fields);
}
@Override
public SetNetworkPolicy setKey(java.lang.String key) {
return (SetNetworkPolicy) super.setKey(key);
}
@Override
public SetNetworkPolicy setOauthToken(java.lang.String oauthToken) {
return (SetNetworkPolicy) super.setOauthToken(oauthToken);
}
@Override
public SetNetworkPolicy setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetNetworkPolicy) super.setPrettyPrint(prettyPrint);
}
@Override
public SetNetworkPolicy setQuotaUser(java.lang.String quotaUser) {
return (SetNetworkPolicy) super.setQuotaUser(quotaUser);
}
@Override
public SetNetworkPolicy setUploadType(java.lang.String uploadType) {
return (SetNetworkPolicy) super.setUploadType(uploadType);
}
@Override
public SetNetworkPolicy setUploadProtocol(java.lang.String uploadProtocol) {
return (SetNetworkPolicy) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://developers.google.com/console/help/new/#projectnumber). This field has been
deprecated and replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
*/
public SetNetworkPolicy setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public SetNetworkPolicy setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
public SetNetworkPolicy setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public SetNetworkPolicy set(String parameterName, Object value) {
return (SetNetworkPolicy) super.set(parameterName, value);
}
}
/**
* Starts master IP rotation.
*
* Create a request for the method "clusters.startIpRotation".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link StartIpRotation#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.StartIPRotationRequest}
* @return the request
*/
public StartIpRotation startIpRotation(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.StartIPRotationRequest content) throws java.io.IOException {
StartIpRotation result = new StartIpRotation(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class StartIpRotation extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}:startIpRotation";
/**
* Starts master IP rotation.
*
* Create a request for the method "clusters.startIpRotation".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link StartIpRotation#execute()} method to invoke the remote
* operation. <p> {@link StartIpRotation#initialize(com.google.api.client.googleapis.services.Abst
* ractGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.StartIPRotationRequest}
* @since 1.13
*/
protected StartIpRotation(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.StartIPRotationRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public StartIpRotation set$Xgafv(java.lang.String $Xgafv) {
return (StartIpRotation) super.set$Xgafv($Xgafv);
}
@Override
public StartIpRotation setAccessToken(java.lang.String accessToken) {
return (StartIpRotation) super.setAccessToken(accessToken);
}
@Override
public StartIpRotation setAlt(java.lang.String alt) {
return (StartIpRotation) super.setAlt(alt);
}
@Override
public StartIpRotation setCallback(java.lang.String callback) {
return (StartIpRotation) super.setCallback(callback);
}
@Override
public StartIpRotation setFields(java.lang.String fields) {
return (StartIpRotation) super.setFields(fields);
}
@Override
public StartIpRotation setKey(java.lang.String key) {
return (StartIpRotation) super.setKey(key);
}
@Override
public StartIpRotation setOauthToken(java.lang.String oauthToken) {
return (StartIpRotation) super.setOauthToken(oauthToken);
}
@Override
public StartIpRotation setPrettyPrint(java.lang.Boolean prettyPrint) {
return (StartIpRotation) super.setPrettyPrint(prettyPrint);
}
@Override
public StartIpRotation setQuotaUser(java.lang.String quotaUser) {
return (StartIpRotation) super.setQuotaUser(quotaUser);
}
@Override
public StartIpRotation setUploadType(java.lang.String uploadType) {
return (StartIpRotation) super.setUploadType(uploadType);
}
@Override
public StartIpRotation setUploadProtocol(java.lang.String uploadProtocol) {
return (StartIpRotation) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://developers.google.com/console/help/new/#projectnumber). This field has been
deprecated and replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
*/
public StartIpRotation setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public StartIpRotation setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
public StartIpRotation setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public StartIpRotation set(String parameterName, Object value) {
return (StartIpRotation) super.set(parameterName, value);
}
}
/**
* Updates the settings for a specific cluster.
*
* Create a request for the method "clusters.update".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Update#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateClusterRequest}
* @return the request
*/
public Update update(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.UpdateClusterRequest content) throws java.io.IOException {
Update result = new Update(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class Update extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}";
/**
* Updates the settings for a specific cluster.
*
* Create a request for the method "clusters.update".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Update#execute()} method to invoke the remote operation.
* <p> {@link
* Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateClusterRequest}
* @since 1.13
*/
protected Update(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.UpdateClusterRequest content) {
super(Container.this, "PUT", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public Update set$Xgafv(java.lang.String $Xgafv) {
return (Update) super.set$Xgafv($Xgafv);
}
@Override
public Update setAccessToken(java.lang.String accessToken) {
return (Update) super.setAccessToken(accessToken);
}
@Override
public Update setAlt(java.lang.String alt) {
return (Update) super.setAlt(alt);
}
@Override
public Update setCallback(java.lang.String callback) {
return (Update) super.setCallback(callback);
}
@Override
public Update setFields(java.lang.String fields) {
return (Update) super.setFields(fields);
}
@Override
public Update setKey(java.lang.String key) {
return (Update) super.setKey(key);
}
@Override
public Update setOauthToken(java.lang.String oauthToken) {
return (Update) super.setOauthToken(oauthToken);
}
@Override
public Update setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Update) super.setPrettyPrint(prettyPrint);
}
@Override
public Update setQuotaUser(java.lang.String quotaUser) {
return (Update) super.setQuotaUser(quotaUser);
}
@Override
public Update setUploadType(java.lang.String uploadType) {
return (Update) super.setUploadType(uploadType);
}
@Override
public Update setUploadProtocol(java.lang.String uploadProtocol) {
return (Update) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Update setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Update setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
public Update setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public Update set(String parameterName, Object value) {
return (Update) super.set(parameterName, value);
}
}
/**
* An accessor for creating requests from the NodePools collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.NodePools.List request = container.nodePools().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public NodePools nodePools() {
return new NodePools();
}
/**
* The "nodePools" collection of methods.
*/
public class NodePools {
/**
* Sets the autoscaling settings of a specific node pool.
*
* Create a request for the method "nodePools.autoscaling".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Autoscaling#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolAutoscalingRequest}
* @return the request
*/
public Autoscaling autoscaling(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId, com.google.api.services.container.v1beta1.model.SetNodePoolAutoscalingRequest content) throws java.io.IOException {
Autoscaling result = new Autoscaling(projectId, zone, clusterId, nodePoolId, content);
initialize(result);
return result;
}
public class Autoscaling extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools/{nodePoolId}/autoscaling";
/**
* Sets the autoscaling settings of a specific node pool.
*
* Create a request for the method "nodePools.autoscaling".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Autoscaling#execute()} method to invoke the remote
* operation. <p> {@link
* Autoscaling#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolAutoscalingRequest}
* @since 1.13
*/
protected Autoscaling(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId, com.google.api.services.container.v1beta1.model.SetNodePoolAutoscalingRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
this.nodePoolId = com.google.api.client.util.Preconditions.checkNotNull(nodePoolId, "Required parameter nodePoolId must be specified.");
}
@Override
public Autoscaling set$Xgafv(java.lang.String $Xgafv) {
return (Autoscaling) super.set$Xgafv($Xgafv);
}
@Override
public Autoscaling setAccessToken(java.lang.String accessToken) {
return (Autoscaling) super.setAccessToken(accessToken);
}
@Override
public Autoscaling setAlt(java.lang.String alt) {
return (Autoscaling) super.setAlt(alt);
}
@Override
public Autoscaling setCallback(java.lang.String callback) {
return (Autoscaling) super.setCallback(callback);
}
@Override
public Autoscaling setFields(java.lang.String fields) {
return (Autoscaling) super.setFields(fields);
}
@Override
public Autoscaling setKey(java.lang.String key) {
return (Autoscaling) super.setKey(key);
}
@Override
public Autoscaling setOauthToken(java.lang.String oauthToken) {
return (Autoscaling) super.setOauthToken(oauthToken);
}
@Override
public Autoscaling setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Autoscaling) super.setPrettyPrint(prettyPrint);
}
@Override
public Autoscaling setQuotaUser(java.lang.String quotaUser) {
return (Autoscaling) super.setQuotaUser(quotaUser);
}
@Override
public Autoscaling setUploadType(java.lang.String uploadType) {
return (Autoscaling) super.setUploadType(uploadType);
}
@Override
public Autoscaling setUploadProtocol(java.lang.String uploadProtocol) {
return (Autoscaling) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Autoscaling setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Autoscaling setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
public Autoscaling setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The name of the node pool to upgrade. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String nodePoolId;
/** Required. Deprecated. The name of the node pool to upgrade. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getNodePoolId() {
return nodePoolId;
}
/**
* Required. Deprecated. The name of the node pool to upgrade. This field has been
* deprecated and replaced by the name field.
*/
public Autoscaling setNodePoolId(java.lang.String nodePoolId) {
this.nodePoolId = nodePoolId;
return this;
}
@Override
public Autoscaling set(String parameterName, Object value) {
return (Autoscaling) super.set(parameterName, value);
}
}
/**
* Creates a node pool for a cluster.
*
* Create a request for the method "nodePools.create".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the parent field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* parent field.
* @param content the {@link com.google.api.services.container.v1beta1.model.CreateNodePoolRequest}
* @return the request
*/
public Create create(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.CreateNodePoolRequest content) throws java.io.IOException {
Create result = new Create(projectId, zone, clusterId, content);
initialize(result);
return result;
}
public class Create extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools";
/**
* Creates a node pool for a cluster.
*
* Create a request for the method "nodePools.create".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Create#execute()} method to invoke the remote operation.
* <p> {@link
* Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the parent field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* parent field.
* @param content the {@link com.google.api.services.container.v1beta1.model.CreateNodePoolRequest}
* @since 1.13
*/
protected Create(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, com.google.api.services.container.v1beta1.model.CreateNodePoolRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public Create set$Xgafv(java.lang.String $Xgafv) {
return (Create) super.set$Xgafv($Xgafv);
}
@Override
public Create setAccessToken(java.lang.String accessToken) {
return (Create) super.setAccessToken(accessToken);
}
@Override
public Create setAlt(java.lang.String alt) {
return (Create) super.setAlt(alt);
}
@Override
public Create setCallback(java.lang.String callback) {
return (Create) super.setCallback(callback);
}
@Override
public Create setFields(java.lang.String fields) {
return (Create) super.setFields(fields);
}
@Override
public Create setKey(java.lang.String key) {
return (Create) super.setKey(key);
}
@Override
public Create setOauthToken(java.lang.String oauthToken) {
return (Create) super.setOauthToken(oauthToken);
}
@Override
public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Create) super.setPrettyPrint(prettyPrint);
}
@Override
public Create setQuotaUser(java.lang.String quotaUser) {
return (Create) super.setQuotaUser(quotaUser);
}
@Override
public Create setUploadType(java.lang.String uploadType) {
return (Create) super.setUploadType(uploadType);
}
@Override
public Create setUploadProtocol(java.lang.String uploadProtocol) {
return (Create) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://developers.google.com/console/help/new/#projectnumber). This field has been
deprecated and replaced by the parent field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the parent field.
*/
public Create setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the parent field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
*/
public Create setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
parent field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the parent field.
*/
public Create setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
@Override
public Create set(String parameterName, Object value) {
return (Create) super.set(parameterName, value);
}
}
/**
* Deletes a node pool from a cluster.
*
* Create a request for the method "nodePools.delete".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Delete#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to delete. This field has been deprecated and
* replaced by the name field.
* @return the request
*/
public Delete delete(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId) throws java.io.IOException {
Delete result = new Delete(projectId, zone, clusterId, nodePoolId);
initialize(result);
return result;
}
public class Delete extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools/{nodePoolId}";
/**
* Deletes a node pool from a cluster.
*
* Create a request for the method "nodePools.delete".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Delete#execute()} method to invoke the remote operation.
* <p> {@link
* Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to delete. This field has been deprecated and
* replaced by the name field.
* @since 1.13
*/
protected Delete(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId) {
super(Container.this, "DELETE", REST_PATH, null, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
this.nodePoolId = com.google.api.client.util.Preconditions.checkNotNull(nodePoolId, "Required parameter nodePoolId must be specified.");
}
@Override
public Delete set$Xgafv(java.lang.String $Xgafv) {
return (Delete) super.set$Xgafv($Xgafv);
}
@Override
public Delete setAccessToken(java.lang.String accessToken) {
return (Delete) super.setAccessToken(accessToken);
}
@Override
public Delete setAlt(java.lang.String alt) {
return (Delete) super.setAlt(alt);
}
@Override
public Delete setCallback(java.lang.String callback) {
return (Delete) super.setCallback(callback);
}
@Override
public Delete setFields(java.lang.String fields) {
return (Delete) super.setFields(fields);
}
@Override
public Delete setKey(java.lang.String key) {
return (Delete) super.setKey(key);
}
@Override
public Delete setOauthToken(java.lang.String oauthToken) {
return (Delete) super.setOauthToken(oauthToken);
}
@Override
public Delete setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Delete) super.setPrettyPrint(prettyPrint);
}
@Override
public Delete setQuotaUser(java.lang.String quotaUser) {
return (Delete) super.setQuotaUser(quotaUser);
}
@Override
public Delete setUploadType(java.lang.String uploadType) {
return (Delete) super.setUploadType(uploadType);
}
@Override
public Delete setUploadProtocol(java.lang.String uploadProtocol) {
return (Delete) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://developers.google.com/console/help/new/#projectnumber). This field has been
deprecated and replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the name field.
*/
public Delete setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Delete setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
public Delete setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The name of the node pool to delete. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String nodePoolId;
/** Required. Deprecated. The name of the node pool to delete. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getNodePoolId() {
return nodePoolId;
}
/**
* Required. Deprecated. The name of the node pool to delete. This field has been
* deprecated and replaced by the name field.
*/
public Delete setNodePoolId(java.lang.String nodePoolId) {
this.nodePoolId = nodePoolId;
return this;
}
/**
* The name (project, location, cluster, node pool id) of the node pool to delete.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster, node pool id) of the node pool to delete. Specified in the
format `projects/locations/clusters/nodePools`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster, node pool id) of the node pool to delete.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
public Delete setName(java.lang.String name) {
this.name = name;
return this;
}
@Override
public Delete set(String parameterName, Object value) {
return (Delete) super.set(parameterName, value);
}
}
/**
* Retrieves the requested node pool.
*
* Create a request for the method "nodePools.get".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param nodePoolId Required. Deprecated. The name of the node pool. This field has been deprecated and replaced by the
* name field.
* @return the request
*/
public Get get(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId) throws java.io.IOException {
Get result = new Get(projectId, zone, clusterId, nodePoolId);
initialize(result);
return result;
}
public class Get extends ContainerRequest<com.google.api.services.container.v1beta1.model.NodePool> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools/{nodePoolId}";
/**
* Retrieves the requested node pool.
*
* Create a request for the method "nodePools.get".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p>
* {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* name field.
* @param nodePoolId Required. Deprecated. The name of the node pool. This field has been deprecated and replaced by the
* name field.
* @since 1.13
*/
protected Get(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.NodePool.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
this.nodePoolId = com.google.api.client.util.Preconditions.checkNotNull(nodePoolId, "Required parameter nodePoolId must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://developers.google.com/console/help/new/#projectnumber). This field has been
deprecated and replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the name field.
*/
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Get setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the name field.
*/
public Get setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The name of the node pool. This field has been deprecated and
* replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String nodePoolId;
/** Required. Deprecated. The name of the node pool. This field has been deprecated and replaced by the
name field.
*/
public java.lang.String getNodePoolId() {
return nodePoolId;
}
/**
* Required. Deprecated. The name of the node pool. This field has been deprecated and
* replaced by the name field.
*/
public Get setNodePoolId(java.lang.String nodePoolId) {
this.nodePoolId = nodePoolId;
return this;
}
/**
* The name (project, location, cluster, node pool id) of the node pool to get.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, cluster, node pool id) of the node pool to get. Specified in the
format `projects/locations/clusters/nodePools`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, cluster, node pool id) of the node pool to get.
* Specified in the format `projects/locations/clusters/nodePools`.
*/
public Get setName(java.lang.String name) {
this.name = name;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Lists the node pools for a cluster.
*
* Create a request for the method "nodePools.list".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the parent field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* parent field.
* @return the request
*/
public List list(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId) throws java.io.IOException {
List result = new List(projectId, zone, clusterId);
initialize(result);
return result;
}
public class List extends ContainerRequest<com.google.api.services.container.v1beta1.model.ListNodePoolsResponse> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools";
/**
* Lists the node pools for a cluster.
*
* Create a request for the method "nodePools.list".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p>
* {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field has
* been deprecated and replaced by the parent field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
* @param clusterId Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
* parent field.
* @since 1.13
*/
protected List(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.ListNodePoolsResponse.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://developers.google.com/console/help/new/#projectnumber). This field has been
deprecated and replaced by the parent field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://developers.google.com/console/help/new/#projectnumber). This field
* has been deprecated and replaced by the parent field.
*/
public List setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the parent field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the parent field.
*/
public List setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster. This field has been deprecated and replaced by the
parent field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster. This field has been deprecated and
* replaced by the parent field.
*/
public List setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* The parent (project, location, cluster name) where the node pools will be listed.
* Specified in the format `projects/locations/clusters`.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** The parent (project, location, cluster name) where the node pools will be listed. Specified in the
format `projects/locations/clusters`.
*/
public java.lang.String getParent() {
return parent;
}
/**
* The parent (project, location, cluster name) where the node pools will be listed.
* Specified in the format `projects/locations/clusters`.
*/
public List setParent(java.lang.String parent) {
this.parent = parent;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
/**
* Rolls back a previously Aborted or Failed NodePool upgrade. This makes no changes if the last
* upgrade successfully completed.
*
* Create a request for the method "nodePools.rollback".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Rollback#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to rollback. This field has been deprecated and
* replaced by the name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to rollback. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.RollbackNodePoolUpgradeRequest}
* @return the request
*/
public Rollback rollback(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId, com.google.api.services.container.v1beta1.model.RollbackNodePoolUpgradeRequest content) throws java.io.IOException {
Rollback result = new Rollback(projectId, zone, clusterId, nodePoolId, content);
initialize(result);
return result;
}
public class Rollback extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools/{nodePoolId}:rollback";
/**
* Rolls back a previously Aborted or Failed NodePool upgrade. This makes no changes if the last
* upgrade successfully completed.
*
* Create a request for the method "nodePools.rollback".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Rollback#execute()} method to invoke the remote operation.
* <p> {@link
* Rollback#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to rollback. This field has been deprecated and
* replaced by the name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to rollback. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.RollbackNodePoolUpgradeRequest}
* @since 1.13
*/
protected Rollback(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId, com.google.api.services.container.v1beta1.model.RollbackNodePoolUpgradeRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
this.nodePoolId = com.google.api.client.util.Preconditions.checkNotNull(nodePoolId, "Required parameter nodePoolId must be specified.");
}
@Override
public Rollback set$Xgafv(java.lang.String $Xgafv) {
return (Rollback) super.set$Xgafv($Xgafv);
}
@Override
public Rollback setAccessToken(java.lang.String accessToken) {
return (Rollback) super.setAccessToken(accessToken);
}
@Override
public Rollback setAlt(java.lang.String alt) {
return (Rollback) super.setAlt(alt);
}
@Override
public Rollback setCallback(java.lang.String callback) {
return (Rollback) super.setCallback(callback);
}
@Override
public Rollback setFields(java.lang.String fields) {
return (Rollback) super.setFields(fields);
}
@Override
public Rollback setKey(java.lang.String key) {
return (Rollback) super.setKey(key);
}
@Override
public Rollback setOauthToken(java.lang.String oauthToken) {
return (Rollback) super.setOauthToken(oauthToken);
}
@Override
public Rollback setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Rollback) super.setPrettyPrint(prettyPrint);
}
@Override
public Rollback setQuotaUser(java.lang.String quotaUser) {
return (Rollback) super.setQuotaUser(quotaUser);
}
@Override
public Rollback setUploadType(java.lang.String uploadType) {
return (Rollback) super.setUploadType(uploadType);
}
@Override
public Rollback setUploadProtocol(java.lang.String uploadProtocol) {
return (Rollback) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Rollback setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Rollback setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to rollback. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to rollback. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to rollback. This field has been
* deprecated and replaced by the name field.
*/
public Rollback setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The name of the node pool to rollback. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String nodePoolId;
/** Required. Deprecated. The name of the node pool to rollback. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getNodePoolId() {
return nodePoolId;
}
/**
* Required. Deprecated. The name of the node pool to rollback. This field has been
* deprecated and replaced by the name field.
*/
public Rollback setNodePoolId(java.lang.String nodePoolId) {
this.nodePoolId = nodePoolId;
return this;
}
@Override
public Rollback set(String parameterName, Object value) {
return (Rollback) super.set(parameterName, value);
}
}
/**
* Sets the NodeManagement options for a node pool.
*
* Create a request for the method "nodePools.setManagement".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetManagement#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to update. This field has been deprecated and replaced
* by the name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to update. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolManagementRequest}
* @return the request
*/
public SetManagement setManagement(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId, com.google.api.services.container.v1beta1.model.SetNodePoolManagementRequest content) throws java.io.IOException {
SetManagement result = new SetManagement(projectId, zone, clusterId, nodePoolId, content);
initialize(result);
return result;
}
public class SetManagement extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools/{nodePoolId}/setManagement";
/**
* Sets the NodeManagement options for a node pool.
*
* Create a request for the method "nodePools.setManagement".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetManagement#execute()} method to invoke the remote
* operation. <p> {@link SetManagement#initialize(com.google.api.client.googleapis.services.Abstra
* ctGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to update. This field has been deprecated and replaced
* by the name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to update. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolManagementRequest}
* @since 1.13
*/
protected SetManagement(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId, com.google.api.services.container.v1beta1.model.SetNodePoolManagementRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
this.nodePoolId = com.google.api.client.util.Preconditions.checkNotNull(nodePoolId, "Required parameter nodePoolId must be specified.");
}
@Override
public SetManagement set$Xgafv(java.lang.String $Xgafv) {
return (SetManagement) super.set$Xgafv($Xgafv);
}
@Override
public SetManagement setAccessToken(java.lang.String accessToken) {
return (SetManagement) super.setAccessToken(accessToken);
}
@Override
public SetManagement setAlt(java.lang.String alt) {
return (SetManagement) super.setAlt(alt);
}
@Override
public SetManagement setCallback(java.lang.String callback) {
return (SetManagement) super.setCallback(callback);
}
@Override
public SetManagement setFields(java.lang.String fields) {
return (SetManagement) super.setFields(fields);
}
@Override
public SetManagement setKey(java.lang.String key) {
return (SetManagement) super.setKey(key);
}
@Override
public SetManagement setOauthToken(java.lang.String oauthToken) {
return (SetManagement) super.setOauthToken(oauthToken);
}
@Override
public SetManagement setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetManagement) super.setPrettyPrint(prettyPrint);
}
@Override
public SetManagement setQuotaUser(java.lang.String quotaUser) {
return (SetManagement) super.setQuotaUser(quotaUser);
}
@Override
public SetManagement setUploadType(java.lang.String uploadType) {
return (SetManagement) super.setUploadType(uploadType);
}
@Override
public SetManagement setUploadProtocol(java.lang.String uploadProtocol) {
return (SetManagement) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public SetManagement setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public SetManagement setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to update. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to update. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to update. This field has been
* deprecated and replaced by the name field.
*/
public SetManagement setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The name of the node pool to update. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String nodePoolId;
/** Required. Deprecated. The name of the node pool to update. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getNodePoolId() {
return nodePoolId;
}
/**
* Required. Deprecated. The name of the node pool to update. This field has been
* deprecated and replaced by the name field.
*/
public SetManagement setNodePoolId(java.lang.String nodePoolId) {
this.nodePoolId = nodePoolId;
return this;
}
@Override
public SetManagement set(String parameterName, Object value) {
return (SetManagement) super.set(parameterName, value);
}
}
/**
* SetNodePoolSizeRequest sets the size of a node pool. The new size will be used for all replicas,
* including future replicas created by modifying NodePool.locations.
*
* Create a request for the method "nodePools.setSize".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link SetSize#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to update. This field has been deprecated and replaced
* by the name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to update. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolSizeRequest}
* @return the request
*/
public SetSize setSize(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId, com.google.api.services.container.v1beta1.model.SetNodePoolSizeRequest content) throws java.io.IOException {
SetSize result = new SetSize(projectId, zone, clusterId, nodePoolId, content);
initialize(result);
return result;
}
public class SetSize extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools/{nodePoolId}/setSize";
/**
* SetNodePoolSizeRequest sets the size of a node pool. The new size will be used for all
* replicas, including future replicas created by modifying NodePool.locations.
*
* Create a request for the method "nodePools.setSize".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link SetSize#execute()} method to invoke the remote operation.
* <p> {@link
* SetSize#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to update. This field has been deprecated and replaced
* by the name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to update. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.SetNodePoolSizeRequest}
* @since 1.13
*/
protected SetSize(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId, com.google.api.services.container.v1beta1.model.SetNodePoolSizeRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
this.nodePoolId = com.google.api.client.util.Preconditions.checkNotNull(nodePoolId, "Required parameter nodePoolId must be specified.");
}
@Override
public SetSize set$Xgafv(java.lang.String $Xgafv) {
return (SetSize) super.set$Xgafv($Xgafv);
}
@Override
public SetSize setAccessToken(java.lang.String accessToken) {
return (SetSize) super.setAccessToken(accessToken);
}
@Override
public SetSize setAlt(java.lang.String alt) {
return (SetSize) super.setAlt(alt);
}
@Override
public SetSize setCallback(java.lang.String callback) {
return (SetSize) super.setCallback(callback);
}
@Override
public SetSize setFields(java.lang.String fields) {
return (SetSize) super.setFields(fields);
}
@Override
public SetSize setKey(java.lang.String key) {
return (SetSize) super.setKey(key);
}
@Override
public SetSize setOauthToken(java.lang.String oauthToken) {
return (SetSize) super.setOauthToken(oauthToken);
}
@Override
public SetSize setPrettyPrint(java.lang.Boolean prettyPrint) {
return (SetSize) super.setPrettyPrint(prettyPrint);
}
@Override
public SetSize setQuotaUser(java.lang.String quotaUser) {
return (SetSize) super.setQuotaUser(quotaUser);
}
@Override
public SetSize setUploadType(java.lang.String uploadType) {
return (SetSize) super.setUploadType(uploadType);
}
@Override
public SetSize setUploadProtocol(java.lang.String uploadProtocol) {
return (SetSize) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public SetSize setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public SetSize setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to update. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to update. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to update. This field has been
* deprecated and replaced by the name field.
*/
public SetSize setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The name of the node pool to update. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String nodePoolId;
/** Required. Deprecated. The name of the node pool to update. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getNodePoolId() {
return nodePoolId;
}
/**
* Required. Deprecated. The name of the node pool to update. This field has been
* deprecated and replaced by the name field.
*/
public SetSize setNodePoolId(java.lang.String nodePoolId) {
this.nodePoolId = nodePoolId;
return this;
}
@Override
public SetSize set(String parameterName, Object value) {
return (SetSize) super.set(parameterName, value);
}
}
/**
* Updates the version and/or image type of a specific node pool.
*
* Create a request for the method "nodePools.update".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Update#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateNodePoolRequest}
* @return the request
*/
public Update update(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId, com.google.api.services.container.v1beta1.model.UpdateNodePoolRequest content) throws java.io.IOException {
Update result = new Update(projectId, zone, clusterId, nodePoolId, content);
initialize(result);
return result;
}
public class Update extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools/{nodePoolId}/update";
/**
* Updates the version and/or image type of a specific node pool.
*
* Create a request for the method "nodePools.update".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Update#execute()} method to invoke the remote operation.
* <p> {@link
* Update#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param clusterId Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
* replaced by the name field.
* @param nodePoolId Required. Deprecated. The name of the node pool to upgrade. This field has been deprecated and
* replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.UpdateNodePoolRequest}
* @since 1.13
*/
protected Update(java.lang.String projectId, java.lang.String zone, java.lang.String clusterId, java.lang.String nodePoolId, com.google.api.services.container.v1beta1.model.UpdateNodePoolRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.clusterId = com.google.api.client.util.Preconditions.checkNotNull(clusterId, "Required parameter clusterId must be specified.");
this.nodePoolId = com.google.api.client.util.Preconditions.checkNotNull(nodePoolId, "Required parameter nodePoolId must be specified.");
}
@Override
public Update set$Xgafv(java.lang.String $Xgafv) {
return (Update) super.set$Xgafv($Xgafv);
}
@Override
public Update setAccessToken(java.lang.String accessToken) {
return (Update) super.setAccessToken(accessToken);
}
@Override
public Update setAlt(java.lang.String alt) {
return (Update) super.setAlt(alt);
}
@Override
public Update setCallback(java.lang.String callback) {
return (Update) super.setCallback(callback);
}
@Override
public Update setFields(java.lang.String fields) {
return (Update) super.setFields(fields);
}
@Override
public Update setKey(java.lang.String key) {
return (Update) super.setKey(key);
}
@Override
public Update setOauthToken(java.lang.String oauthToken) {
return (Update) super.setOauthToken(oauthToken);
}
@Override
public Update setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Update) super.setPrettyPrint(prettyPrint);
}
@Override
public Update setQuotaUser(java.lang.String quotaUser) {
return (Update) super.setQuotaUser(quotaUser);
}
@Override
public Update setUploadType(java.lang.String uploadType) {
return (Update) super.setUploadType(uploadType);
}
@Override
public Update setUploadProtocol(java.lang.String uploadProtocol) {
return (Update) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Update setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Update setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String clusterId;
/** Required. Deprecated. The name of the cluster to upgrade. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getClusterId() {
return clusterId;
}
/**
* Required. Deprecated. The name of the cluster to upgrade. This field has been
* deprecated and replaced by the name field.
*/
public Update setClusterId(java.lang.String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Required. Deprecated. The name of the node pool to upgrade. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String nodePoolId;
/** Required. Deprecated. The name of the node pool to upgrade. This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getNodePoolId() {
return nodePoolId;
}
/**
* Required. Deprecated. The name of the node pool to upgrade. This field has been
* deprecated and replaced by the name field.
*/
public Update setNodePoolId(java.lang.String nodePoolId) {
this.nodePoolId = nodePoolId;
return this;
}
@Override
public Update set(String parameterName, Object value) {
return (Update) super.set(parameterName, value);
}
}
}
}
/**
* An accessor for creating requests from the Operations collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Container container = new Container(...);}
* {@code Container.Operations.List request = container.operations().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Operations operations() {
return new Operations();
}
/**
* The "operations" collection of methods.
*/
public class Operations {
/**
* Cancels the specified operation.
*
* Create a request for the method "operations.cancel".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Cancel#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the operation
* resides. This field has been deprecated and replaced by the name field.
* @param operationId Required. Deprecated. The server-assigned `name` of the operation. This field has been deprecated
* and replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.CancelOperationRequest}
* @return the request
*/
public Cancel cancel(java.lang.String projectId, java.lang.String zone, java.lang.String operationId, com.google.api.services.container.v1beta1.model.CancelOperationRequest content) throws java.io.IOException {
Cancel result = new Cancel(projectId, zone, operationId, content);
initialize(result);
return result;
}
public class Cancel extends ContainerRequest<com.google.api.services.container.v1beta1.model.Empty> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/operations/{operationId}:cancel";
/**
* Cancels the specified operation.
*
* Create a request for the method "operations.cancel".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Cancel#execute()} method to invoke the remote operation.
* <p> {@link
* Cancel#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the operation
* resides. This field has been deprecated and replaced by the name field.
* @param operationId Required. Deprecated. The server-assigned `name` of the operation. This field has been deprecated
* and replaced by the name field.
* @param content the {@link com.google.api.services.container.v1beta1.model.CancelOperationRequest}
* @since 1.13
*/
protected Cancel(java.lang.String projectId, java.lang.String zone, java.lang.String operationId, com.google.api.services.container.v1beta1.model.CancelOperationRequest content) {
super(Container.this, "POST", REST_PATH, content, com.google.api.services.container.v1beta1.model.Empty.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.operationId = com.google.api.client.util.Preconditions.checkNotNull(operationId, "Required parameter operationId must be specified.");
}
@Override
public Cancel set$Xgafv(java.lang.String $Xgafv) {
return (Cancel) super.set$Xgafv($Xgafv);
}
@Override
public Cancel setAccessToken(java.lang.String accessToken) {
return (Cancel) super.setAccessToken(accessToken);
}
@Override
public Cancel setAlt(java.lang.String alt) {
return (Cancel) super.setAlt(alt);
}
@Override
public Cancel setCallback(java.lang.String callback) {
return (Cancel) super.setCallback(callback);
}
@Override
public Cancel setFields(java.lang.String fields) {
return (Cancel) super.setFields(fields);
}
@Override
public Cancel setKey(java.lang.String key) {
return (Cancel) super.setKey(key);
}
@Override
public Cancel setOauthToken(java.lang.String oauthToken) {
return (Cancel) super.setOauthToken(oauthToken);
}
@Override
public Cancel setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Cancel) super.setPrettyPrint(prettyPrint);
}
@Override
public Cancel setQuotaUser(java.lang.String quotaUser) {
return (Cancel) super.setQuotaUser(quotaUser);
}
@Override
public Cancel setUploadType(java.lang.String uploadType) {
return (Cancel) super.setUploadType(uploadType);
}
@Override
public Cancel setUploadProtocol(java.lang.String uploadProtocol) {
return (Cancel) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Cancel setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the operation
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the operation resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the operation
* resides. This field has been deprecated and replaced by the name field.
*/
public Cancel setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The server-assigned `name` of the operation. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String operationId;
/** Required. Deprecated. The server-assigned `name` of the operation. This field has been deprecated
and replaced by the name field.
*/
public java.lang.String getOperationId() {
return operationId;
}
/**
* Required. Deprecated. The server-assigned `name` of the operation. This field has been
* deprecated and replaced by the name field.
*/
public Cancel setOperationId(java.lang.String operationId) {
this.operationId = operationId;
return this;
}
@Override
public Cancel set(String parameterName, Object value) {
return (Cancel) super.set(parameterName, value);
}
}
/**
* Gets the specified operation.
*
* Create a request for the method "operations.get".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param operationId Required. Deprecated. The server-assigned `name` of the operation. This field has been deprecated
* and replaced by the name field.
* @return the request
*/
public Get get(java.lang.String projectId, java.lang.String zone, java.lang.String operationId) throws java.io.IOException {
Get result = new Get(projectId, zone, operationId);
initialize(result);
return result;
}
public class Get extends ContainerRequest<com.google.api.services.container.v1beta1.model.Operation> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/operations/{operationId}";
/**
* Gets the specified operation.
*
* Create a request for the method "operations.get".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p>
* {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the name field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
* @param operationId Required. Deprecated. The server-assigned `name` of the operation. This field has been deprecated
* and replaced by the name field.
* @since 1.13
*/
protected Get(java.lang.String projectId, java.lang.String zone, java.lang.String operationId) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.Operation.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
this.operationId = com.google.api.client.util.Preconditions.checkNotNull(operationId, "Required parameter operationId must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the name field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the name field.
*/
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This
field has been deprecated and replaced by the name field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster
* resides. This field has been deprecated and replaced by the name field.
*/
public Get setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* Required. Deprecated. The server-assigned `name` of the operation. This field has been
* deprecated and replaced by the name field.
*/
@com.google.api.client.util.Key
private java.lang.String operationId;
/** Required. Deprecated. The server-assigned `name` of the operation. This field has been deprecated
and replaced by the name field.
*/
public java.lang.String getOperationId() {
return operationId;
}
/**
* Required. Deprecated. The server-assigned `name` of the operation. This field has been
* deprecated and replaced by the name field.
*/
public Get setOperationId(java.lang.String operationId) {
this.operationId = operationId;
return this;
}
/**
* The name (project, location, operation id) of the operation to get. Specified in the
* format `projects/locations/operations`.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The name (project, location, operation id) of the operation to get. Specified in the format
`projects/locations/operations`.
*/
public java.lang.String getName() {
return name;
}
/**
* The name (project, location, operation id) of the operation to get. Specified in the
* format `projects/locations/operations`.
*/
public Get setName(java.lang.String name) {
this.name = name;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Lists all operations in a project in the specified zone or all zones.
*
* Create a request for the method "operations.list".
*
* This request holds the parameters needed by the container server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the parent field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for, or
* `-` for all zones. This field has been deprecated and replaced by the parent field.
* @return the request
*/
public List list(java.lang.String projectId, java.lang.String zone) throws java.io.IOException {
List result = new List(projectId, zone);
initialize(result);
return result;
}
public class List extends ContainerRequest<com.google.api.services.container.v1beta1.model.ListOperationsResponse> {
private static final String REST_PATH = "v1beta1/projects/{projectId}/zones/{zone}/operations";
/**
* Lists all operations in a project in the specified zone or all zones.
*
* Create a request for the method "operations.list".
*
* This request holds the parameters needed by the the container server. After setting any
* optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p>
* {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
* and replaced by the parent field.
* @param zone Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for, or
* `-` for all zones. This field has been deprecated and replaced by the parent field.
* @since 1.13
*/
protected List(java.lang.String projectId, java.lang.String zone) {
super(Container.this, "GET", REST_PATH, null, com.google.api.services.container.v1beta1.model.ListOperationsResponse.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.zone = com.google.api.client.util.Preconditions.checkNotNull(zone, "Required parameter zone must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and
replaced by the parent field.
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. Deprecated. The Google Developers Console [project ID or project
* number](https://support.google.com/cloud/answer/6158840). This field has been
* deprecated and replaced by the parent field.
*/
public List setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for,
* or `-` for all zones. This field has been deprecated and replaced by the parent field.
*/
@com.google.api.client.util.Key
private java.lang.String zone;
/** Required. Deprecated. The name of the Google Compute Engine
[zone](https://cloud.google.com/compute/docs/zones#available) to return operations for, or `-` for
all zones. This field has been deprecated and replaced by the parent field.
*/
public java.lang.String getZone() {
return zone;
}
/**
* Required. Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available) to return operations for,
* or `-` for all zones. This field has been deprecated and replaced by the parent field.
*/
public List setZone(java.lang.String zone) {
this.zone = zone;
return this;
}
/**
* The parent (project and location) where the operations will be listed. Specified in the
* format `projects/locations`. Location "-" matches all zones and all regions.
*/
@com.google.api.client.util.Key
private java.lang.String parent;
/** The parent (project and location) where the operations will be listed. Specified in the format
`projects/locations`. Location "-" matches all zones and all regions.
*/
public java.lang.String getParent() {
return parent;
}
/**
* The parent (project and location) where the operations will be listed. Specified in the
* format `projects/locations`. Location "-" matches all zones and all regions.
*/
public List setParent(java.lang.String parent) {
this.parent = parent;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
}
}
}
/**
* Builder for {@link Container}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
private static String chooseEndpoint(com.google.api.client.http.HttpTransport transport) {
// If the GOOGLE_API_USE_MTLS_ENDPOINT environment variable value is "always", use mTLS endpoint.
// If the env variable is "auto", use mTLS endpoint if and only if the transport is mTLS.
// Use the regular endpoint for all other cases.
String useMtlsEndpoint = System.getenv("GOOGLE_API_USE_MTLS_ENDPOINT");
useMtlsEndpoint = useMtlsEndpoint == null ? "auto" : useMtlsEndpoint;
if ("always".equals(useMtlsEndpoint) || ("auto".equals(useMtlsEndpoint) && transport != null && transport.isMtls())) {
return DEFAULT_MTLS_ROOT_URL;
}
return DEFAULT_ROOT_URL;
}
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
Builder.chooseEndpoint(transport),
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link Container}. */
@Override
public Container build() {
return new Container(this);
}
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setBatchPath(String batchPath) {
return (Builder) super.setBatchPath(batchPath);
}
@Override
public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
@Override
public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) {
return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks);
}
@Override
public Builder setSuppressAllChecks(boolean suppressAllChecks) {
return (Builder) super.setSuppressAllChecks(suppressAllChecks);
}
/**
* Set the {@link ContainerRequestInitializer}.
*
* @since 1.12
*/
public Builder setContainerRequestInitializer(
ContainerRequestInitializer containerRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(containerRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
| [
"\"GOOGLE_API_USE_MTLS_ENDPOINT\""
]
| []
| [
"GOOGLE_API_USE_MTLS_ENDPOINT"
]
| [] | ["GOOGLE_API_USE_MTLS_ENDPOINT"] | java | 1 | 0 | |
cmd/discussion_comments_user.go | // Copyright © 2018 Chris Tava <[email protected]>
//
// 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.
package cmd
import (
"fmt"
"strings"
"time"
"context"
"os"
"github.com/ctava/github-teamwork/github"
"github.com/spf13/cobra"
)
var discussionCmdName = "teamdiscussion"
// discussionCmd prints out contributions to dicussions
var discussionCmd = &cobra.Command{
Use: discussionCmdName,
Short: discussionCmdName + " org team user startDay endDay",
Long: discussionCmdName + ` org team user startDay endDay: prints out team discussion comments by date, user. includes reactions (total count, :+1:, :-1:, :laugh:, :confused:, :heart: and :hooray:)`,
Run: func(cmd *cobra.Command, args []string) {
githubAuthToken := os.Getenv("GITHUB_ACCESS_TOKEN")
if githubAuthToken == "" {
fmt.Println("warning: will be limited to 60 calls per hour without a token")
}
ctx := context.Background()
fetcher := github.NewFetcher(ctx, githubAuthToken)
team := getFlagString(cmd, "team")
values := strings.Split(team, "/")
if len(values) < 2 {
fmt.Println("error: team name needs to be owner/teamname")
return
}
org, teamName := values[0], values[1]
user := getFlagString(cmd, "user")
start := getFlagString(cmd, "start")
end := getFlagString(cmd, "end")
startTime, sterr := time.Parse("2006-01-02", start)
if sterr != nil {
fmt.Println("an error occurred while parsing the start time. err:", sterr)
return
}
startYear := startTime.Year()
startMonth := startTime.Month()
endTime, eterr := time.Parse("2006-01-02", end)
if eterr != nil {
fmt.Println("an error occurred while parsing the end time. err:", eterr)
return
}
endYear := endTime.Year()
endMonth := endTime.Month()
discussionComments, err := fetcher.FetchTeamDiscussionComments(ctx, org, teamName)
if err != nil {
fmt.Println("an error occurred while fetching PR Comments err:", err)
return
}
var timeSeriesDataSet []byte
fmt.Printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s \n", "created_date", "handle", "body", "reaction_total_count", "reaction_plusone", "reaction_minusone", "reaction_laugh", "reaction_confused", "reaction_heart", "reaction_hooray")
for _, c := range discussionComments {
if strings.Compare(user, c.Handle) == 0 {
if strings.Compare(c.CreatedAt, start) != -1 {
if strings.Compare(c.CreatedAt, end) != 1 {
fmt.Printf("%s,%s,%s,%v,%v,%v,%v,%v,%v,%v \n", c.CreatedAt, c.Handle, c.Body, c.ReactionTotalCount, c.ReactionPlusOne, c.ReactionMinusOne, c.ReactionLaugh, c.ReactionConfused, c.ReactionHeart, c.ReactionHooray)
timeSeriesDataSet = append(timeSeriesDataSet, c.CreatedAt...)
timeSeriesDataSet = append(timeSeriesDataSet, "\n"...)
}
}
}
}
fileRoot := start + "-" + user + "-" + discussionCmdName
writeDataSetToFile(fileRoot+".csv", timeSeriesDataSet)
derr := drawChart(startYear, endYear, startMonth, endMonth, discussionCmdName, fileRoot+".csv", fileRoot+".png")
if derr != nil {
fmt.Println("an error occurred while drawing the chart. err:", derr)
return
}
},
}
func init() {
RootCmd.AddCommand(discussionCmd)
discussionCmd.Flags().StringP("team", "T", "", "team to search for discussion threads")
discussionCmd.Flags().StringP("user", "U", "", "commenter to search for")
discussionCmd.Flags().StringP("start", "S", "", "comment start day")
discussionCmd.Flags().StringP("end", "E", "", "comment end day")
discussionCmd.MarkFlagRequired("team")
discussionCmd.MarkFlagRequired("user")
discussionCmd.MarkFlagRequired("start")
discussionCmd.MarkFlagRequired("end")
}
| [
"\"GITHUB_ACCESS_TOKEN\""
]
| []
| [
"GITHUB_ACCESS_TOKEN"
]
| [] | ["GITHUB_ACCESS_TOKEN"] | go | 1 | 0 | |
server/schedule_jobs.py | from typing import Callable, List
import schedule
from dotenv import load_dotenv
import os
import requests
import sys
load_dotenv()
def email_logs(
admins: List[str],
file_name: str,
file_path: str,
error: bool = False,
message: str = None,
):
if not error:
data = {
"from": "CodeChef SRM <[email protected]>",
"to": admins,
"subject": "Admin Logs",
}
files = ([("attachment", (file_name, open(file_path, "rb").read()))],)
else:
data = {
"from": "CodeChef SRM <[email protected]>",
"to": admins,
"subject": "Error Occurred",
"text": message,
}
files = None
requests.post(
url=os.getenv("base_url"),
auth=("api", os.getenv("sending_keys")),
data=data,
files=files,
)
def run(day: str, time: str, func: Callable, *args, **kwargs):
if not os.path.exists(kwargs.get("file_path")):
func(
error=True,
message="Log File Not Found",
file_name=None,
file_path=None,
admins=kwargs.get("admins"),
)
sys.exit(0)
_day = getattr(schedule.every(), day)
_day.at(time).do(func, *args, **kwargs)
while True:
schedule.run_pending()
if __name__ == "__main__":
run(
day="monday",
time="10:30",
func=email_logs,
admins=os.getenv("admins").split(","),
file_name="Logs",
file_path="../admin.log",
)
| []
| []
| [
"base_url",
"admins",
"sending_keys"
]
| [] | ["base_url", "admins", "sending_keys"] | python | 3 | 0 | |
hackeriet/web/brusweb/__init__.py | from flask import Flask, request, Response, render_template, g, redirect, url_for, send_file, jsonify
from functools import wraps
import stripe
import os, uuid, json
from hackeriet.web.brusweb import brusdb, members
from hackeriet.mqtt import MQTT
# teste stripe
# lage bruker for gratis brus
# brus/error virker ikke
# descriptions virker settes ikke
# fikse graf
# sende mail
# Stripe ids
stripe_keys = {
'secret_key': os.environ.get('SECRET_KEY', ""),
'publishable_key': os.environ.get('PUBLISHABLE_KEY', "")
}
stripe.api_key = stripe_keys['secret_key']
app = Flask(__name__)
def mqtt_handler(mosq,obj,msg):
if msg.topic == "brus/sell":
args = json.loads(msg.payload.decode())
authorise_sale(**args)
if msg.topic == "hackeriet/reload_users":
members.load()
members.load()
mqtt = MQTT(mqtt_handler)
mqtt.subscribe("brus/sell",0)
mqtt.subscribe("hackeriet/reload_users",0)
def check_auth(username, password):
return members.authenticate(username, password)
def check_admin(username, password):
return members.authenticate_admin(username, password)
def authenticate():
return Response('L33t hax0rz only\n',401,
{'WWW-Authenticate': 'Basic realm="Hackeriet"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
def requires_admin(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_admin(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@app.route("/")
def hello():
return redirect(url_for('index'))
@app.route("/brus/sales.json")
def stats():
r = []
st = brusdb.get_outgoing_transactions()
for d in {e for (t,v,e) in st}:
if len([t for (t,v,e) in st if e==d]) > 4:
r += [{"key": d, "values": [[int(t)*1000,-v] if e==d else [int(t)*1000,0] for (t,v,e) in st]}]
return json.dumps(r)
@app.route('/brus/')
def index():
return render_template('index.html')
@app.route("/brus/account")
@requires_auth
def account():
user=request.authorization.username
return render_template('account.html', username=user,
history=brusdb.transaction_history(user),
balance=brusdb.balance(user),
key=stripe_keys['publishable_key'])
@app.route("/brus/withdraw", methods=['POST'])
def manual_subtract():
user=request.authorization.username
if brusdb.subtract_funds(user, int(request.form['value']),
request.form['desc'], True):
return redirect(url_for('account'))
else:
return "Insufficient funds"
@app.route("/brus/admin")
@requires_admin
def admin():
user=request.authorization.username
return render_template('admin.html', username=user,
users=members.list_users())
@app.route("/brus/admin/add", methods=['POST'])
@requires_admin
def admin_add():
brusdb.add_funds(request.form['user'], int(request.form['value']),
request.form['desc'])
return 'ok'
@app.route("/brus/charge", methods=['POST'])
@requires_auth
def charge():
# Amount in cents
amount = request.form['amountt']
user=request.authorization.username
stripe_id = None #brusdb.get_stripe_id(user)
if not stripe_id:
customer = stripe.Customer.create(
email=members.get_email(user),
card=request.form['stripeToken']
)
stripe_id = customer.id
#brusdb.set_stripe_id(user, stripe_id)
charge = stripe.Charge.create(
customer=stripe_id,
amount=amount,
currency='NOK',
description='Hackeriet'
)
brusdb.add_funds(user, int(amount)/100, "Transfer with Stripe.")
return render_template('charge.html', amount=int(amount)/100)
def authorise_sale(slot, card_data):
price, desc = brusdb.get_product_price_descr(brusdb.getproduct("brusautomat", slot))
if brusdb.subtract_funds(members.username_from_card(card_data), price, desc):
mqtt("brus/dispense", slot)
mqtt("brus/error", "Insufficient funds")
if __name__ == "__main__":
main()
def main():
app.debug = False
app.run()
| []
| []
| [
"SECRET_KEY",
"PUBLISHABLE_KEY"
]
| [] | ["SECRET_KEY", "PUBLISHABLE_KEY"] | python | 2 | 0 | |
pkg/provider/kubernetes/crd/kubernetes.go | package crd
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"errors"
"fmt"
"os"
"sort"
"strings"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/mitchellh/hashstructure"
ptypes "github.com/traefik/paerser/types"
"github.com/traefik/traefik/v2/pkg/config/dynamic"
"github.com/traefik/traefik/v2/pkg/job"
"github.com/traefik/traefik/v2/pkg/log"
"github.com/traefik/traefik/v2/pkg/provider"
"github.com/traefik/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1"
"github.com/traefik/traefik/v2/pkg/safe"
"github.com/traefik/traefik/v2/pkg/tls"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
)
const (
annotationKubernetesIngressClass = "kubernetes.io/ingress.class"
traefikDefaultIngressClass = "traefik"
)
const (
providerName = "kubernetescrd"
providerNamespaceSeparator = "@"
)
// Provider holds configurations of the provider.
type Provider struct {
Endpoint string `description:"Kubernetes server endpoint (required for external cluster client)." json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty"`
Token string `description:"Kubernetes bearer token (not needed for in-cluster client)." json:"token,omitempty" toml:"token,omitempty" yaml:"token,omitempty"`
CertAuthFilePath string `description:"Kubernetes certificate authority file path (not needed for in-cluster client)." json:"certAuthFilePath,omitempty" toml:"certAuthFilePath,omitempty" yaml:"certAuthFilePath,omitempty"`
DisablePassHostHeaders bool `description:"Kubernetes disable PassHost Headers." json:"disablePassHostHeaders,omitempty" toml:"disablePassHostHeaders,omitempty" yaml:"disablePassHostHeaders,omitempty" export:"true"`
Namespaces []string `description:"Kubernetes namespaces." json:"namespaces,omitempty" toml:"namespaces,omitempty" yaml:"namespaces,omitempty" export:"true"`
LabelSelector string `description:"Kubernetes label selector to use." json:"labelSelector,omitempty" toml:"labelSelector,omitempty" yaml:"labelSelector,omitempty" export:"true"`
IngressClass string `description:"Value of kubernetes.io/ingress.class annotation to watch for." json:"ingressClass,omitempty" toml:"ingressClass,omitempty" yaml:"ingressClass,omitempty" export:"true"`
ThrottleDuration ptypes.Duration `description:"Ingress refresh throttle duration" json:"throttleDuration,omitempty" toml:"throttleDuration,omitempty" yaml:"throttleDuration,omitempty" export:"true"`
lastConfiguration safe.Safe
}
func (p *Provider) newK8sClient(ctx context.Context, labelSelector string) (*clientWrapper, error) {
labelSel, err := labels.Parse(labelSelector)
if err != nil {
return nil, fmt.Errorf("invalid label selector: %q", labelSelector)
}
log.FromContext(ctx).Infof("label selector is: %q", labelSel)
withEndpoint := ""
if p.Endpoint != "" {
withEndpoint = fmt.Sprintf(" with endpoint %s", p.Endpoint)
}
var client *clientWrapper
switch {
case os.Getenv("KUBERNETES_SERVICE_HOST") != "" && os.Getenv("KUBERNETES_SERVICE_PORT") != "":
log.FromContext(ctx).Infof("Creating in-cluster Provider client%s", withEndpoint)
client, err = newInClusterClient(p.Endpoint)
case os.Getenv("KUBECONFIG") != "":
log.FromContext(ctx).Infof("Creating cluster-external Provider client from KUBECONFIG %s", os.Getenv("KUBECONFIG"))
client, err = newExternalClusterClientFromFile(os.Getenv("KUBECONFIG"))
default:
log.FromContext(ctx).Infof("Creating cluster-external Provider client%s", withEndpoint)
client, err = newExternalClusterClient(p.Endpoint, p.Token, p.CertAuthFilePath)
}
if err == nil {
client.labelSelector = labelSel
}
return client, err
}
// Init the provider.
func (p *Provider) Init() error {
return nil
}
// Provide allows the k8s provider to provide configurations to traefik
// using the given configuration channel.
func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error {
ctxLog := log.With(context.Background(), log.Str(log.ProviderName, providerName))
logger := log.FromContext(ctxLog)
logger.Debugf("Using label selector: %q", p.LabelSelector)
k8sClient, err := p.newK8sClient(ctxLog, p.LabelSelector)
if err != nil {
return err
}
pool.GoCtx(func(ctxPool context.Context) {
operation := func() error {
eventsChan, err := k8sClient.WatchAll(p.Namespaces, ctxPool.Done())
if err != nil {
logger.Errorf("Error watching kubernetes events: %v", err)
timer := time.NewTimer(1 * time.Second)
select {
case <-timer.C:
return err
case <-ctxPool.Done():
return nil
}
}
throttleDuration := time.Duration(p.ThrottleDuration)
throttledChan := throttleEvents(ctxLog, throttleDuration, pool, eventsChan)
if throttledChan != nil {
eventsChan = throttledChan
}
for {
select {
case <-ctxPool.Done():
return nil
case event := <-eventsChan:
// Note that event is the *first* event that came in during this throttling interval -- if we're hitting our throttle, we may have dropped events.
// This is fine, because we don't treat different event types differently.
// But if we do in the future, we'll need to track more information about the dropped events.
conf := p.loadConfigurationFromCRD(ctxLog, k8sClient)
confHash, err := hashstructure.Hash(conf, nil)
switch {
case err != nil:
logger.Error("Unable to hash the configuration")
case p.lastConfiguration.Get() == confHash:
logger.Debugf("Skipping Kubernetes event kind %T", event)
default:
p.lastConfiguration.Set(confHash)
configurationChan <- dynamic.Message{
ProviderName: providerName,
Configuration: conf,
}
}
// If we're throttling,
// we sleep here for the throttle duration to enforce that we don't refresh faster than our throttle.
// time.Sleep returns immediately if p.ThrottleDuration is 0 (no throttle).
time.Sleep(throttleDuration)
}
}
}
notify := func(err error, time time.Duration) {
logger.Errorf("Provider connection error: %v; retrying in %s", err, time)
}
err := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxPool), notify)
if err != nil {
logger.Errorf("Cannot connect to Provider: %v", err)
}
})
return nil
}
func (p *Provider) loadConfigurationFromCRD(ctx context.Context, client Client) *dynamic.Configuration {
tlsConfigs := make(map[string]*tls.CertAndStores)
conf := &dynamic.Configuration{
HTTP: p.loadIngressRouteConfiguration(ctx, client, tlsConfigs),
TCP: p.loadIngressRouteTCPConfiguration(ctx, client, tlsConfigs),
UDP: p.loadIngressRouteUDPConfiguration(ctx, client),
TLS: &dynamic.TLSConfiguration{
Certificates: getTLSConfig(tlsConfigs),
Options: buildTLSOptions(ctx, client),
Stores: buildTLSStores(ctx, client),
},
}
for _, middleware := range client.GetMiddlewares() {
id := provider.Normalize(makeID(middleware.Namespace, middleware.Name))
ctxMid := log.With(ctx, log.Str(log.MiddlewareName, id))
basicAuth, err := createBasicAuthMiddleware(client, middleware.Namespace, middleware.Spec.BasicAuth)
if err != nil {
log.FromContext(ctxMid).Errorf("Error while reading basic auth middleware: %v", err)
continue
}
digestAuth, err := createDigestAuthMiddleware(client, middleware.Namespace, middleware.Spec.DigestAuth)
if err != nil {
log.FromContext(ctxMid).Errorf("Error while reading digest auth middleware: %v", err)
continue
}
forwardAuth, err := createForwardAuthMiddleware(client, middleware.Namespace, middleware.Spec.ForwardAuth)
if err != nil {
log.FromContext(ctxMid).Errorf("Error while reading forward auth middleware: %v", err)
continue
}
errorPage, errorPageService, err := createErrorPageMiddleware(client, middleware.Namespace, middleware.Spec.Errors)
if err != nil {
log.FromContext(ctxMid).Errorf("Error while reading error page middleware: %v", err)
continue
}
if errorPage != nil && errorPageService != nil {
serviceName := id + "-errorpage-service"
errorPage.Service = serviceName
conf.HTTP.Services[serviceName] = errorPageService
}
conf.HTTP.Middlewares[id] = &dynamic.Middleware{
AddPrefix: middleware.Spec.AddPrefix,
StripPrefix: middleware.Spec.StripPrefix,
StripPrefixRegex: middleware.Spec.StripPrefixRegex,
ReplacePath: middleware.Spec.ReplacePath,
ReplacePathRegex: middleware.Spec.ReplacePathRegex,
Chain: createChainMiddleware(ctxMid, middleware.Namespace, middleware.Spec.Chain),
IPWhiteList: middleware.Spec.IPWhiteList,
Headers: middleware.Spec.Headers,
Errors: errorPage,
RateLimit: middleware.Spec.RateLimit,
RedirectRegex: middleware.Spec.RedirectRegex,
RedirectScheme: middleware.Spec.RedirectScheme,
BasicAuth: basicAuth,
DigestAuth: digestAuth,
ForwardAuth: forwardAuth,
InFlightReq: middleware.Spec.InFlightReq,
Buffering: middleware.Spec.Buffering,
CircuitBreaker: middleware.Spec.CircuitBreaker,
Compress: middleware.Spec.Compress,
PassTLSClientCert: middleware.Spec.PassTLSClientCert,
Retry: middleware.Spec.Retry,
ContentType: middleware.Spec.ContentType,
Plugin: middleware.Spec.Plugin,
}
}
cb := configBuilder{client}
for _, service := range client.GetTraefikServices() {
err := cb.buildTraefikService(ctx, service, conf.HTTP.Services)
if err != nil {
log.FromContext(ctx).WithField(log.ServiceName, service.Name).
Errorf("Error while building TraefikService: %v", err)
continue
}
}
return conf
}
func getServicePort(svc *corev1.Service, port int32) (*corev1.ServicePort, error) {
if svc == nil {
return nil, errors.New("service is not defined")
}
if port == 0 {
return nil, errors.New("ingressRoute service port not defined")
}
hasValidPort := false
for _, p := range svc.Spec.Ports {
if p.Port == port {
return &p, nil
}
if p.Port != 0 {
hasValidPort = true
}
}
if svc.Spec.Type != corev1.ServiceTypeExternalName {
return nil, fmt.Errorf("service port not found: %d", port)
}
if hasValidPort {
log.WithoutContext().
Warning("The port %d from IngressRoute doesn't match with ports defined in the ExternalName service %s/%s.", port, svc.Namespace, svc.Name)
}
return &corev1.ServicePort{Port: port}, nil
}
func createErrorPageMiddleware(client Client, namespace string, errorPage *v1alpha1.ErrorPage) (*dynamic.ErrorPage, *dynamic.Service, error) {
if errorPage == nil {
return nil, nil, nil
}
errorPageMiddleware := &dynamic.ErrorPage{
Status: errorPage.Status,
Query: errorPage.Query,
}
balancerServerHTTP, err := configBuilder{client}.buildServersLB(namespace, errorPage.Service.LoadBalancerSpec)
if err != nil {
return nil, nil, err
}
return errorPageMiddleware, balancerServerHTTP, nil
}
func createForwardAuthMiddleware(k8sClient Client, namespace string, auth *v1alpha1.ForwardAuth) (*dynamic.ForwardAuth, error) {
if auth == nil {
return nil, nil
}
if len(auth.Address) == 0 {
return nil, fmt.Errorf("forward authentication requires an address")
}
forwardAuth := &dynamic.ForwardAuth{
Address: auth.Address,
TrustForwardHeader: auth.TrustForwardHeader,
AuthResponseHeaders: auth.AuthResponseHeaders,
}
if auth.TLS == nil {
return forwardAuth, nil
}
forwardAuth.TLS = &dynamic.ClientTLS{
CAOptional: auth.TLS.CAOptional,
InsecureSkipVerify: auth.TLS.InsecureSkipVerify,
}
if len(auth.TLS.CASecret) > 0 {
caSecret, err := loadCASecret(namespace, auth.TLS.CASecret, k8sClient)
if err != nil {
return nil, fmt.Errorf("failed to load auth ca secret: %w", err)
}
forwardAuth.TLS.CA = caSecret
}
if len(auth.TLS.CertSecret) > 0 {
authSecretCert, authSecretKey, err := loadAuthTLSSecret(namespace, auth.TLS.CertSecret, k8sClient)
if err != nil {
return nil, fmt.Errorf("failed to load auth secret: %w", err)
}
forwardAuth.TLS.Cert = authSecretCert
forwardAuth.TLS.Key = authSecretKey
}
return forwardAuth, nil
}
func loadCASecret(namespace, secretName string, k8sClient Client) (string, error) {
secret, ok, err := k8sClient.GetSecret(namespace, secretName)
if err != nil {
return "", fmt.Errorf("failed to fetch secret '%s/%s': %w", namespace, secretName, err)
}
if !ok {
return "", fmt.Errorf("secret '%s/%s' not found", namespace, secretName)
}
if secret == nil {
return "", fmt.Errorf("data for secret '%s/%s' must not be nil", namespace, secretName)
}
if len(secret.Data) != 1 {
return "", fmt.Errorf("found %d elements for secret '%s/%s', must be single element exactly", len(secret.Data), namespace, secretName)
}
for _, v := range secret.Data {
return string(v), nil
}
return "", nil
}
func loadAuthTLSSecret(namespace, secretName string, k8sClient Client) (string, string, error) {
secret, exists, err := k8sClient.GetSecret(namespace, secretName)
if err != nil {
return "", "", fmt.Errorf("failed to fetch secret '%s/%s': %w", namespace, secretName, err)
}
if !exists {
return "", "", fmt.Errorf("secret '%s/%s' does not exist", namespace, secretName)
}
if secret == nil {
return "", "", fmt.Errorf("data for secret '%s/%s' must not be nil", namespace, secretName)
}
if len(secret.Data) != 2 {
return "", "", fmt.Errorf("found %d elements for secret '%s/%s', must be two elements exactly", len(secret.Data), namespace, secretName)
}
return getCertificateBlocks(secret, namespace, secretName)
}
func createBasicAuthMiddleware(client Client, namespace string, basicAuth *v1alpha1.BasicAuth) (*dynamic.BasicAuth, error) {
if basicAuth == nil {
return nil, nil
}
credentials, err := getAuthCredentials(client, basicAuth.Secret, namespace)
if err != nil {
return nil, err
}
return &dynamic.BasicAuth{
Users: credentials,
Realm: basicAuth.Realm,
RemoveHeader: basicAuth.RemoveHeader,
HeaderField: basicAuth.HeaderField,
}, nil
}
func createDigestAuthMiddleware(client Client, namespace string, digestAuth *v1alpha1.DigestAuth) (*dynamic.DigestAuth, error) {
if digestAuth == nil {
return nil, nil
}
credentials, err := getAuthCredentials(client, digestAuth.Secret, namespace)
if err != nil {
return nil, err
}
return &dynamic.DigestAuth{
Users: credentials,
Realm: digestAuth.Realm,
RemoveHeader: digestAuth.RemoveHeader,
HeaderField: digestAuth.HeaderField,
}, nil
}
func getAuthCredentials(k8sClient Client, authSecret, namespace string) ([]string, error) {
if authSecret == "" {
return nil, fmt.Errorf("auth secret must be set")
}
auth, err := loadAuthCredentials(namespace, authSecret, k8sClient)
if err != nil {
return nil, fmt.Errorf("failed to load auth credentials: %w", err)
}
return auth, nil
}
func loadAuthCredentials(namespace, secretName string, k8sClient Client) ([]string, error) {
secret, ok, err := k8sClient.GetSecret(namespace, secretName)
if err != nil {
return nil, fmt.Errorf("failed to fetch secret '%s/%s': %w", namespace, secretName, err)
}
if !ok {
return nil, fmt.Errorf("secret '%s/%s' not found", namespace, secretName)
}
if secret == nil {
return nil, fmt.Errorf("data for secret '%s/%s' must not be nil", namespace, secretName)
}
if len(secret.Data) != 1 {
return nil, fmt.Errorf("found %d elements for secret '%s/%s', must be single element exactly", len(secret.Data), namespace, secretName)
}
var firstSecret []byte
for _, v := range secret.Data {
firstSecret = v
break
}
var credentials []string
scanner := bufio.NewScanner(bytes.NewReader(firstSecret))
for scanner.Scan() {
if cred := scanner.Text(); len(cred) > 0 {
credentials = append(credentials, cred)
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading secret for %s/%s: %w", namespace, secretName, err)
}
if len(credentials) == 0 {
return nil, fmt.Errorf("secret '%s/%s' does not contain any credentials", namespace, secretName)
}
return credentials, nil
}
func createChainMiddleware(ctx context.Context, namespace string, chain *v1alpha1.Chain) *dynamic.Chain {
if chain == nil {
return nil
}
var mds []string
for _, mi := range chain.Middlewares {
if strings.Contains(mi.Name, providerNamespaceSeparator) {
if len(mi.Namespace) > 0 {
log.FromContext(ctx).
Warnf("namespace %q is ignored in cross-provider context", mi.Namespace)
}
mds = append(mds, mi.Name)
continue
}
ns := mi.Namespace
if len(ns) == 0 {
ns = namespace
}
mds = append(mds, makeID(ns, mi.Name))
}
return &dynamic.Chain{Middlewares: mds}
}
func buildTLSOptions(ctx context.Context, client Client) map[string]tls.Options {
tlsOptionsCRD := client.GetTLSOptions()
var tlsOptions map[string]tls.Options
if len(tlsOptionsCRD) == 0 {
return tlsOptions
}
tlsOptions = make(map[string]tls.Options)
var nsDefault []string
for _, tlsOption := range tlsOptionsCRD {
logger := log.FromContext(log.With(ctx, log.Str("tlsOption", tlsOption.Name), log.Str("namespace", tlsOption.Namespace)))
var clientCAs []tls.FileOrContent
for _, secretName := range tlsOption.Spec.ClientAuth.SecretNames {
secret, exists, err := client.GetSecret(tlsOption.Namespace, secretName)
if err != nil {
logger.Errorf("Failed to fetch secret %s/%s: %v", tlsOption.Namespace, secretName, err)
continue
}
if !exists {
logger.Warnf("Secret %s/%s does not exist", tlsOption.Namespace, secretName)
continue
}
cert, err := getCABlocks(secret, tlsOption.Namespace, secretName)
if err != nil {
logger.Errorf("Failed to extract CA from secret %s/%s: %v", tlsOption.Namespace, secretName, err)
continue
}
clientCAs = append(clientCAs, tls.FileOrContent(cert))
}
id := makeID(tlsOption.Namespace, tlsOption.Name)
// If the name is default, we override the default config.
if tlsOption.Name == "default" {
id = tlsOption.Name
nsDefault = append(nsDefault, tlsOption.Namespace)
}
tlsOptions[id] = tls.Options{
MinVersion: tlsOption.Spec.MinVersion,
MaxVersion: tlsOption.Spec.MaxVersion,
CipherSuites: tlsOption.Spec.CipherSuites,
CurvePreferences: tlsOption.Spec.CurvePreferences,
ClientAuth: tls.ClientAuth{
CAFiles: clientCAs,
ClientAuthType: tlsOption.Spec.ClientAuth.ClientAuthType,
},
SniStrict: tlsOption.Spec.SniStrict,
PreferServerCipherSuites: tlsOption.Spec.PreferServerCipherSuites,
}
}
if len(nsDefault) > 1 {
delete(tlsOptions, "default")
log.FromContext(ctx).Errorf("Default TLS Options defined in multiple namespaces: %v", nsDefault)
}
return tlsOptions
}
func buildTLSStores(ctx context.Context, client Client) map[string]tls.Store {
tlsStoreCRD := client.GetTLSStores()
var tlsStores map[string]tls.Store
if len(tlsStoreCRD) == 0 {
return tlsStores
}
tlsStores = make(map[string]tls.Store)
var nsDefault []string
for _, tlsStore := range tlsStoreCRD {
namespace := tlsStore.Namespace
secretName := tlsStore.Spec.DefaultCertificate.SecretName
logger := log.FromContext(log.With(ctx, log.Str("tlsStore", tlsStore.Name), log.Str("namespace", namespace), log.Str("secretName", secretName)))
secret, exists, err := client.GetSecret(namespace, secretName)
if err != nil {
logger.Errorf("Failed to fetch secret %s/%s: %v", namespace, secretName, err)
continue
}
if !exists {
logger.Errorf("Secret %s/%s does not exist", namespace, secretName)
continue
}
cert, key, err := getCertificateBlocks(secret, namespace, secretName)
if err != nil {
logger.Errorf("Could not get certificate blocks: %v", err)
continue
}
id := makeID(tlsStore.Namespace, tlsStore.Name)
// If the name is default, we override the default config.
if tlsStore.Name == "default" {
id = tlsStore.Name
nsDefault = append(nsDefault, tlsStore.Namespace)
}
tlsStores[id] = tls.Store{
DefaultCertificate: &tls.Certificate{
CertFile: tls.FileOrContent(cert),
KeyFile: tls.FileOrContent(key),
},
}
}
if len(nsDefault) > 1 {
delete(tlsStores, "default")
log.FromContext(ctx).Errorf("Default TLS Stores defined in multiple namespaces: %v", nsDefault)
}
return tlsStores
}
func makeServiceKey(rule, ingressName string) (string, error) {
h := sha256.New()
if _, err := h.Write([]byte(rule)); err != nil {
return "", err
}
key := fmt.Sprintf("%s-%.10x", ingressName, h.Sum(nil))
return key, nil
}
func makeID(namespace, name string) string {
if namespace == "" {
return name
}
return namespace + "-" + name
}
func shouldProcessIngress(ingressClass, ingressClassAnnotation string) bool {
return ingressClass == ingressClassAnnotation ||
(len(ingressClass) == 0 && ingressClassAnnotation == traefikDefaultIngressClass)
}
func getTLS(k8sClient Client, secretName, namespace string) (*tls.CertAndStores, error) {
secret, exists, err := k8sClient.GetSecret(namespace, secretName)
if err != nil {
return nil, fmt.Errorf("failed to fetch secret %s/%s: %w", namespace, secretName, err)
}
if !exists {
return nil, fmt.Errorf("secret %s/%s does not exist", namespace, secretName)
}
cert, key, err := getCertificateBlocks(secret, namespace, secretName)
if err != nil {
return nil, err
}
return &tls.CertAndStores{
Certificate: tls.Certificate{
CertFile: tls.FileOrContent(cert),
KeyFile: tls.FileOrContent(key),
},
}, nil
}
func getTLSConfig(tlsConfigs map[string]*tls.CertAndStores) []*tls.CertAndStores {
var secretNames []string
for secretName := range tlsConfigs {
secretNames = append(secretNames, secretName)
}
sort.Strings(secretNames)
var configs []*tls.CertAndStores
for _, secretName := range secretNames {
configs = append(configs, tlsConfigs[secretName])
}
return configs
}
func getCertificateBlocks(secret *corev1.Secret, namespace, secretName string) (string, string, error) {
var missingEntries []string
tlsCrtData, tlsCrtExists := secret.Data["tls.crt"]
if !tlsCrtExists {
missingEntries = append(missingEntries, "tls.crt")
}
tlsKeyData, tlsKeyExists := secret.Data["tls.key"]
if !tlsKeyExists {
missingEntries = append(missingEntries, "tls.key")
}
if len(missingEntries) > 0 {
return "", "", fmt.Errorf("secret %s/%s is missing the following TLS data entries: %s",
namespace, secretName, strings.Join(missingEntries, ", "))
}
cert := string(tlsCrtData)
if cert == "" {
missingEntries = append(missingEntries, "tls.crt")
}
key := string(tlsKeyData)
if key == "" {
missingEntries = append(missingEntries, "tls.key")
}
if len(missingEntries) > 0 {
return "", "", fmt.Errorf("secret %s/%s contains the following empty TLS data entries: %s",
namespace, secretName, strings.Join(missingEntries, ", "))
}
return cert, key, nil
}
func getCABlocks(secret *corev1.Secret, namespace, secretName string) (string, error) {
tlsCrtData, tlsCrtExists := secret.Data["tls.ca"]
if !tlsCrtExists {
return "", fmt.Errorf("the tls.ca entry is missing from secret %s/%s", namespace, secretName)
}
cert := string(tlsCrtData)
if cert == "" {
return "", fmt.Errorf("the tls.ca entry in secret %s/%s is empty", namespace, secretName)
}
return cert, nil
}
func throttleEvents(ctx context.Context, throttleDuration time.Duration, pool *safe.Pool, eventsChan <-chan interface{}) chan interface{} {
if throttleDuration == 0 {
return nil
}
// Create a buffered channel to hold the pending event (if we're delaying processing the event due to throttling)
eventsChanBuffered := make(chan interface{}, 1)
// Run a goroutine that reads events from eventChan and does a non-blocking write to pendingEvent.
// This guarantees that writing to eventChan will never block,
// and that pendingEvent will have something in it if there's been an event since we read from that channel.
pool.GoCtx(func(ctxPool context.Context) {
for {
select {
case <-ctxPool.Done():
return
case nextEvent := <-eventsChan:
select {
case eventsChanBuffered <- nextEvent:
default:
// We already have an event in eventsChanBuffered, so we'll do a refresh as soon as our throttle allows us to.
// It's fine to drop the event and keep whatever's in the buffer -- we don't do different things for different events
log.FromContext(ctx).Debugf("Dropping event kind %T due to throttling", nextEvent)
}
}
}
})
return eventsChanBuffered
}
| [
"\"KUBERNETES_SERVICE_HOST\"",
"\"KUBERNETES_SERVICE_PORT\"",
"\"KUBECONFIG\"",
"\"KUBECONFIG\"",
"\"KUBECONFIG\""
]
| []
| [
"KUBERNETES_SERVICE_HOST",
"KUBERNETES_SERVICE_PORT",
"KUBECONFIG"
]
| [] | ["KUBERNETES_SERVICE_HOST", "KUBERNETES_SERVICE_PORT", "KUBECONFIG"] | go | 3 | 0 | |
pysftp.py | """A friendly Python SFTP interface."""
from __future__ import print_function
import os
from contextlib import contextmanager
import ntpath
import posixpath
import socket
from stat import S_IMODE, S_ISDIR, S_ISREG
import tempfile
import warnings
import paramiko
from paramiko import SSHException # make available
from paramiko import AuthenticationException # make available
from paramiko import AgentKey
__version__ = "0.2.9"
# pylint: disable = R0913
def st_mode_to_int(val):
'''SFTAttributes st_mode returns an stat type that shows more than what
can be set. Trim off those bits and convert to an int representation.
if you want an object that was `chmod 711` to return a value of 711, use
this function
:param int val: the value of an st_mode attr returned by SFTPAttributes
:returns int: integer representation of octal mode
'''
return int(str(oct(S_IMODE(val)))[-3:])
class ConnectionException(Exception):
"""Exception raised for connection problems
Attributes:
message -- explanation of the error
"""
def __init__(self, host, port):
# Call the base class constructor with the parameters it needs
Exception.__init__(self, host, port)
self.message = 'Could not connect to host:port. %s:%s'
class CredentialException(Exception):
"""Exception raised for credential problems
Attributes:
message -- explanation of the error
"""
def __init__(self, message):
# Call the base class constructor with the parameters it needs
Exception.__init__(self, message)
self.message = message
class WTCallbacks(object):
'''an object to house the callbacks, used internally'''
def __init__(self):
'''set instance vars'''
self._flist = []
self._dlist = []
self._ulist = []
def file_cb(self, pathname):
'''called for regular files, appends pathname to .flist
:param str pathname: file path
'''
self._flist.append(pathname)
def dir_cb(self, pathname):
'''called for directories, appends pathname to .dlist
:param str pathname: directory path
'''
self._dlist.append(pathname)
def unk_cb(self, pathname):
'''called for unknown file types, appends pathname to .ulist
:param str pathname: unknown entity path
'''
self._ulist.append(pathname)
@property
def flist(self):
'''return a sorted list of files currently traversed
:getter: returns the list
:setter: sets the list
:type: list
'''
return sorted(self._flist)
@flist.setter
def flist(self, val):
'''setter for _flist '''
self._flist = val
@property
def dlist(self):
'''return a sorted list of directories currently traversed
:getter: returns the list
:setter: sets the list
:type: list
'''
return sorted(self._dlist)
@dlist.setter
def dlist(self, val):
'''setter for _dlist '''
self._dlist = val
@property
def ulist(self):
'''return a sorted list of unknown entities currently traversed
:getter: returns the list
:setter: sets the list
:type: list
'''
return sorted(self._ulist)
@ulist.setter
def ulist(self, val):
'''setter for _ulist '''
self._ulist = val
class CnOpts(object):
'''additional connection options beyond authentication
:ivar bool|str log: initial value: False -
log connection/handshake details? If set to True,
pysftp creates a temporary file and logs to that. If set to a valid
path and filename, pysftp logs to that. The name of the logfile can
be found at ``.logfile``
:ivar bool compression: initial value: False - Enables compression on the
transport, if set to True.
:ivar list|None ciphers: initial value: None -
List of ciphers to use in order.
'''
def __init__(self):
# self.ciphers = None
# self.compression = False
self.log = False
self.compression = False
self.ciphers = None
class Connection(object):
"""Connects and logs into the specified hostname.
Arguments that are not given are guessed from the environment.
:param str host:
The Hostname or IP of the remote machine.
:param str|None username: *Default: None* -
Your username at the remote machine.
:param str|obj|None private_key: *Default: None* -
path to private key file(str) or paramiko.AgentKey
:param str|None password: *Default: None* -
Your password at the remote machine.
:param int port: *Default: 22* -
The SSH port of the remote machine.
:param str|None private_key_pass: *Default: None* -
password to use, if private_key is encrypted.
:param list|None ciphers: *Deprecated* -
see ``pysftp.CnOpts`` and ``cnopts`` parameter
:param bool|str log: *Deprecated* -
see ``pysftp.CnOpts`` and ``cnopts`` parameter
:param None|CnOpts cnopts: *Default: None* - extra connection options
set in a CnOpts object.
:returns: (obj) connection to the requested host
:raises ConnectionException:
:raises CredentialException:
:raises SSHException:
:raises AuthenticationException:
:raises PasswordRequiredException:
"""
def __init__(self,
host,
username=None,
private_key=None,
password=None,
port=22,
private_key_pass=None,
ciphers=None,
log=False,
cnopts=None
):
if cnopts is None:
self._cnopts = CnOpts()
else:
self._cnopts = cnopts
# TODO: remove this if block and log param above in v0.3.0
if log:
wmsg = "log parameter is deprecated and will be remove in 0.3.0. "\
"Use cnopts param."
warnings.warn(wmsg, DeprecationWarning)
self._cnopts.log = log
# TODO: remove this if block and log param above in v0.3.0
if ciphers is not None:
wmsg = "ciphers parameter is deprecated and will be remove in "\
"0.3.0. Use cnopts param."
warnings.warn(wmsg, DeprecationWarning)
self._cnopts.ciphers = ciphers
self._sftp_live = False
self._sftp = None
if not username:
username = os.environ['LOGNAME']
self._logfile = self._cnopts.log
if self._cnopts.log:
if isinstance(self._cnopts.log, bool):
# Log to a temporary file.
fhnd, self._logfile = tempfile.mkstemp('.txt', 'ssh-')
os.close(fhnd) # don't want os file descriptors open
paramiko.util.log_to_file(self._logfile)
# Begin the SSH transport.
self._transport_live = False
try:
self._transport = paramiko.Transport((host, port))
# Set security ciphers if set
if self._cnopts.ciphers is not None:
ciphers = self._cnopts.ciphers
self._transport.get_security_options().ciphers = ciphers
self._transport_live = True
except (AttributeError, socket.gaierror):
# couldn't connect
raise ConnectionException(host, port)
# Toggle compression
self._transport.use_compression(self._cnopts.compression)
# Authenticate the transport. prefer password if given
if password is not None:
# Using Password.
self._transport.connect(username=username, password=password)
else:
# Use Private Key.
if not private_key:
# Try to use default key.
if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')):
private_key = '~/.ssh/id_rsa'
elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')):
private_key = '~/.ssh/id_dsa'
else:
raise CredentialException("You have not specified a "
"password or key.")
if not isinstance(private_key, AgentKey):
private_key_file = os.path.expanduser(private_key)
try: # try rsa
rsakey = paramiko.RSAKey
prv_key = rsakey.from_private_key_file(private_key_file,
private_key_pass)
except paramiko.SSHException: # if it fails, try dss
dsskey = paramiko.DSSKey
prv_key = dsskey.from_private_key_file(private_key_file,
private_key_pass)
else:
# use the paramiko agent key
prv_key = private_key
self._transport.connect(username=username, pkey=prv_key)
def _sftp_connect(self):
"""Establish the SFTP connection."""
if not self._sftp_live:
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
self._sftp_live = True
@property
def pwd(self):
'''return the current working directory
:returns: (str) current working directory
'''
self._sftp_connect()
return self._sftp.normalize('.')
def get(self, remotepath, localpath=None, callback=None,
preserve_mtime=False):
"""Copies a file between the remote host and the local host.
:param str remotepath: the remote path and filename, source
:param str localpath:
the local path and filename to copy, destination. If not specified,
file is copied to local current working directory
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred.
:param bool preserve_mtime:
*Default: False* - make the modification time(st_mtime) on the
local file match the time on the remote. (st_atime can differ
because stat'ing the localfile can/does update it's st_atime)
:returns: None
:raises: IOError
"""
if not localpath:
localpath = os.path.split(remotepath)[1]
self._sftp_connect()
if preserve_mtime:
sftpattrs = self._sftp.stat(remotepath)
self._sftp.get(remotepath, localpath, callback=callback)
if preserve_mtime:
os.utime(localpath, (sftpattrs.st_atime, sftpattrs.st_mtime))
def get_d(self, remotedir, localdir, preserve_mtime=False):
"""get the contents of remotedir and write to locadir. (non-recursive)
:param str remotedir: the remote directory to copy from (source)
:param str localdir: the local directory to copy to (target)
:param bool preserve_mtime: *Default: False* -
preserve modification time on files
:returns: None
:raises:
"""
self._sftp_connect()
with self.cd(remotedir):
for sattr in self._sftp.listdir_attr('.'):
if S_ISREG(sattr.st_mode):
rname = sattr.filename
self.get(rname, reparent(localdir, rname),
preserve_mtime=preserve_mtime)
def get_r(self, remotedir, localdir, preserve_mtime=False):
"""recursively copy remotedir structure to localdir
:param str remotedir: the remote directory to copy from
:param str localdir: the local directory to copy to
:param bool preserve_mtime: *Default: False* -
preserve modification time on files
:returns: None
:raises:
"""
self._sftp_connect()
wtcb = WTCallbacks()
self.walktree(remotedir, wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb)
# handle directories we recursed through
for dname in wtcb.dlist:
for subdir in path_advance(dname):
try:
os.mkdir(reparent(localdir, subdir))
# force result to a list for setter,
wtcb.dlist = wtcb.dlist + [subdir, ]
except OSError: # dir exists
pass
for fname in wtcb.flist:
# they may have told us to start down farther, so we may not have
# recursed through some, ensure local dir structure matches
head, _ = os.path.split(fname)
if head not in wtcb.dlist:
for subdir in path_advance(head):
if subdir not in wtcb.dlist and subdir != '.':
os.mkdir(reparent(localdir, subdir))
wtcb.dlist = wtcb.dlist + [subdir, ]
self.get(fname,
reparent(localdir, fname),
preserve_mtime=preserve_mtime)
def getfo(self, remotepath, flo, callback=None):
"""Copy a remote file (remotepath) to a file-like object, flo.
:param str remotepath: the remote path and filename, source
:param flo: open file like object to write, destination.
:param callable callback:
optional callback function (form: ``func(int, int``)) that accepts
the bytes transferred so far and the total bytes to be transferred.
:returns: (int) the number of bytes written to the opened file object
:raises: Any exception raised by operations will be passed through.
"""
self._sftp_connect()
return self._sftp.getfo(remotepath, flo, callback=callback)
def put(self, localpath, remotepath=None, callback=None, confirm=True,
preserve_mtime=False):
"""Copies a file between the local host and the remote host.
:param str localpath: the local path and filename
:param str remotepath:
the remote path, else the remote :attr:`.pwd` and filename is used.
:param callable callback:
optional callback function (form: ``func(int, int``)) that accepts
the bytes transferred so far and the total bytes to be transferred.
:param bool confirm:
whether to do a stat() on the file afterwards to confirm the file
size
:param bool preserve_mtime:
*Default: False* - make the modification time(st_mtime) on the
remote file match the time on the local. (st_atime can differ
because stat'ing the localfile can/does update it's st_atime)
:returns:
(obj) SFTPAttributes containing attributes about the given file
:raises IOError: if remotepath doesn't exist
:raises OSError: if localpath doesn't exist
"""
if not remotepath:
remotepath = os.path.split(localpath)[1]
self._sftp_connect()
if preserve_mtime:
local_stat = os.stat(localpath)
times = (local_stat.st_atime, local_stat.st_mtime)
sftpattrs = self._sftp.put(localpath, remotepath, callback=callback,
confirm=confirm)
if preserve_mtime:
self._sftp.utime(remotepath, times)
sftpattrs = self._sftp.stat(remotepath)
return sftpattrs
def put_d(self, localpath, remotepath, confirm=True, preserve_mtime=False):
"""Copies a local directory's contents to a remotepath
:param str localpath: the local path to copy (source)
:param str remotepath:
the remote path to copy to (target)
:param bool confirm:
whether to do a stat() on the file afterwards to confirm the file
size
:param bool preserve_mtime:
*Default: False* - make the modification time(st_mtime) on the
remote file match the time on the local. (st_atime can differ
because stat'ing the localfile can/does update it's st_atime)
:returns: None
:raises IOError: if remotepath doesn't exist
:raises OSError: if localpath doesn't exist
"""
self._sftp_connect()
wtcb = WTCallbacks()
cur_local_dir = os.getcwd()
os.chdir(localpath)
walktree('.', wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb,
recurse=False)
for fname in wtcb.flist:
src = os.path.join(localpath, fname)
dest = reparent(remotepath, fname)
# print('put', src, dest)
self.put(src, dest, confirm=confirm, preserve_mtime=preserve_mtime)
# restore local directory
os.chdir(cur_local_dir)
def put_r(self, localpath, remotepath, confirm=True, preserve_mtime=False):
"""Recursively copies a local directory's contents to a remotepath
:param str localpath: the local path to copy (source)
:param str remotepath:
the remote path to copy to (target)
:param bool confirm:
whether to do a stat() on the file afterwards to confirm the file
size
:param bool preserve_mtime:
*Default: False* - make the modification time(st_mtime) on the
remote file match the time on the local. (st_atime can differ
because stat'ing the localfile can/does update it's st_atime)
:returns: None
:raises IOError: if remotepath doesn't exist
:raises OSError: if localpath doesn't exist
"""
self._sftp_connect()
wtcb = WTCallbacks()
cur_local_dir = os.getcwd()
os.chdir(localpath)
walktree('.', wtcb.file_cb, wtcb.dir_cb, wtcb.unk_cb)
# restore local directory
os.chdir(cur_local_dir)
for dname in wtcb.dlist:
if dname != '.':
self.mkdir(reparent(remotepath, dname))
for fname in wtcb.flist:
head, _ = os.path.split(fname)
if head not in wtcb.dlist:
for subdir in path_advance(head):
if subdir not in wtcb.dlist and subdir != '.':
self.mkdir(reparent(remotepath, subdir))
wtcb.dlist = wtcb.dlist + [subdir, ]
src = os.path.join(localpath, fname)
dest = reparent(remotepath, fname)
# print('put', src, dest)
self.put(src, dest, confirm=confirm, preserve_mtime=preserve_mtime)
def putfo(self, flo, remotepath=None, file_size=0, callback=None,
confirm=True):
"""Copies the contents of a file like object to remotepath.
:param flo: a file-like object that supports .read()
:param str remotepath: the remote path.
:param int file_size:
the size of flo, if not given the second param passed to the
callback function will always be 0.
:param callable callback:
optional callback function (form: ``func(int, int``)) that accepts
the bytes transferred so far and the total bytes to be transferred.
:param bool confirm:
whether to do a stat() on the file afterwards to confirm the file
size
:returns:
(obj) SFTPAttributes containing attributes about the given file
:raises: TypeError, if remotepath not specified, any underlying error
"""
self._sftp_connect()
return self._sftp.putfo(flo, remotepath, file_size=file_size,
callback=callback, confirm=confirm)
def execute(self, command):
"""Execute the given commands on a remote machine. The command is
executed without regard to the remote :attr:`.pwd`.
:param str command: the command to execute.
:returns: (list of str) representing the results of the command
:raises: Any exception raised by command will be passed through.
"""
channel = self._transport.open_session()
channel.exec_command(command)
output = channel.makefile('rb', -1).readlines()
if output:
return output
else:
return channel.makefile_stderr('rb', -1).readlines()
@contextmanager
def cd(self, remotepath=None):
"""context manager that can change to a optionally specified remote
directory and restores the old pwd on exit.
:param str|None remotepath: *Default: None* -
remotepath to temporarily make the current directory
:returns: None
:raises: IOError, if remote path doesn't exist
"""
try:
original_path = self.pwd
if remotepath is not None:
self.cwd(remotepath)
yield
finally:
self.cwd(original_path)
def chdir(self, remotepath):
"""change the current working directory on the remote
:param str remotepath: the remote path to change to
:returns: None
:raises: IOError, if path does not exist
"""
self._sftp_connect()
self._sftp.chdir(remotepath)
cwd = chdir # synonym for chdir
def chmod(self, remotepath, mode=777):
"""set the mode of a remotepath to mode, where mode is an integer
representation of the octal mode to use.
:param str remotepath: the remote path/file to modify
:param int mode: *Default: 777* -
int representation of octal mode for directory
:returns: None
:raises: IOError, if the file doesn't exist
"""
self._sftp_connect()
self._sftp.chmod(remotepath, mode=int(str(mode), 8))
def chown(self, remotepath, uid=None, gid=None):
""" set uid and/or gid on a remotepath, you may specify either or both.
Unless you have **permission** to do this on the remote server, you
will raise an IOError: 13 - permission denied
:param str remotepath: the remote path/file to modify
:param int uid: the user id to set on the remotepath
:param int gid: the group id to set on the remotepath
:returns: None
:raises:
IOError, if you don't have permission or the file doesn't exist
"""
self._sftp_connect()
if uid is None or gid is None:
if uid is None and gid is None: # short circuit if no change
return
rstat = self._sftp.stat(remotepath)
if uid is None:
uid = rstat.st_uid
if gid is None:
gid = rstat.st_gid
self._sftp.chown(remotepath, uid=uid, gid=gid)
def getcwd(self):
"""return the current working directory on the remote. This is a wrapper
for paramiko's method and not to be confused with the SFTP command,
cwd.
:returns: (str) the current remote path. None, if not set.
"""
self._sftp_connect()
return self._sftp.getcwd()
def listdir(self, remotepath='.'):
"""return a list of files/directories for the given remote path.
Unlike, paramiko, the directory listing is sorted.
:param str remotepath: path to list on the server
:returns: (list of str) directory entries, sorted
"""
self._sftp_connect()
return sorted(self._sftp.listdir(remotepath))
def listdir_attr(self, remotepath='.'):
"""return a list of SFTPAttribute objects of the files/directories for
the given remote path. The list is in arbitrary order. It does not
include the special entries '.' and '..'.
The returned SFTPAttributes objects will each have an additional field:
longname, which may contain a formatted string of the file's
attributes, in unix format. The content of this string will depend on
the SFTP server.
:param str remotepath: path to list on the server
:returns: (list of SFTPAttributes), sorted
"""
self._sftp_connect()
return sorted(self._sftp.listdir_attr(remotepath),
key=lambda attr: attr.filename)
def mkdir(self, remotepath, mode=777):
"""Create a directory named remotepath with mode. On some systems,
mode is ignored. Where it is used, the current umask value is first
masked out.
:param str remotepath: directory to create`
:param int mode: *Default: 777* -
int representation of octal mode for directory
:returns: None
"""
self._sftp_connect()
self._sftp.mkdir(remotepath, mode=int(str(mode), 8))
def normalize(self, remotepath):
"""Return the expanded path, w.r.t the server, of a given path. This
can be used to resolve symlinks or determine what the server believes
to be the :attr:`.pwd`, by passing '.' as remotepath.
:param str remotepath: path to be normalized
:return: (str) normalized form of the given path
:raises: IOError, if remotepath can't be resolved
"""
self._sftp_connect()
return self._sftp.normalize(remotepath)
def isdir(self, remotepath):
"""return true, if remotepath is a directory
:param str remotepath: the path to test
:returns: (bool)
"""
self._sftp_connect()
try:
result = S_ISDIR(self._sftp.stat(remotepath).st_mode)
except IOError: # no such file
result = False
return result
def isfile(self, remotepath):
"""return true if remotepath is a file
:param str remotepath: the path to test
:returns: (bool)
"""
self._sftp_connect()
try:
result = S_ISREG(self._sftp.stat(remotepath).st_mode)
except IOError: # no such file
result = False
return result
def makedirs(self, remotedir, mode=777):
"""create all directories in remotedir as needed, setting their mode
to mode, if created.
If remotedir already exists, silently complete. If a regular file is
in the way, raise an exception.
:param str remotedir: the directory structure to create
:param int mode: *Default: 777* -
int representation of octal mode for directory
:returns: None
:raises: OSError
"""
self._sftp_connect()
if self.isdir(remotedir):
pass
elif self.isfile(remotedir):
raise OSError("a file with the same name as the remotedir, "
"'%s', already exists." % remotedir)
else:
head, tail = os.path.split(remotedir)
if head and not self.isdir(head):
self.makedirs(head, mode)
if tail:
self.mkdir(remotedir, mode=mode)
def readlink(self, remotelink):
"""Return the target of a symlink (shortcut). The result will be
an absolute pathname.
:param str remotelink: remote path of the symlink
:return: (str) absolute path to target
"""
self._sftp_connect()
return self._sftp.normalize(self._sftp.readlink(remotelink))
def remove(self, remotefile):
"""remove the file @ remotefile, remotefile may include a path, if no
path, then :attr:`.pwd` is used. This method only works on files
:param str remotefile: the remote file to delete
:returns: None
:raises: IOError
"""
self._sftp_connect()
self._sftp.remove(remotefile)
unlink = remove # synonym for remove
def rmdir(self, remotepath):
"""remove remote directory
:param str remotepath: the remote directory to remove
:returns: None
"""
self._sftp_connect()
self._sftp.rmdir(remotepath)
def rename(self, remote_src, remote_dest):
"""rename a file or directory on the remote host.
:param str remote_src: the remote file/directory to rename
:param str remote_dest: the remote file/directory to put it
:returns: None
:raises: IOError
"""
self._sftp_connect()
self._sftp.rename(remote_src, remote_dest)
def stat(self, remotepath):
"""return information about file/directory for the given remote path
:param str remotepath: path to stat
:returns: (obj) SFTPAttributes
"""
self._sftp_connect()
return self._sftp.stat(remotepath)
def lstat(self, remotepath):
"""return information about file/directory for the given remote path,
without following symbolic links. Otherwise, the same as .stat()
:param str remotepath: path to stat
:returns: (obj) SFTPAttributes object
"""
self._sftp_connect()
return self._sftp.lstat(remotepath)
def close(self):
"""Closes the connection and cleans up."""
# Close SFTP Connection.
if self._sftp_live:
self._sftp.close()
self._sftp_live = False
# Close the SSH Transport.
if self._transport_live:
self._transport.close()
self._transport_live = False
# clean up any loggers
if self._cnopts.log:
# if handlers are active they hang around until the app exits
# this closes and removes the handlers if in use at close
import logging
lgr = logging.getLogger("paramiko")
if lgr:
lgr.handlers = []
def open(self, remote_file, mode='r', bufsize=-1):
"""Open a file on the remote server.
See http://paramiko-docs.readthedocs.org/en/latest/api/sftp.html for
details.
:param str remote_file: name of the file to open.
:param str mode:
mode (Python-style) to open file (always assumed binary)
:param int bufsize: *Default: -1* - desired buffering
:returns: (obj) SFTPFile, a handle the remote open file
:raises: IOError, if the file could not be opened.
"""
self._sftp_connect()
return self._sftp.open(remote_file, mode=mode, bufsize=bufsize)
def exists(self, remotepath):
"""Test whether a remotepath exists.
:param str remotepath: the remote path to verify
:returns: (bool) True, if remotepath exists, else False
"""
self._sftp_connect()
try:
self._sftp.stat(remotepath)
except IOError:
return False
return True
def lexists(self, remotepath):
"""Test whether a remotepath exists. Returns True for broken symbolic
links
:param str remotepath: the remote path to verify
:returns: (bool), True, if lexists, else False
"""
self._sftp_connect()
try:
self._sftp.lstat(remotepath)
except IOError:
return False
return True
def symlink(self, remote_src, remote_dest):
'''create a symlink for a remote file on the server
:param str remote_src: path of original file
:param str remote_dest: path of the created symlink
:returns: None
:raises:
any underlying error, IOError if something already exists at
remote_dest
'''
self._sftp_connect()
self._sftp.symlink(remote_src, remote_dest)
def truncate(self, remotepath, size):
"""Change the size of the file specified by path. Used to modify the
size of the file, just like the truncate method on Python file objects.
The new file size is confirmed and returned.
:param str remotepath: remote file path to modify
:param int|long size: the new file size
:returns: (int) new size of file
:raises: IOError, if file does not exist
"""
self._sftp_connect()
self._sftp.truncate(remotepath, size)
return self._sftp.stat(remotepath).st_size
def walktree(self, remotepath, fcallback, dcallback, ucallback,
recurse=True):
'''recursively descend, depth first, the directory tree rooted at
remotepath, calling discreet callback functions for each regular file,
directory and unknown file type.
:param str remotepath:
root of remote directory to descend, use '.' to start at
:attr:`.pwd`
:param callable fcallback:
callback function to invoke for a regular file.
(form: ``func(str)``)
:param callable dcallback:
callback function to invoke for a directory. (form: ``func(str)``)
:param callable ucallback:
callback function to invoke for an unknown file type.
(form: ``func(str)``)
:param bool recurse: *Default: True* - should it recurse
:returns: None
:raises:
'''
self._sftp_connect()
for entry in self.listdir(remotepath):
pathname = posixpath.join(remotepath, entry)
mode = self._sftp.stat(pathname).st_mode
if S_ISDIR(mode):
# It's a directory, call the dcallback function
dcallback(pathname)
if recurse:
# now, recurse into it
self.walktree(pathname, fcallback, dcallback, ucallback)
elif S_ISREG(mode):
# It's a file, call the fcallback function
fcallback(pathname)
else:
# Unknown file type
ucallback(pathname)
@property
def sftp_client(self):
"""give access to the underlying, connected paramiko SFTPClient object
see http://paramiko-docs.readthedocs.org/en/latest/api/sftp.html
:params: None
:returns: (obj) the active SFTPClient object
"""
self._sftp_connect()
return self._sftp
@property
def active_ciphers(self):
"""Get tuple of currently used local and remote ciphers.
:returns:
(tuple of str) currently used ciphers (local_cipher,
remote_cipher)
"""
return self._transport.local_cipher, self._transport.remote_cipher
@property
def active_compression(self):
"""Get tuple of currently used local and remote compression.
:returns:
(tuple of str) currently used compression (local_compression,
remote_compression)
"""
localc = self._transport.local_compression
remotec = self._transport.remote_compression
return localc, remotec
@property
def security_options(self):
"""return the available security options recognized by paramiko.
:returns:
(obj) security preferences of the ssh transport. These are tuples
of acceptable `.ciphers`, `.digests`, `.key_types`, and key
exchange algorithms `.kex`, listed in order of preference.
"""
return self._transport.get_security_options()
@property
def logfile(self):
'''return the name of the file used for logging or False it not logging
:returns: (str)logfile or (bool) False
'''
return self._logfile
@property
def timeout(self):
''' (float|None) *Default: None* -
get or set the underlying socket timeout for pending read/write
ops.
:returns:
(float|None) seconds to wait for a pending read/write operation
before raising socket.timeout, or None for no timeout
'''
self._sftp_connect()
channel = self._sftp.get_channel()
return channel.gettimeout()
@timeout.setter
def timeout(self, val):
'''setter for timeout'''
self._sftp_connect()
channel = self._sftp.get_channel()
channel.settimeout(val)
def __del__(self):
"""Attempt to clean up if not explicitly closed."""
self.close()
def __enter__(self):
return self
def __exit__(self, etype, value, traceback):
self.close()
def path_advance(thepath, sep=os.sep):
'''generator to iterate over a file path forwards
:param str thepath: the path to navigate forwards
:param str sep: *Default: os.sep* - the path separator to use
:returns: (iter)able of strings
'''
# handle a direct path
pre = ''
if thepath[0] == sep:
pre = sep
curpath = ''
parts = thepath.split(sep)
if pre:
if parts[0]:
parts[0] = pre + parts[0]
else:
parts[1] = pre + parts[1]
for part in parts:
curpath = os.path.join(curpath, part)
if curpath:
yield curpath
def path_retreat(thepath, sep=os.sep):
'''generator to iterate over a file path in reverse
:param str thepath: the path to retreat over
:param str sep: *Default: os.sep* - the path separator to use
:returns: (iter)able of strings
'''
pre = ''
if thepath[0] == sep:
pre = sep
parts = thepath.split(sep)
while parts:
if os.path.join(*parts):
yield '%s%s' % (pre, os.path.join(*parts))
parts = parts[:-1]
def reparent(newparent, oldpath):
'''when copying or moving a directory structure, you need to re-parent the
oldpath. When using os.path.join to calculate this new path, the
appearance of a / root path at the beginning of oldpath, supplants the
newparent and we don't want this to happen, so we need to make the oldpath
root appear as a child of the newparent.
:param: str newparent: the new parent location for oldpath (target)
:param str oldpath: the path being adopted by newparent (source)
:returns: (str) resulting adoptive path
'''
if oldpath[0] in (posixpath.sep, ntpath.sep):
oldpath = '.' + oldpath
return os.path.join(newparent, oldpath)
def walktree(localpath, fcallback, dcallback, ucallback, recurse=True):
'''on the local file system, recursively descend, depth first, the
directory tree rooted at localpath, calling discreet callback functions
for each regular file, directory and unknown file type.
:param str localpath:
root of remote directory to descend, use '.' to start at
:attr:`.pwd`
:param callable fcallback:
callback function to invoke for a regular file.
(form: ``func(str)``)
:param callable dcallback:
callback function to invoke for a directory. (form: ``func(str)``)
:param callable ucallback:
callback function to invoke for an unknown file type.
(form: ``func(str)``)
:param bool recurse: *Default: True* - should it recurse
:returns: None
:raises: OSError, if localpath doesn't exist
'''
for entry in os.listdir(localpath):
pathname = os.path.join(localpath, entry)
mode = os.stat(pathname).st_mode
if S_ISDIR(mode):
# It's a directory, call the dcallback function
dcallback(pathname)
if recurse:
# now, recurse into it
walktree(pathname, fcallback, dcallback, ucallback)
elif S_ISREG(mode):
# It's a file, call the fcallback function
fcallback(pathname)
else:
# Unknown file type
ucallback(pathname)
@contextmanager
def cd(localpath=None):
"""context manager that can change to a optionally specified local
directory and restores the old pwd on exit.
:param str|None localpath: *Default: None* -
local path to temporarily make the current directory
:returns: None
:raises: OSError, if local path doesn't exist
"""
try:
original_path = os.getcwd()
if localpath is not None:
os.chdir(localpath)
yield
finally:
os.chdir(original_path)
| []
| []
| [
"LOGNAME"
]
| [] | ["LOGNAME"] | python | 1 | 0 | |
catalyst/contrib/utils/__init__.py | # flake8: noqa
# isort:skip_file
import logging
import os
logger = logging.getLogger(__name__)
from .argparse import boolean_flag
from .compression import pack, pack_if_needed, unpack, unpack_if_needed
from .confusion_matrix import (
calculate_tp_fp_fn,
calculate_confusion_matrix_from_arrays,
calculate_confusion_matrix_from_tensors,
)
from .dataset import create_dataset, split_dataset_train_test, create_dataframe
from .image import (
has_image_extension,
imread,
imwrite,
imsave,
mask_to_overlay_image,
mimread,
mimwrite_with_meta,
tensor_from_rgb_image,
tensor_to_ndimage,
)
from .misc import (
args_are_not_none,
make_tuple,
pairwise,
)
from .pandas import (
dataframe_to_list,
folds_to_list,
split_dataframe_train_test,
split_dataframe_on_folds,
split_dataframe_on_stratified_folds,
split_dataframe_on_column_folds,
map_dataframe,
separate_tags,
get_dataset_labeling,
split_dataframe,
merge_multiple_fold_csv,
read_multiple_dataframes,
read_csv_data,
balance_classes,
)
from .parallel import parallel_imap, tqdm_parallel_imap, get_pool
from .plotly import plot_tensorboard_log
from .serialization import deserialize, serialize
try:
import transformers # noqa: F401
from .text import tokenize_text, process_bert_output
except ImportError as ex:
if os.environ.get("USE_TRANSFORMERS", "0") == "1":
logger.warning(
"transformers not available, to install transformers,"
" run `pip install transformers`."
)
raise ex
from .visualization import (
plot_confusion_matrix,
render_figure_to_tensor,
plot_metrics,
)
| []
| []
| [
"USE_TRANSFORMERS"
]
| [] | ["USE_TRANSFORMERS"] | python | 1 | 0 | |
catalyst/utils/torch.py | from typing import Dict, Iterable, List, Union
import collections
import os
import re
import numpy as np
import torch
from torch import nn, Tensor
import torch.backends
from torch.backends import cudnn
from catalyst.settings import IS_XLA_AVAILABLE
from catalyst.typing import Device, Model, Optimizer
from catalyst.utils.dict import merge_dicts
def get_optimizable_params(model_or_params):
"""Returns all the parameters that requires gradients."""
params: Iterable[torch.Tensor] = model_or_params
if isinstance(model_or_params, nn.Module):
params = model_or_params.parameters()
master_params = [p for p in params if p.requires_grad]
return master_params
def get_optimizer_momentum(optimizer: Optimizer) -> float:
"""Get momentum of current optimizer.
Args:
optimizer: PyTorch optimizer
Returns:
float: momentum at first param group
"""
betas = optimizer.param_groups[0].get("betas", None)
momentum = optimizer.param_groups[0].get("momentum", None)
return betas[0] if betas is not None else momentum
def set_optimizer_momentum(optimizer: Optimizer, value: float, index: int = 0):
"""Set momentum of ``index`` 'th param group of optimizer to ``value``.
Args:
optimizer: PyTorch optimizer
value: new value of momentum
index (int, optional): integer index of optimizer's param groups,
default is 0
"""
betas = optimizer.param_groups[0].get("betas", None)
momentum = optimizer.param_groups[0].get("momentum", None)
if betas is not None:
_, beta = betas
optimizer.param_groups[index]["betas"] = (value, beta)
elif momentum is not None:
optimizer.param_groups[index]["momentum"] = value
def get_device() -> torch.device:
"""Simple returning the best available device (TPU > GPU > CPU)."""
is_available_gpu = torch.cuda.is_available()
device = "cpu"
if IS_XLA_AVAILABLE:
import torch_xla.core.xla_model as xm
device = xm.xla_device()
elif is_available_gpu:
device = "cuda"
return torch.device(device)
def get_available_gpus():
"""Array of available GPU ids.
Examples:
>>> os.environ["CUDA_VISIBLE_DEVICES"] = "0,2"
>>> get_available_gpus()
[0, 2]
>>> os.environ["CUDA_VISIBLE_DEVICES"] = "0,-1,1"
>>> get_available_gpus()
[0]
>>> os.environ["CUDA_VISIBLE_DEVICES"] = ""
>>> get_available_gpus()
[]
>>> os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
>>> get_available_gpus()
[]
Returns:
iterable: available GPU ids
"""
if "CUDA_VISIBLE_DEVICES" in os.environ:
result = os.environ["CUDA_VISIBLE_DEVICES"].split(",")
result = [id_ for id_ in result if id_ != ""]
# invisible GPUs
# https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#env-vars
if -1 in result:
index = result.index(-1)
result = result[:index]
elif torch.cuda.is_available():
result = list(range(torch.cuda.device_count()))
else:
result = []
return result
def get_activation_fn(activation: str = None):
"""Returns the activation function from ``torch.nn`` by its name."""
if activation is None or activation.lower() == "none":
activation_fn = lambda x: x # noqa: E731
else:
activation_fn = torch.nn.__dict__[activation]()
return activation_fn
def any2device(value, device: Device):
"""
Move tensor, list of tensors, list of list of tensors,
dict of tensors, tuple of tensors to target device.
Args:
value: Object to be moved
device: target device ids
Returns:
Same structure as value, but all tensors and np.arrays moved to device
"""
if isinstance(value, dict):
return {k: any2device(v, device) for k, v in value.items()}
elif isinstance(value, (tuple, list)):
return [any2device(v, device) for v in value]
elif torch.is_tensor(value):
return value.to(device, non_blocking=True)
elif (
isinstance(value, (np.ndarray, np.void))
and value.dtype.fields is not None
):
return {
k: any2device(value[k], device) for k in value.dtype.fields.keys()
}
elif isinstance(value, np.ndarray):
return torch.Tensor(value).to(device)
return value
def prepare_cudnn(deterministic: bool = None, benchmark: bool = None) -> None:
"""
Prepares CuDNN benchmark and sets CuDNN
to be deterministic/non-deterministic mode
Args:
deterministic: deterministic mode if running in CuDNN backend.
benchmark: If ``True`` use CuDNN heuristics to figure out
which algorithm will be most performant
for your model architecture and input.
Setting it to ``False`` may slow down your training.
"""
if torch.cuda.is_available():
# CuDNN reproducibility
# https://pytorch.org/docs/stable/notes/randomness.html#cudnn
if deterministic is None:
deterministic = (
os.environ.get("CUDNN_DETERMINISTIC", "True") == "True"
)
cudnn.deterministic = deterministic
# https://discuss.pytorch.org/t/how-should-i-disable-using-cudnn-in-my-code/38053/4
if benchmark is None:
benchmark = os.environ.get("CUDNN_BENCHMARK", "True") == "True"
cudnn.benchmark = benchmark
def process_model_params(
model: Model,
layerwise_params: Dict[str, dict] = None,
no_bias_weight_decay: bool = True,
lr_scaling: float = 1.0,
) -> List[Union[torch.nn.Parameter, dict]]:
"""Gains model parameters for ``torch.optim.Optimizer``.
Args:
model: Model to process
layerwise_params: Order-sensitive dict where
each key is regex pattern and values are layer-wise options
for layers matching with a pattern
no_bias_weight_decay: If true, removes weight_decay
for all ``bias`` parameters in the model
lr_scaling: layer-wise learning rate scaling,
if 1.0, learning rates will not be scaled
Returns:
iterable: parameters for an optimizer
Example::
>>> model = catalyst.contrib.models.segmentation.ResnetUnet()
>>> layerwise_params = collections.OrderedDict([
>>> ("conv1.*", dict(lr=0.001, weight_decay=0.0003)),
>>> ("conv.*", dict(lr=0.002))
>>> ])
>>> params = process_model_params(model, layerwise_params)
>>> optimizer = torch.optim.Adam(params, lr=0.0003)
"""
params = list(model.named_parameters())
layerwise_params = layerwise_params or collections.OrderedDict()
model_params = []
for name, parameters in params:
options = {}
for pattern, pattern_options in layerwise_params.items():
if re.match(pattern, name) is not None:
# all new LR rules write on top of the old ones
options = merge_dicts(options, pattern_options)
# no bias decay from https://arxiv.org/abs/1812.01187
if no_bias_weight_decay and name.endswith("bias"):
options["weight_decay"] = 0.0
# lr linear scaling from https://arxiv.org/pdf/1706.02677.pdf
if "lr" in options:
options["lr"] *= lr_scaling
model_params.append({"params": parameters, **options})
return model_params
def get_requires_grad(model: Model):
"""Gets the ``requires_grad`` value for all model parameters.
Example::
>>> model = SimpleModel()
>>> requires_grad = get_requires_grad(model)
Args:
model: model
Returns:
requires_grad (Dict[str, bool]): value
"""
requires_grad = {}
for name, param in model.named_parameters():
requires_grad[name] = param.requires_grad
return requires_grad
def set_requires_grad(
model: Model, requires_grad: Union[bool, Dict[str, bool]]
):
"""Sets the ``requires_grad`` value for all model parameters.
Example::
>>> model = SimpleModel()
>>> set_requires_grad(model, requires_grad=True)
>>> # or
>>> model = SimpleModel()
>>> set_requires_grad(model, requires_grad={""})
Args:
model: model
requires_grad (Union[bool, Dict[str, bool]]): value
"""
if isinstance(requires_grad, dict):
for name, param in model.named_parameters():
assert (
name in requires_grad
), f"Parameter `{name}` does not exist in requires_grad"
param.requires_grad = requires_grad[name]
else:
requires_grad = bool(requires_grad)
for param in model.parameters():
param.requires_grad = requires_grad
def get_network_output(net: Model, *input_shapes_args, **input_shapes_kwargs):
"""# noqa: D202
For each input shape returns an output tensor
Examples:
>>> net = nn.Linear(10, 5)
>>> utils.get_network_output(net, (1, 10))
tensor([[[-0.2665, 0.5792, 0.9757, -0.5782, 0.1530]]])
Args:
net: the model
*input_shapes_args: variable length argument list of shapes
**input_shapes_kwargs: key-value arguemnts of shapes
Returns:
tensor with network output
"""
def _rand_sample(
input_shape,
) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
if isinstance(input_shape, dict):
input_t = {
key: torch.Tensor(torch.randn((1,) + key_input_shape))
for key, key_input_shape in input_shape.items()
}
else:
input_t = torch.Tensor(torch.randn((1,) + input_shape))
return input_t
input_args = [
_rand_sample(input_shape) for input_shape in input_shapes_args
]
input_kwargs = {
key: _rand_sample(input_shape)
for key, input_shape in input_shapes_kwargs.items()
}
output_t = net(*input_args, **input_kwargs)
return output_t
def detach(tensor: torch.Tensor) -> np.ndarray:
"""Detach a pytorch tensor from graph and
convert it to numpy array
Args:
tensor: PyTorch tensor
Returns:
numpy ndarray
"""
return tensor.cpu().detach().numpy()
def trim_tensors(tensors):
"""
Trim padding off of a batch of tensors to the smallest possible length.
Should be used with `catalyst.data.DynamicLenBatchSampler`.
Adapted from `Dynamic minibatch trimming to improve BERT training speed`_.
Args:
tensors: list of tensors to trim.
Returns:
List[torch.tensor]: list of trimmed tensors.
.. _`Dynamic minibatch trimming to improve BERT training speed`:
https://www.kaggle.com/c/jigsaw-unintended-bias-in-toxicity-classification/discussion/94779
"""
max_len = torch.max(torch.sum((tensors[0] != 0), 1))
if max_len > 2:
tensors = [tsr[:, :max_len] for tsr in tensors]
return tensors
def normalize(samples: Tensor) -> Tensor:
"""
Args:
samples: tensor with shape of [n_samples, features_dim]
Returns:
normalized tensor with the same shape
"""
norms = torch.norm(samples, p=2, dim=1).unsqueeze(1)
samples = samples / (norms + torch.finfo(torch.float32).eps)
return samples
__all__ = [
"get_optimizable_params",
"get_optimizer_momentum",
"set_optimizer_momentum",
"get_device",
"get_available_gpus",
"get_activation_fn",
"any2device",
"prepare_cudnn",
"process_model_params",
"get_requires_grad",
"set_requires_grad",
"get_network_output",
"detach",
"trim_tensors",
"normalize",
]
| []
| []
| [
"CUDA_VISIBLE_DEVICES",
"CUDNN_BENCHMARK",
"CUDNN_DETERMINISTIC"
]
| [] | ["CUDA_VISIBLE_DEVICES", "CUDNN_BENCHMARK", "CUDNN_DETERMINISTIC"] | python | 3 | 0 | |
enterprise/cmd/frontend/internal/licensing/licensing.go | package licensing
import (
"fmt"
"log"
"os"
"sync"
"github.com/pkg/errors"
"github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend"
"github.com/sourcegraph/sourcegraph/enterprise/pkg/license"
"github.com/sourcegraph/sourcegraph/pkg/conf"
"github.com/sourcegraph/sourcegraph/pkg/env"
"golang.org/x/crypto/ssh"
)
// publicKey is the public key used to verify product license keys.
//
// It is hardcoded here intentionally (we only have one private signing key, and we don't yet
// support/need key rotation). The corresponding private key is at
// https://team-sourcegraph.1password.com/vaults/dnrhbauihkhjs5ag6vszsme45a/allitems/zkdx6gpw4uqejs3flzj7ef5j4i
// and set below in SOURCEGRAPH_LICENSE_GENERATION_KEY.
var publicKey = func() ssh.PublicKey {
// To convert PKCS#8 format (which `openssl rsa -in key.pem -pubout` produces) to the format
// that ssh.ParseAuthorizedKey reads here, use `ssh-keygen -i -mPKCS8 -f key.pub`.
const publicKeyData = `ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDUUd9r83fGmYVLzcqQp5InyAoJB5lLxlM7s41SUUtxfnG6JpmvjNd+WuEptJGk0C/Zpyp/cCjCV4DljDs8Z7xjRbvJYW+vklFFxXrMTBs/+HjpIBKlYTmG8SqTyXyu1s4485Kh1fEC5SK6z2IbFaHuSHUXgDi/IepSOg1QudW4n8J91gPtT2E30/bPCBRq8oz/RVwJSDMvYYjYVb//LhV0Mx3O6hg4xzUNuwiCtNjCJ9t4YU2sV87+eJwWtQNbSQ8TelQa8WjG++XSnXUHw12bPDe7wGL/7/EJb7knggKSAMnpYpCyV35dyi4DsVc46c+b6P0gbVSosh3Uc3BJHSWF`
var err error
publicKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKeyData))
if err != nil {
panic("failed to parse public key for license verification: " + err.Error())
}
return publicKey
}()
// ParseProductLicenseKey parses and verifies the license key using the license verification public
// key (publicKey in this package).
func ParseProductLicenseKey(licenseKey string) (*license.Info, string, error) {
return license.ParseSignedKey(licenseKey, publicKey)
}
// ParseProductLicenseKeyWithBuiltinOrGenerationKey is like ParseProductLicenseKey, except it tries
// parsing and verifying the license key with the license generation key (if set), instead of always
// using the builtin license key.
//
// It is useful for local development when using a test license generation key (whose signatures
// aren't considered valid when verified using the builtin public key).
func ParseProductLicenseKeyWithBuiltinOrGenerationKey(licenseKey string) (*license.Info, string, error) {
var k ssh.PublicKey
if licenseGenerationPrivateKey != nil {
k = licenseGenerationPrivateKey.PublicKey()
} else {
k = publicKey
}
return license.ParseSignedKey(licenseKey, k)
}
// Cache the parsing of the license key because public key crypto can be slow.
var (
mu sync.Mutex
lastKeyText string
lastInfo *license.Info
lastSignature string
)
var MockGetConfiguredProductLicenseInfo func() (*license.Info, string, error)
// GetConfiguredProductLicenseInfo returns information about the current product license key
// specified in site configuration.
func GetConfiguredProductLicenseInfo() (*license.Info, error) {
info, _, err := GetConfiguredProductLicenseInfoWithSignature()
return info, err
}
// GetConfiguredProductLicenseInfoWithSignature returns information about the current product license key
// specified in site configuration, with the signed key's signature.
func GetConfiguredProductLicenseInfoWithSignature() (*license.Info, string, error) {
if MockGetConfiguredProductLicenseInfo != nil {
return MockGetConfiguredProductLicenseInfo()
}
// Support reading the license key from the environment (intended for development, because we
// don't want to commit a valid license key to dev/config.json in the OSS repo).
keyText := os.Getenv("SOURCEGRAPH_LICENSE_KEY")
if keyText == "" {
keyText = conf.Get().Critical.LicenseKey
}
if keyText != "" {
mu.Lock()
defer mu.Unlock()
var (
info *license.Info
signature string
)
if keyText == lastKeyText {
info = lastInfo
signature = lastSignature
} else {
var err error
info, signature, err = ParseProductLicenseKey(keyText)
if err != nil {
return nil, "", err
}
lastKeyText = keyText
lastInfo = info
lastSignature = signature
}
return info, signature, nil
}
// No license key.
return nil, "", nil
}
// Make the Site.productSubscription GraphQL field return the actual info about the product license,
// if any.
func init() {
graphqlbackend.GetConfiguredProductLicenseInfo = func() (*graphqlbackend.ProductLicenseInfo, error) {
info, err := GetConfiguredProductLicenseInfo()
if info == nil || err != nil {
return nil, err
}
return &graphqlbackend.ProductLicenseInfo{
TagsValue: info.Tags,
UserCountValue: info.UserCount,
ExpiresAtValue: info.ExpiresAt,
}, nil
}
}
// licenseGenerationPrivateKeyURL is the URL where Sourcegraph staff can find the private key for
// generating licenses.
//
// NOTE: If you change this, use text search to replace other instances of it (in source code
// comments).
const licenseGenerationPrivateKeyURL = "https://team-sourcegraph.1password.com/vaults/dnrhbauihkhjs5ag6vszsme45a/allitems/zkdx6gpw4uqejs3flzj7ef5j4i"
// envLicenseGenerationPrivateKey (the env var SOURCEGRAPH_LICENSE_GENERATION_KEY) is the
// PEM-encoded form of the private key used to sign product license keys. It is stored at
// https://team-sourcegraph.1password.com/vaults/dnrhbauihkhjs5ag6vszsme45a/allitems/zkdx6gpw4uqejs3flzj7ef5j4i.
var envLicenseGenerationPrivateKey = env.Get("SOURCEGRAPH_LICENSE_GENERATION_KEY", "", "the PEM-encoded form of the private key used to sign product license keys ("+licenseGenerationPrivateKeyURL+")")
// licenseGenerationPrivateKey is the private key used to generate license keys.
var licenseGenerationPrivateKey = func() ssh.Signer {
if envLicenseGenerationPrivateKey == "" {
// Most Sourcegraph instances don't use/need this key. Generally only Sourcegraph.com and
// local dev will have this key set.
return nil
}
privateKey, err := ssh.ParsePrivateKey([]byte(envLicenseGenerationPrivateKey))
if err != nil {
log.Fatalf("Failed to parse private key in SOURCEGRAPH_LICENSE_GENERATION_KEY env var: %s.", err)
}
return privateKey
}()
// GenerateProductLicenseKey generates a product license key using the license generation private
// key configured in site configuration.
func GenerateProductLicenseKey(info license.Info) (string, error) {
if envLicenseGenerationPrivateKey == "" {
const msg = "no product license generation private key was configured"
if env.InsecureDev {
// Show more helpful error message in local dev.
return "", fmt.Errorf("%s (for testing by Sourcegraph staff: set the SOURCEGRAPH_LICENSE_GENERATION_KEY env var to the key obtained at %s)", msg, licenseGenerationPrivateKeyURL)
}
return "", errors.New(msg)
}
licenseKey, err := license.GenerateSignedKey(info, licenseGenerationPrivateKey)
if err != nil {
return "", err
}
return licenseKey, nil
}
| [
"\"SOURCEGRAPH_LICENSE_KEY\""
]
| []
| [
"SOURCEGRAPH_LICENSE_KEY"
]
| [] | ["SOURCEGRAPH_LICENSE_KEY"] | go | 1 | 0 | |
cat/__main__.py | import argparse
import logging
import warnings
import pkg_resources
from .cat import run
warnings.simplefilter(action="ignore", category=FutureWarning)
warnings.simplefilter(action="ignore", category=DeprecationWarning)
warnings.simplefilter(action="ignore", category=RuntimeWarning)
def init_logger(verbose: bool):
logger = logging.getLogger(__name__)
logger_format = (
"[%(filename)s->%(funcName)s():%(lineno)s]%(levelname)s: %(message)s"
)
logging.basicConfig(format=logger_format, level=logging.INFO)
logger.setLevel(logging.DEBUG if verbose else logging.INFO)
def main():
parser = argparse.ArgumentParser(description=f"Cluster Alignment Tool (CAT)")
parser.add_argument(
"--ds1",
action="store",
type=str,
help="Processed dataset (h5/h5ad)",
)
parser.add_argument(
"--ds1_name",
type=str,
help="Dataset name",
)
parser.add_argument(
"--ds1_cluster",
type=str,
help="Column name for comparison",
)
parser.add_argument(
"--ds1_genes",
type=str,
default=None,
help="Gene column, using `index` as default",
)
parser.add_argument(
"--ds2",
action="store",
type=str,
help="Processed dataset (h5/h5ad)",
)
parser.add_argument(
"--ds2_name",
type=str,
help="Dataset name",
)
parser.add_argument(
"--ds2_cluster",
type=str,
help="Column name for comparison",
)
parser.add_argument(
"--ds2_genes",
type=str,
default=None,
help="Gene column, using `index` as default",
)
parser.add_argument(
"--features",
type=str,
default=None,
help="File containing list of genes on new lines",
)
parser.add_argument(
"--output",
type=str,
default="./results",
help="Output location",
)
parser.add_argument(
"--distance", type=str, default="euclidean", help="Distance measurement"
)
parser.add_argument(
"--sigma", type=float, default=1.6, help="Sigma cutoff (1.6 => p-value: 0.05)"
)
parser.add_argument(
"--n_iter", type=int, default=1_000, help="Number of bootstraps, default 1,000"
)
parser.add_argument(
"--format",
type=str,
default="excel",
choices=["excel", "html"],
help="Report output format",
)
parser.add_argument(
"--verbose",
action="store_true",
help="Verbose mode",
)
parser.add_argument(
"--version",
action="version",
version=f"CAT v{pkg_resources.require('cat-python')[0].version}",
)
args = parser.parse_args()
init_logger(args.verbose)
run(args)
if __name__ == "__main__":
main()
| []
| []
| []
| [] | [] | python | null | null | null |
Gems/Blast/Editor/Scripts/asset_builder_blast.py | """
Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
def install_user_site():
import os
import sys
import azlmbr.paths
executableBinFolder = azlmbr.paths.executableFolder
# the PyAssImp module checks the Windows PATH for the assimp DLL file
if os.name == "nt":
os.environ['PATH'] = os.environ['PATH'] + os.pathsep + executableBinFolder
# PyAssImp module needs to find the shared library for assimp to load; "posix" handles Mac and Linux
if os.name == "posix":
if 'LD_LIBRARY_PATH' in os.environ:
os.environ['LD_LIBRARY_PATH'] = os.environ['LD_LIBRARY_PATH'] + os.pathsep + executableBinFolder
else:
os.environ['LD_LIBRARY_PATH'] = executableBinFolder
# add the user site packages folder to find the pyassimp egg link
import site
for item in sys.path:
if (item.find('site-packages') != -1):
site.addsitedir(item)
install_user_site()
import pyassimp
import azlmbr.asset
import azlmbr.asset.builder
import azlmbr.asset.entity
import azlmbr.blast
import azlmbr.bus as bus
import azlmbr.editor as editor
import azlmbr.entity
import azlmbr.math
import os
import traceback
import binascii
import sys
# the UUID must be unique amongst all the asset builders in Python or otherwise
# a collision of builders will happen preventing one from running
busIdString = '{CF5C74D1-9ED4-4851-85B1-9B15090DBEC7}'
busId = azlmbr.math.Uuid_CreateString(busIdString, 0)
handler = None
jobKeyName = 'Blast Chunk Assets'
sceneManifestType = azlmbr.math.Uuid_CreateString('{9274AD17-3212-4651-9F3B-7DCCB080E467}', 0)
dccMaterialType = azlmbr.math.Uuid_CreateString('{C88469CF-21E7-41EB-96FD-BF14FBB05EDC}', 0)
def log_exception_traceback():
exc_type, exc_value, exc_tb = sys.exc_info()
data = traceback.format_exception(exc_type, exc_value, exc_tb)
print(str(data))
def get_source_fbx_filename(request):
fullPath = os.path.join(request.watchFolder, request.sourceFile)
basePath, filePart = os.path.split(fullPath)
filename = os.path.splitext(filePart)[0] + '.fbx'
filename = os.path.join(basePath, filename)
return filename
def raise_error(message):
raise RuntimeError(f'[ERROR]: {message}')
def generate_asset_info(chunkNames, request):
import azlmbr.blast
# write out an object stream with the extension of .fbx.assetinfo.generated
basePath, sceneFile = os.path.split(request.sourceFile)
assetinfoFilename = os.path.splitext(sceneFile)[0] + '.fbx.assetinfo.generated'
assetinfoFilename = os.path.join(basePath, assetinfoFilename)
assetinfoFilename = assetinfoFilename.replace('\\', '/').lower()
outputFilename = os.path.join(request.tempDirPath, assetinfoFilename)
storage = azlmbr.blast.BlastSliceAssetStorageComponent()
if (storage.GenerateAssetInfo(chunkNames, request.sourceFile, outputFilename)):
product = azlmbr.asset.builder.JobProduct(assetinfoFilename, sceneManifestType, 1)
product.dependenciesHandled = True
return product
raise_error('Failed to generate assetinfo.generated')
def export_fbx_manifest(request):
output = []
fbxFilename = get_source_fbx_filename(request)
sceneAsset = pyassimp.load(fbxFilename)
with sceneAsset as scene:
rootNode = scene.mRootNode.contents
for index in range(0, rootNode.mNumChildren):
child = rootNode.mChildren[index]
childNode = child.contents
childNodeName = bytes.decode(childNode.mName.data)
output.append(str(childNodeName))
return output
def convert_to_asset_paths(fbxFilename, gameRoot, chunkNameList):
realtivePath = fbxFilename[len(gameRoot) + 1:]
realtivePath = os.path.splitext(realtivePath)[0]
output = []
for chunk in chunkNameList:
assetPath = realtivePath + '-' + chunk + '.cgf'
assetPath = assetPath.replace('\\', '/')
assetPath = assetPath.lower()
output.append(assetPath)
return output
# creates a single job to compile for each platform
def create_jobs(request):
fbxSidecarFilename = get_source_fbx_filename(request)
if (os.path.exists(fbxSidecarFilename) is False):
print('[WARN] Sidecar FBX file {} is missing for blast file {}'.format(fbxSidecarFilename, request.sourceFile))
return azlmbr.asset.builder.CreateJobsResponse()
# see if the FBX file already has a .assetinfo source asset, if so then do not create a job
if (os.path.exists(f'{fbxSidecarFilename}.assetinfo')):
response = azlmbr.asset.builder.CreateJobsResponse()
response.result = azlmbr.asset.builder.CreateJobsResponse_ResultSuccess
return response
# create job descriptor for each platform
jobDescriptorList = []
for platformInfo in request.enabledPlatforms:
jobDesc = azlmbr.asset.builder.JobDescriptor()
jobDesc.jobKey = jobKeyName
jobDesc.priority = 12 # higher than the 'Scene compilation' or 'fbx'
jobDesc.set_platform_identifier(platformInfo.identifier)
jobDescriptorList.append(jobDesc)
response = azlmbr.asset.builder.CreateJobsResponse()
response.result = azlmbr.asset.builder.CreateJobsResponse_ResultSuccess
response.createJobOutputs = jobDescriptorList
return response
# handler to create jobs for a source asset
def on_create_jobs(args):
try:
request = args[0]
return create_jobs(request)
except:
log_exception_traceback()
return azlmbr.asset.builder.CreateJobsResponse()
def generate_blast_slice_asset(chunkNameList, request):
# get list of relative chunk paths
fbxFilename = get_source_fbx_filename(request)
assetPaths = convert_to_asset_paths(fbxFilename, request.watchFolder, chunkNameList)
outcome = azlmbr.asset.entity.PythonBuilderRequestBus(bus.Broadcast, 'CreateEditorEntity', 'BlastData')
if (outcome.IsSuccess() is False):
raise_error('could not create an editor entity')
blastDataEntityId = outcome.GetValue()
# create a component for the editor entity
gameType = azlmbr.entity.EntityType().Game
blastMeshDataTypeIdList = editor.EditorComponentAPIBus(bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["Blast Slice Storage Component"], gameType)
componentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentOfType', blastDataEntityId, blastMeshDataTypeIdList[0])
if (componentOutcome.IsSuccess() is False):
raise_error('failed to add component (Blast Slice Storage Component) to the blast_slice')
# build the blast slice using the chunk asset paths
blastMeshComponentId = componentOutcome.GetValue()[0]
outcome = editor.EditorComponentAPIBus(bus.Broadcast, 'BuildComponentPropertyTreeEditor', blastMeshComponentId)
if(outcome.IsSuccess() is False):
raise_error(f'failed to create Property Tree Editor for component ({blastMeshComponentId})')
pte = outcome.GetValue()
pte.set_visible_enforcement(True)
pte.set_value('Mesh Paths', assetPaths)
# write out an object stream with the extension of .blast_slice
basePath, sceneFile = os.path.split(request.sourceFile)
blastFilename = os.path.splitext(sceneFile)[0] + '.blast_slice'
blastFilename = os.path.join(basePath, blastFilename)
blastFilename = blastFilename.replace('\\', '/').lower()
tempFilename = os.path.join(request.tempDirPath, blastFilename)
entityList = [blastDataEntityId]
makeDynamic = False
outcome = azlmbr.asset.entity.PythonBuilderRequestBus(bus.Broadcast, 'WriteSliceFile', tempFilename, entityList, makeDynamic)
if (outcome.IsSuccess() is False):
raise_error(f'WriteSliceFile failed for blast_slice file ({blastFilename})')
# return a job product
blastSliceAsset = azlmbr.blast.BlastSliceAsset()
subId = binascii.crc32(blastFilename.encode('utf8'))
product = azlmbr.asset.builder.JobProduct(blastFilename, blastSliceAsset.GetAssetTypeId(), subId)
product.dependenciesHandled = True
return product
def read_in_string(data, dataLength):
stringData = ''
for idx in range(4, dataLength - 1):
char = bytes.decode(data[idx])
if (str.isascii(char)):
stringData += char
return stringData
def import_material_info(fbxFilename):
_, group_name = os.path.split(fbxFilename)
group_name = os.path.splitext(group_name)[0]
output = {}
output['group_name'] = group_name
output['material_name_list'] = []
sceneAsset = pyassimp.load(fbxFilename)
with sceneAsset as scene:
for materialIndex in range(0, scene.mNumMaterials):
material = scene.mMaterials[materialIndex].contents
for materialPropertyIdx in range(0, material.mNumProperties):
materialProperty = material.mProperties[materialPropertyIdx].contents
materialPropertyName = bytes.decode(materialProperty.mKey.data)
if (materialPropertyName.endswith('mat.name') and materialProperty.mType is 3):
stringData = read_in_string(materialProperty.mData, materialProperty.mDataLength)
output['material_name_list'].append(stringData)
return output
def write_material_file(sourceFile, destFolder):
# preserve source MTL files
rootPath, materialSourceFile = os.path.split(sourceFile)
materialSourceFile = os.path.splitext(materialSourceFile)[0] + '.mtl'
materialSourceFile = os.path.join(rootPath, materialSourceFile)
if (os.path.exists(materialSourceFile)):
print(f'{materialSourceFile} source already exists')
return None
# auto-generate a DCC material file
info = import_material_info(sourceFile)
materialGroupName = info['group_name']
materialNames = info['material_name_list']
materialFilename = materialGroupName + '.dccmtl.generated'
subId = binascii.crc32(materialFilename.encode('utf8'))
materialFilename = os.path.join(destFolder, materialFilename)
storage = azlmbr.blast.BlastSliceAssetStorageComponent()
storage.WriteMaterialFile(materialGroupName, materialNames, materialFilename)
product = azlmbr.asset.builder.JobProduct(materialFilename, dccMaterialType, subId)
product.dependenciesHandled = True
return product
def process_fbx_file(request):
# fill out response object
response = azlmbr.asset.builder.ProcessJobResponse()
productOutputs = []
# write out DCCMTL file as a product (if needed)
materialProduct = write_material_file(get_source_fbx_filename(request), request.tempDirPath)
if (materialProduct is not None):
productOutputs.append(materialProduct)
# prepare output folder
basePath, _ = os.path.split(request.sourceFile)
outputPath = os.path.join(request.tempDirPath, basePath)
os.makedirs(outputPath)
# parse FBX for chunk names
chunkNameList = export_fbx_manifest(request)
# create assetinfo generated (is product)
productOutputs.append(generate_asset_info(chunkNameList, request))
# write out the blast_slice object stream
productOutputs.append(generate_blast_slice_asset(chunkNameList, request))
response.outputProducts = productOutputs
response.resultCode = azlmbr.asset.builder.ProcessJobResponse_Success
response.dependenciesHandled = True
return response
# using the incoming 'request' find the type of job via 'jobKey' to determine what to do
def on_process_job(args):
try:
request = args[0]
if (request.jobDescription.jobKey.startswith(jobKeyName)):
return process_fbx_file(request)
return azlmbr.asset.builder.ProcessJobResponse()
except:
log_exception_traceback()
return azlmbr.asset.builder.ProcessJobResponse()
# register asset builder
def register_asset_builder():
assetPattern = azlmbr.asset.builder.AssetBuilderPattern()
assetPattern.pattern = '*.blast'
assetPattern.type = azlmbr.asset.builder.AssetBuilderPattern_Wildcard
builderDescriptor = azlmbr.asset.builder.AssetBuilderDesc()
builderDescriptor.name = "Blast Gem"
builderDescriptor.patterns = [assetPattern]
builderDescriptor.busId = busId
builderDescriptor.version = 5
outcome = azlmbr.asset.builder.PythonAssetBuilderRequestBus(azlmbr.bus.Broadcast, 'RegisterAssetBuilder', builderDescriptor)
if outcome.IsSuccess():
# created the asset builder to hook into the notification bus
handler = azlmbr.asset.builder.PythonBuilderNotificationBusHandler()
handler.connect(busId)
handler.add_callback('OnCreateJobsRequest', on_create_jobs)
handler.add_callback('OnProcessJobRequest', on_process_job)
return handler
# create the asset builder handler
try:
handler = register_asset_builder()
except:
handler = None
log_exception_traceback()
| []
| []
| [
"LD_LIBRARY_PATH",
"PATH"
]
| [] | ["LD_LIBRARY_PATH", "PATH"] | python | 2 | 0 | |
tools/test.py | import os
import torch
from tensorboardX import SummaryWriter
import time
import glob
import re
import datetime
import argparse
from pathlib import Path
import torch.distributed as dist
from pcdet.datasets import build_dataloader
from pcdet.models import build_network
from pcdet.utils import common_utils
from pcdet.config import cfg, cfg_from_list, cfg_from_yaml_file, log_config_to_file
from eval_utils import eval_utils
def parse_config():
parser = argparse.ArgumentParser(description='arg parser')
parser.add_argument('--cfg_file', type=str, default=None, help='specify the config for training')
parser.add_argument('--batch_size', type=int, default=16, required=False, help='batch size for training')
parser.add_argument('--epochs', type=int, default=80, required=False, help='Number of epochs to train for')
parser.add_argument('--workers', type=int, default=4, help='number of workers for dataloader')
parser.add_argument('--extra_tag', type=str, default='default', help='extra tag for this experiment')
parser.add_argument('--ckpt', type=str, default=None, help='checkpoint to start from')
parser.add_argument('--mgpus', action='store_true', default=False, help='whether to use multiple gpu')
parser.add_argument('--launcher', choices=['none', 'pytorch', 'slurm'], default='none')
parser.add_argument('--tcp_port', type=int, default=18888, help='tcp port for distrbuted training')
parser.add_argument('--local_rank', type=int, default=0, help='local rank for distributed training')
parser.add_argument('--set', dest='set_cfgs', default=None, nargs=argparse.REMAINDER,
help='set extra config keys if needed')
parser.add_argument('--max_waiting_mins', type=int, default=30, help='max waiting minutes')
parser.add_argument('--start_epoch', type=int, default=0, help='')
parser.add_argument('--eval_tag', type=str, default='default', help='eval tag for this experiment')
parser.add_argument('--eval_all', action='store_true', default=False, help='whether to evaluate all checkpoints')
parser.add_argument('--ckpt_dir', type=str, default=None, help='specify a ckpt directory to be evaluated if needed')
parser.add_argument('--save_to_file', action='store_true', default=False, help='')
args = parser.parse_args()
cfg_from_yaml_file(args.cfg_file, cfg)
cfg.TAG = Path(args.cfg_file).stem
cfg.EXP_GROUP_PATH = '/'.join(args.cfg_file.split('/')[1:-1]) # remove 'cfgs' and 'xxxx.yaml'
if args.set_cfgs is not None:
cfg_from_list(args.set_cfgs, cfg)
return args, cfg
def eval_single_ckpt(model, test_loader, args, eval_output_dir, logger, epoch_id, dist_test=False):
# load checkpoint
model.load_params_from_file(filename=args.ckpt, logger=logger, to_cpu=dist_test)
model.cuda()
# start evaluation
eval_utils.eval_one_epoch(
cfg, model, test_loader, epoch_id, logger, dist_test=dist_test,
result_dir=eval_output_dir, save_to_file=args.save_to_file
)
def get_no_evaluated_ckpt(ckpt_dir, ckpt_record_file, args):
ckpt_list = glob.glob(os.path.join(ckpt_dir, '*checkpoint_epoch_*.pth'))
ckpt_list.sort(key=os.path.getmtime)
evaluated_ckpt_list = [float(x.strip()) for x in open(ckpt_record_file, 'r').readlines()]
for cur_ckpt in ckpt_list:
num_list = re.findall('checkpoint_epoch_(.*).pth', cur_ckpt)
if num_list.__len__() == 0:
continue
epoch_id = num_list[-1]
if 'optim' in epoch_id:
continue
if float(epoch_id) not in evaluated_ckpt_list and int(float(epoch_id)) >= args.start_epoch:
return epoch_id, cur_ckpt
return -1, None
def repeat_eval_ckpt(model, test_loader, args, eval_output_dir, logger, ckpt_dir, dist_test=False):
# evaluated ckpt record
ckpt_record_file = eval_output_dir / ('eval_list_%s.txt' % cfg.DATA_CONFIG.DATA_SPLIT['test'])
with open(ckpt_record_file, 'a'):
pass
# tensorboard log
if cfg.LOCAL_RANK == 0:
tb_log = SummaryWriter(log_dir=str(eval_output_dir / ('tensorboard_%s' % cfg.DATA_CONFIG.DATA_SPLIT['test'])))
total_time = 0
first_eval = True
while True:
# check whether there is checkpoint which is not evaluated
cur_epoch_id, cur_ckpt = get_no_evaluated_ckpt(ckpt_dir, ckpt_record_file, args)
if cur_epoch_id == -1 or int(float(cur_epoch_id)) < args.start_epoch:
wait_second = 30
if cfg.LOCAL_RANK == 0:
print('Wait %s seconds for next check (progress: %.1f / %d minutes): %s \r'
% (wait_second, total_time * 1.0 / 60, args.max_waiting_mins, ckpt_dir), end='', flush=True)
time.sleep(wait_second)
total_time += 30
if total_time > args.max_waiting_mins * 60 and (first_eval is False):
break
continue
total_time = 0
first_eval = False
model.load_params_from_file(filename=cur_ckpt, logger=logger, to_cpu=dist_test)
model.cuda()
# start evaluation
cur_result_dir = eval_output_dir / ('epoch_%s' % cur_epoch_id) / cfg.DATA_CONFIG.DATA_SPLIT['test']
tb_dict = eval_utils.eval_one_epoch(
cfg, model, test_loader, cur_epoch_id, logger, dist_test=dist_test,
result_dir=cur_result_dir, save_to_file=args.save_to_file
)
if cfg.LOCAL_RANK == 0:
for key, val in tb_dict.items():
tb_log.add_scalar(key, val, cur_epoch_id)
# record this epoch which has been evaluated
with open(ckpt_record_file, 'a') as f:
print('%s' % cur_epoch_id, file=f)
logger.info('Epoch %s has been evaluated' % cur_epoch_id)
def main():
args, cfg = parse_config()
if args.launcher == 'none':
dist_test = False
else:
args.batch_size, cfg.LOCAL_RANK = getattr(common_utils, 'init_dist_%s' % args.launcher)(
args.batch_size, args.tcp_port, args.local_rank, backend='nccl'
)
dist_test = True
output_dir = cfg.ROOT_DIR / 'output' / cfg.EXP_GROUP_PATH / cfg.TAG / args.extra_tag
output_dir.mkdir(parents=True, exist_ok=True)
eval_output_dir = output_dir / 'eval'
if not args.eval_all:
num_list = re.findall(r'\d+', args.ckpt) if args.ckpt is not None else []
epoch_id = num_list[-1] if num_list.__len__() > 0 else 'no_number'
eval_output_dir = eval_output_dir / ('epoch_%s' % epoch_id) / cfg.DATA_CONFIG.DATA_SPLIT['test']
else:
eval_output_dir = eval_output_dir / 'eval_all_default'
if args.eval_tag is not None:
eval_output_dir = eval_output_dir / args.eval_tag
eval_output_dir.mkdir(parents=True, exist_ok=True)
log_file = eval_output_dir / ('log_eval_%s.txt' % datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
logger = common_utils.create_logger(log_file, rank=cfg.LOCAL_RANK)
# log to file
logger.info('**********************Start logging**********************')
gpu_list = os.environ['CUDA_VISIBLE_DEVICES'] if 'CUDA_VISIBLE_DEVICES' in os.environ.keys() else 'ALL'
logger.info('CUDA_VISIBLE_DEVICES=%s' % gpu_list)
if dist_test:
total_gpus = dist.get_world_size()
logger.info('total_batch_size: %d' % (total_gpus * args.batch_size))
for key, val in vars(args).items():
logger.info('{:16} {}'.format(key, val))
log_config_to_file(cfg, logger=logger)
ckpt_dir = args.ckpt_dir if args.ckpt_dir is not None else output_dir / 'ckpt'
test_set, test_loader, sampler = build_dataloader(
dataset_cfg=cfg.DATA_CONFIG,
class_names=cfg.CLASS_NAMES,
batch_size=args.batch_size,
dist=dist_test, workers=args.workers, logger=logger, training=False
)
model = build_network(model_cfg=cfg.MODEL, num_class=len(cfg.CLASS_NAMES), dataset=test_set)
with torch.no_grad():
if args.eval_all:
repeat_eval_ckpt(model, test_loader, args, eval_output_dir, logger, ckpt_dir, dist_test=dist_test)
else:
eval_single_ckpt(model, test_loader, args, eval_output_dir, logger, epoch_id, dist_test=dist_test)
if __name__ == '__main__':
main()
| []
| []
| [
"CUDA_VISIBLE_DEVICES"
]
| [] | ["CUDA_VISIBLE_DEVICES"] | python | 1 | 0 | |
make_tweet.py | from congress import Congress
from today_success import practice_todayData
import re
import tweepy
import os
# Heroku Variables. You define these in Heroku's dashboard.
the_consumer_key = os.environ.get('the_consumer_key')
the_consumer_secret = os.environ.get('the_consumer_secret')
the_access_key = os.environ.get('the_access_key')
the_access_secret = os.environ.get('the_access_secret')
congress_key = os.environ.get('congress_key')
# Access keys from Twitter and ProPublica's API
consumer_key = the_consumer_key
consumer_secret = the_consumer_secret
access_key = the_access_key
access_secret = the_access_secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
congress = Congress(congress_key)
api = tweepy.API(auth)
# Returns votes that happend on the day that the function is called.
todays_votes = congress.votes.today('house')
# This function accepts 3 arguments: The chamber, either 'house' or 'senate'; roll_call_num, which is the roll call number for each vote, and a session.
def get_info(chamber, roll_call_num, sess):
today_yoho_vote = congress.votes.get(chamber, roll_call_num, sess)['votes']['vote']['positions'][426]['vote_position']
shortTitle = congress.votes.get(chamber, roll_call_num, sess)['votes']['vote']['bill']['short_title']
billNum = congress.votes.get(chamber, roll_call_num, sess)['votes']['vote']['bill']['number']
bill_desc = congress.votes.get(chamber, roll_call_num, sess)['votes']['vote']['description']
which_congress = str(congress.votes.get(chamber, roll_call_num, sess)['votes']['vote']['congress'])
iso_bill = congress.votes.get(chamber, roll_call_num, sess)['votes']['vote']['bill']['bill_id']
cleaned_bill = re.sub("[^0-9\-.]", '', iso_bill)
congress_dot_gov = 'https://www.congress.gov/bill/' + which_congress + 'th-congress/house-bill/' + cleaned_bill
api.update_status('Ted Yoho voted ' + today_yoho_vote + ' on "' + bill_desc + '," in '+ billNum + ' "' + shortTitle + '." ' + congress_dot_gov)
# This function goes through every vote that took place in the argument that is passed through in the form of d. It keeps going until there is no more (that's where except IndexError comes in). It gets the roll call number, session and chamber in each vote and then passes it into the get_info function.
def practice_today_roll(d):
z = 0
for i in d:
try:
rollCall = d['votes'][z]['roll_call']
sess = d['votes'][z]['session']
chamber = d['chamber']
get_info(chamber, rollCall, sess)
z += 1
pass
except IndexError:
break
practice_today_roll(todays_votes) | []
| []
| [
"the_access_secret",
"the_consumer_key",
"the_access_key",
"the_consumer_secret",
"congress_key"
]
| [] | ["the_access_secret", "the_consumer_key", "the_access_key", "the_consumer_secret", "congress_key"] | python | 5 | 0 | |
tests/test_impersonation.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import errno
import functools
import logging
import os
import subprocess
import sys
import unittest
from tests.compat import mock
from copy import deepcopy
from airflow import jobs, models
from airflow.utils.db import add_default_pool_if_not_exists
from airflow.utils.state import State
from airflow.utils.timezone import datetime
DEV_NULL = '/dev/null'
TEST_DAG_FOLDER = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'dags')
TEST_DAG_CORRUPTED_FOLDER = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'dags_corrupted')
TEST_UTILS_FOLDER = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'test_utils')
DEFAULT_DATE = datetime(2015, 1, 1)
TEST_USER = 'airflow_test_user'
logger = logging.getLogger(__name__)
def mock_custom_module_path(path):
"""
This decorator adds a path to sys.path to simulate running the current script with the ``PYTHONPATH``
environment variable set and sets the environment variable ``PYTHONPATH`` to change the
module load directory for child scripts.
"""
def wrapper(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
copy_sys_path = deepcopy(sys.path)
sys.path.append(path)
try:
with mock.patch.dict('os.environ', {'PYTHONPATH': path}):
return func(*args, **kwargs)
finally:
sys.path = copy_sys_path
return decorator
return wrapper
def grant_permissions():
airflow_home = os.environ['AIRFLOW_HOME']
subprocess.check_call(
'find "%s" -exec sudo chmod og+w {} +; sudo chmod og+rx /root' % airflow_home, shell=True)
def revoke_permissions():
airflow_home = os.environ['AIRFLOW_HOME']
subprocess.check_call(
'find "%s" -exec sudo chmod og-w {} +; sudo chmod og-rx /root' % airflow_home, shell=True)
def check_original_docker_image():
if not os.path.isfile('/.dockerenv') or os.environ.get('PYTHON_BASE_IMAGE') is None:
raise unittest.SkipTest("""Adding/removing a user as part of a test is very bad for host os
(especially if the user already existed to begin with on the OS), therefore we check if we run inside a
the official docker container and only allow to run the test there. This is done by checking /.dockerenv
file (always present inside container) and checking for PYTHON_BASE_IMAGE variable.
""")
def create_user():
try:
subprocess.check_output(['sudo', 'useradd', '-m', TEST_USER, '-g',
str(os.getegid())])
except OSError as e:
if e.errno == errno.ENOENT:
raise unittest.SkipTest(
"The 'useradd' command did not exist so unable to test "
"impersonation; Skipping Test. These tests can only be run on a "
"linux host that supports 'useradd'."
)
else:
raise unittest.SkipTest(
"The 'useradd' command exited non-zero; Skipping tests. Does the "
"current user have permission to run 'useradd' without a password "
"prompt (check sudoers file)?"
)
class TestImpersonation(unittest.TestCase):
def setUp(self):
check_original_docker_image()
grant_permissions()
add_default_pool_if_not_exists()
self.dagbag = models.DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
logger.info('Loaded DAGS:')
logger.info(self.dagbag.dagbag_report())
create_user()
def tearDown(self):
subprocess.check_output(['sudo', 'userdel', '-r', TEST_USER])
revoke_permissions()
def run_backfill(self, dag_id, task_id):
dag = self.dagbag.get_dag(dag_id)
dag.clear()
jobs.BackfillJob(
dag=dag,
start_date=DEFAULT_DATE,
end_date=DEFAULT_DATE).run()
ti = models.TaskInstance(
task=dag.get_task(task_id),
execution_date=DEFAULT_DATE)
ti.refresh_from_db()
self.assertEqual(ti.state, State.SUCCESS)
def test_impersonation(self):
"""
Tests that impersonating a unix user works
"""
self.run_backfill(
'test_impersonation',
'test_impersonated_user'
)
def test_no_impersonation(self):
"""
If default_impersonation=None, tests that the job is run
as the current user (which will be a sudoer)
"""
self.run_backfill(
'test_no_impersonation',
'test_superuser',
)
def test_default_impersonation(self):
"""
If default_impersonation=TEST_USER, tests that the job defaults
to running as TEST_USER for a test without run_as_user set
"""
os.environ['AIRFLOW__CORE__DEFAULT_IMPERSONATION'] = TEST_USER
try:
self.run_backfill(
'test_default_impersonation',
'test_deelevated_user'
)
finally:
del os.environ['AIRFLOW__CORE__DEFAULT_IMPERSONATION']
def test_impersonation_subdag(self):
"""
Tests that impersonation using a subdag correctly passes the right configuration
:return:
"""
self.run_backfill(
'impersonation_subdag',
'test_subdag_operation'
)
class TestImpersonationWithCustomPythonPath(unittest.TestCase):
@mock_custom_module_path(TEST_UTILS_FOLDER)
def setUp(self):
check_original_docker_image()
grant_permissions()
add_default_pool_if_not_exists()
self.dagbag = models.DagBag(
dag_folder=TEST_DAG_CORRUPTED_FOLDER,
include_examples=False,
)
logger.info('Loaded DAGS:')
logger.info(self.dagbag.dagbag_report())
create_user()
def tearDown(self):
subprocess.check_output(['sudo', 'userdel', '-r', TEST_USER])
revoke_permissions()
def run_backfill(self, dag_id, task_id):
dag = self.dagbag.get_dag(dag_id)
dag.clear()
jobs.BackfillJob(
dag=dag,
start_date=DEFAULT_DATE,
end_date=DEFAULT_DATE).run()
ti = models.TaskInstance(
task=dag.get_task(task_id),
execution_date=DEFAULT_DATE)
ti.refresh_from_db()
self.assertEqual(ti.state, State.SUCCESS)
@mock_custom_module_path(TEST_UTILS_FOLDER)
def test_impersonation_custom(self):
"""
Tests that impersonation using a unix user works with custom packages in
PYTHONPATH
"""
# PYTHONPATH is already set in script triggering tests
assert 'PYTHONPATH' in os.environ
self.run_backfill(
'impersonation_with_custom_pkg',
'exec_python_fn'
)
| []
| []
| [
"PYTHON_BASE_IMAGE",
"AIRFLOW_HOME",
"AIRFLOW__CORE__DEFAULT_IMPERSONATION"
]
| [] | ["PYTHON_BASE_IMAGE", "AIRFLOW_HOME", "AIRFLOW__CORE__DEFAULT_IMPERSONATION"] | python | 3 | 0 | |
_examples/tokens/main.go | package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"github.com/google/uuid"
"github.com/upbound/up-sdk-go"
"github.com/upbound/up-sdk-go/service/tokens"
)
// Creates a control plane token for the specified control plane.
func main() {
// Prompt for auth input
fmt.Println("Enter username: ")
var user string
fmt.Scanln(&user)
fmt.Println("Enter password: ")
var password string
fmt.Scanln(&password)
fmt.Println("Enter control plane ID: ")
var cpID string
fmt.Scanln(&cpID)
var api string
if api = os.Getenv("UP_ENDPOINT"); api == "" {
api = "https://api.upbound.io"
}
base, _ := url.Parse(api)
cj, err := cookiejar.New(nil)
if err != nil {
panic(err)
}
upClient := up.NewClient(func(c *up.HTTPClient) {
c.BaseURL = base
c.HTTP = &http.Client{
Jar: cj,
}
})
cfg := up.NewConfig(func(cfg *up.Config) {
cfg.Client = upClient
})
auth := &struct {
ID string `json:"id"`
Password string `json:"password"`
}{
ID: user,
Password: password,
}
jsonStr, err := json.Marshal(auth)
if err != nil {
panic(err)
}
u, err := base.Parse("/v1/login")
if err != nil {
panic(err)
}
req, err := http.NewRequest(http.MethodPost, u.String(), bytes.NewReader(jsonStr))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
err = cfg.Client.Do(req, nil)
if err != nil {
panic(err)
}
client := tokens.NewClient(cfg)
fmt.Println("Creating control plane token...")
cp, err := client.Create(context.Background(), &tokens.TokenCreateParameters{
Attributes: tokens.TokenAttributes{
Name: "cool token",
},
Relationships: tokens.TokenRelationships{
Owner: tokens.TokenOwner{
Data: tokens.TokenOwnerData{
Type: tokens.TokenOwnerControlPlane,
ID: uuid.MustParse(cpID),
},
},
},
})
if err != nil {
panic(err)
}
fmt.Printf("Token: %v\n", cp.DataSet.Meta["jwt"])
}
| [
"\"UP_ENDPOINT\""
]
| []
| [
"UP_ENDPOINT"
]
| [] | ["UP_ENDPOINT"] | go | 1 | 0 | |
clients/google-api-services-admin/reports_v1/1.31.0/com/google/api/services/reports/Reports.java | /*
* 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 code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.reports;
/**
* Service definition for Reports (reports_v1).
*
* <p>
* Admin SDK lets administrators of enterprise domains to view and manage resources like user, groups etc. It also provides audit and usage reports of domain.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://developers.google.com/admin-sdk/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link ReportsRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class Reports extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
(com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 32 ||
(com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION == 31 &&
com.google.api.client.googleapis.GoogleUtils.BUGFIX_VERSION >= 1)),
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.31.1 of google-api-client to run version " +
"1.32.1 of the Admin SDK API library.", com.google.api.client.googleapis.GoogleUtils.VERSION);
}
/**
* The default encoded root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_ROOT_URL = "https://admin.googleapis.com/";
/**
* The default encoded mTLS root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.31
*/
public static final String DEFAULT_MTLS_ROOT_URL = "https://admin.mtls.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Reports(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
this(new Builder(transport, jsonFactory, httpRequestInitializer));
}
/**
* @param builder builder
*/
Reports(Builder builder) {
super(builder);
}
@Override
protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException {
super.initialize(httpClientRequest);
}
/**
* An accessor for creating requests from the Activities collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Reports admin = new Reports(...);}
* {@code Reports.Activities.List request = admin.activities().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Activities activities() {
return new Activities();
}
/**
* The "activities" collection of methods.
*/
public class Activities {
/**
* Retrieves a list of activities for a specific customer's account and application such as the
* Admin console application or the Google Drive application. For more information, see the guides
* for administrator and Google Drive activity reports. For more information about the activity
* report's parameters, see the activity parameters reference guides.
*
* Create a request for the method "activities.list".
*
* This request holds the parameters needed by the admin server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param userKey Represents the profile ID or the user email for which the data should be filtered. Can be `all` for
* all information, or `userKey` for a user's unique Google Workspace profile ID or their
* primary email address. Must not be a deleted user. For a deleted user, call `users.list`
* in Directory API with `showDeleted=true`, then use the returned `ID` as the `userKey`.
* @param applicationName Application name for which the events are to be retrieved.
* @return the request
*/
public List list(java.lang.String userKey, java.lang.String applicationName) throws java.io.IOException {
List result = new List(userKey, applicationName);
initialize(result);
return result;
}
public class List extends ReportsRequest<com.google.api.services.reports.model.Activities> {
private static final String REST_PATH = "admin/reports/v1/activity/users/{userKey}/applications/{applicationName}";
private final java.util.regex.Pattern APPLICATION_NAME_PATTERN =
java.util.regex.Pattern.compile("(access_transparency)|(admin)|(calendar)|(chat)|(chrome)|(context_aware_access)|(data_studio)|(drive)|(gcp)|(gplus)|(groups)|(groups_enterprise)|(jamboard)|(keep)|(login)|(meet)|(mobile)|(rules)|(saml)|(token)|(user_accounts)");
private final java.util.regex.Pattern CUSTOMER_ID_PATTERN =
java.util.regex.Pattern.compile("C.+|my_customer");
private final java.util.regex.Pattern END_TIME_PATTERN =
java.util.regex.Pattern.compile("(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))");
private final java.util.regex.Pattern FILTERS_PATTERN =
java.util.regex.Pattern.compile("(.+[<,<=,==,>=,>,<>].+,)*(.+[<,<=,==,>=,>,<>].+)");
private final java.util.regex.Pattern GROUP_ID_FILTER_PATTERN =
java.util.regex.Pattern.compile("(id:[a-z0-9]+(,id:[a-z0-9]+)*)");
private final java.util.regex.Pattern ORG_UNIT_ID_PATTERN =
java.util.regex.Pattern.compile("(id:[a-z0-9]+)");
private final java.util.regex.Pattern START_TIME_PATTERN =
java.util.regex.Pattern.compile("(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))");
/**
* Retrieves a list of activities for a specific customer's account and application such as the
* Admin console application or the Google Drive application. For more information, see the guides
* for administrator and Google Drive activity reports. For more information about the activity
* report's parameters, see the activity parameters reference guides.
*
* Create a request for the method "activities.list".
*
* This request holds the parameters needed by the the admin server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation. <p> {@link
* List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be
* called to initialize this instance immediately after invoking the constructor. </p>
*
* @param userKey Represents the profile ID or the user email for which the data should be filtered. Can be `all` for
* all information, or `userKey` for a user's unique Google Workspace profile ID or their
* primary email address. Must not be a deleted user. For a deleted user, call `users.list`
* in Directory API with `showDeleted=true`, then use the returned `ID` as the `userKey`.
* @param applicationName Application name for which the events are to be retrieved.
* @since 1.13
*/
protected List(java.lang.String userKey, java.lang.String applicationName) {
super(Reports.this, "GET", REST_PATH, null, com.google.api.services.reports.model.Activities.class);
this.userKey = com.google.api.client.util.Preconditions.checkNotNull(userKey, "Required parameter userKey must be specified.");
this.applicationName = com.google.api.client.util.Preconditions.checkNotNull(applicationName, "Required parameter applicationName must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(APPLICATION_NAME_PATTERN.matcher(applicationName).matches(),
"Parameter applicationName must conform to the pattern " +
"(access_transparency)|(admin)|(calendar)|(chat)|(chrome)|(context_aware_access)|(data_studio)|(drive)|(gcp)|(gplus)|(groups)|(groups_enterprise)|(jamboard)|(keep)|(login)|(meet)|(mobile)|(rules)|(saml)|(token)|(user_accounts)");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setCallback(java.lang.String callback) {
return (List) super.setCallback(callback);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUploadType(java.lang.String uploadType) {
return (List) super.setUploadType(uploadType);
}
@Override
public List setUploadProtocol(java.lang.String uploadProtocol) {
return (List) super.setUploadProtocol(uploadProtocol);
}
/**
* Represents the profile ID or the user email for which the data should be filtered. Can be
* `all` for all information, or `userKey` for a user's unique Google Workspace profile ID or
* their primary email address. Must not be a deleted user. For a deleted user, call
* `users.list` in Directory API with `showDeleted=true`, then use the returned `ID` as the
* `userKey`.
*/
@com.google.api.client.util.Key
private java.lang.String userKey;
/** Represents the profile ID or the user email for which the data should be filtered. Can be `all` for
all information, or `userKey` for a user's unique Google Workspace profile ID or their primary
email address. Must not be a deleted user. For a deleted user, call `users.list` in Directory API
with `showDeleted=true`, then use the returned `ID` as the `userKey`.
*/
public java.lang.String getUserKey() {
return userKey;
}
/**
* Represents the profile ID or the user email for which the data should be filtered. Can be
* `all` for all information, or `userKey` for a user's unique Google Workspace profile ID or
* their primary email address. Must not be a deleted user. For a deleted user, call
* `users.list` in Directory API with `showDeleted=true`, then use the returned `ID` as the
* `userKey`.
*/
public List setUserKey(java.lang.String userKey) {
this.userKey = userKey;
return this;
}
/** Application name for which the events are to be retrieved. */
@com.google.api.client.util.Key
private java.lang.String applicationName;
/** Application name for which the events are to be retrieved.
*/
public java.lang.String getApplicationName() {
return applicationName;
}
/** Application name for which the events are to be retrieved. */
public List setApplicationName(java.lang.String applicationName) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(APPLICATION_NAME_PATTERN.matcher(applicationName).matches(),
"Parameter applicationName must conform to the pattern " +
"(access_transparency)|(admin)|(calendar)|(chat)|(chrome)|(context_aware_access)|(data_studio)|(drive)|(gcp)|(gplus)|(groups)|(groups_enterprise)|(jamboard)|(keep)|(login)|(meet)|(mobile)|(rules)|(saml)|(token)|(user_accounts)");
}
this.applicationName = applicationName;
return this;
}
/**
* The Internet Protocol (IP) Address of host where the event was performed. This is an
* additional way to filter a report's summary using the IP address of the user whose activity
* is being reported. This IP address may or may not reflect the user's physical location. For
* example, the IP address can be the user's proxy server's address or a virtual private
* network (VPN) address. This parameter supports both IPv4 and IPv6 address versions.
*/
@com.google.api.client.util.Key
private java.lang.String actorIpAddress;
/** The Internet Protocol (IP) Address of host where the event was performed. This is an additional way
to filter a report's summary using the IP address of the user whose activity is being reported.
This IP address may or may not reflect the user's physical location. For example, the IP address
can be the user's proxy server's address or a virtual private network (VPN) address. This parameter
supports both IPv4 and IPv6 address versions.
*/
public java.lang.String getActorIpAddress() {
return actorIpAddress;
}
/**
* The Internet Protocol (IP) Address of host where the event was performed. This is an
* additional way to filter a report's summary using the IP address of the user whose activity
* is being reported. This IP address may or may not reflect the user's physical location. For
* example, the IP address can be the user's proxy server's address or a virtual private
* network (VPN) address. This parameter supports both IPv4 and IPv6 address versions.
*/
public List setActorIpAddress(java.lang.String actorIpAddress) {
this.actorIpAddress = actorIpAddress;
return this;
}
/** The unique ID of the customer to retrieve data for. */
@com.google.api.client.util.Key
private java.lang.String customerId;
/** The unique ID of the customer to retrieve data for.
*/
public java.lang.String getCustomerId() {
return customerId;
}
/** The unique ID of the customer to retrieve data for. */
public List setCustomerId(java.lang.String customerId) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(CUSTOMER_ID_PATTERN.matcher(customerId).matches(),
"Parameter customerId must conform to the pattern " +
"C.+|my_customer");
}
this.customerId = customerId;
return this;
}
/**
* Sets the end of the range of time shown in the report. The date is in the RFC 3339 format,
* for example 2010-10-28T10:26:35.000Z. The default value is the approximate time of the API
* request. An API report has three basic time concepts: - *Date of the API's request for a
* report*: When the API created and retrieved the report. - *Report's start time*: The
* beginning of the timespan shown in the report. The `startTime` must be before the `endTime`
* (if specified) and the current time when the request is made, or the API returns an error.
* - *Report's end time*: The end of the timespan shown in the report. For example, the
* timespan of events summarized in a report can start in April and end in May. The report
* itself can be requested in August. If the `endTime` is not specified, the report returns
* all activities from the `startTime` until the current time or the most recent 180 days if
* the `startTime` is more than 180 days in the past.
*/
@com.google.api.client.util.Key
private java.lang.String endTime;
/** Sets the end of the range of time shown in the report. The date is in the RFC 3339 format, for
example 2010-10-28T10:26:35.000Z. The default value is the approximate time of the API request. An
API report has three basic time concepts: - *Date of the API's request for a report*: When the API
created and retrieved the report. - *Report's start time*: The beginning of the timespan shown in
the report. The `startTime` must be before the `endTime` (if specified) and the current time when
the request is made, or the API returns an error. - *Report's end time*: The end of the timespan
shown in the report. For example, the timespan of events summarized in a report can start in April
and end in May. The report itself can be requested in August. If the `endTime` is not specified,
the report returns all activities from the `startTime` until the current time or the most recent
180 days if the `startTime` is more than 180 days in the past.
*/
public java.lang.String getEndTime() {
return endTime;
}
/**
* Sets the end of the range of time shown in the report. The date is in the RFC 3339 format,
* for example 2010-10-28T10:26:35.000Z. The default value is the approximate time of the API
* request. An API report has three basic time concepts: - *Date of the API's request for a
* report*: When the API created and retrieved the report. - *Report's start time*: The
* beginning of the timespan shown in the report. The `startTime` must be before the `endTime`
* (if specified) and the current time when the request is made, or the API returns an error.
* - *Report's end time*: The end of the timespan shown in the report. For example, the
* timespan of events summarized in a report can start in April and end in May. The report
* itself can be requested in August. If the `endTime` is not specified, the report returns
* all activities from the `startTime` until the current time or the most recent 180 days if
* the `startTime` is more than 180 days in the past.
*/
public List setEndTime(java.lang.String endTime) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(END_TIME_PATTERN.matcher(endTime).matches(),
"Parameter endTime must conform to the pattern " +
"(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))");
}
this.endTime = endTime;
return this;
}
/**
* The name of the event being queried by the API. Each `eventName` is related to a specific
* Google Workspace service or feature which the API organizes into types of events. An
* example is the Google Calendar events in the Admin console application's reports. The
* Calendar Settings `type` structure has all of the Calendar `eventName` activities reported
* by the API. When an administrator changes a Calendar setting, the API reports this activity
* in the Calendar Settings `type` and `eventName` parameters. For more information about
* `eventName` query strings and parameters, see the list of event names for various
* applications above in `applicationName`.
*/
@com.google.api.client.util.Key
private java.lang.String eventName;
/** The name of the event being queried by the API. Each `eventName` is related to a specific Google
Workspace service or feature which the API organizes into types of events. An example is the Google
Calendar events in the Admin console application's reports. The Calendar Settings `type` structure
has all of the Calendar `eventName` activities reported by the API. When an administrator changes a
Calendar setting, the API reports this activity in the Calendar Settings `type` and `eventName`
parameters. For more information about `eventName` query strings and parameters, see the list of
event names for various applications above in `applicationName`.
*/
public java.lang.String getEventName() {
return eventName;
}
/**
* The name of the event being queried by the API. Each `eventName` is related to a specific
* Google Workspace service or feature which the API organizes into types of events. An
* example is the Google Calendar events in the Admin console application's reports. The
* Calendar Settings `type` structure has all of the Calendar `eventName` activities reported
* by the API. When an administrator changes a Calendar setting, the API reports this activity
* in the Calendar Settings `type` and `eventName` parameters. For more information about
* `eventName` query strings and parameters, see the list of event names for various
* applications above in `applicationName`.
*/
public List setEventName(java.lang.String eventName) {
this.eventName = eventName;
return this;
}
/**
* The `filters` query string is a comma-separated list. The list is composed of event
* parameters that are manipulated by relational operators. Event parameters are in the form
* `parameter1 name[parameter1 value],parameter2 name[parameter2 value],...` These event
* parameters are associated with a specific `eventName`. An empty report is returned if the
* filtered request's parameter does not belong to the `eventName`. For more information about
* `eventName` parameters, see the list of event names for various applications above in
* `applicationName`. In the following Admin Activity example, the <> operator is URL-encoded
* in the request's query string (%3C%3E): GET...=CHANGE_CALENDAR_SETTING
* =NEW_VALUE%3C%3EREAD_ONLY_ACCESS In the following Drive example, the list can be a view or
* edit event's `doc_id` parameter with a value that is manipulated by an 'equal to' (==) or
* 'not equal to' (<>) relational operator. In the first example, the report returns each
* edited document's `doc_id`. In the second example, the report returns each viewed
* document's `doc_id` that equals the value 12345 and does not return any viewed document's
* which have a `doc_id` value of 98765. The <> operator is URL-encoded in the request's query
* string (%3C%3E): GET...=edit=doc_id GET...=view=doc_id==12345,doc_id%3C%3E98765 The
* relational operators include: - `==` - 'equal to'. - `<>` - 'not equal to'. It is URL-
* encoded (%3C%3E). - `<` - 'less than'. It is URL-encoded (%3C). - `<=` - 'less than or
* equal to'. It is URL-encoded (%3C=). - `>` - 'greater than'. It is URL-encoded (%3E). -
* `>=` - 'greater than or equal to'. It is URL-encoded (%3E=). *Note:* The API doesn't accept
* multiple values of a parameter. If a particular parameter is supplied more than once in the
* API request, the API only accepts the last value of that request parameter. In addition, if
* an invalid request parameter is supplied in the API request, the API ignores that request
* parameter and returns the response corresponding to the remaining valid request parameters.
* If no parameters are requested, all parameters are returned.
*/
@com.google.api.client.util.Key
private java.lang.String filters;
/** The `filters` query string is a comma-separated list. The list is composed of event parameters that
are manipulated by relational operators. Event parameters are in the form `parameter1
name[parameter1 value],parameter2 name[parameter2 value],...` These event parameters are associated
with a specific `eventName`. An empty report is returned if the filtered request's parameter does
not belong to the `eventName`. For more information about `eventName` parameters, see the list of
event names for various applications above in `applicationName`. In the following Admin Activity
example, the <> operator is URL-encoded in the request's query string (%3C%3E):
GET...=CHANGE_CALENDAR_SETTING =NEW_VALUE%3C%3EREAD_ONLY_ACCESS In the following Drive example, the
list can be a view or edit event's `doc_id` parameter with a value that is manipulated by an 'equal
to' (==) or 'not equal to' (<>) relational operator. In the first example, the report returns each
edited document's `doc_id`. In the second example, the report returns each viewed document's
`doc_id` that equals the value 12345 and does not return any viewed document's which have a
`doc_id` value of 98765. The <> operator is URL-encoded in the request's query string (%3C%3E):
GET...=edit=doc_id GET...=view=doc_id==12345,doc_id%3C%3E98765 The relational operators include: -
`==` - 'equal to'. - `<>` - 'not equal to'. It is URL-encoded (%3C%3E). - `<` - 'less than'. It is
URL-encoded (%3C). - `<=` - 'less than or equal to'. It is URL-encoded (%3C=). - `>` - 'greater
than'. It is URL-encoded (%3E). - `>=` - 'greater than or equal to'. It is URL-encoded (%3E=).
*Note:* The API doesn't accept multiple values of a parameter. If a particular parameter is
supplied more than once in the API request, the API only accepts the last value of that request
parameter. In addition, if an invalid request parameter is supplied in the API request, the API
ignores that request parameter and returns the response corresponding to the remaining valid
request parameters. If no parameters are requested, all parameters are returned.
*/
public java.lang.String getFilters() {
return filters;
}
/**
* The `filters` query string is a comma-separated list. The list is composed of event
* parameters that are manipulated by relational operators. Event parameters are in the form
* `parameter1 name[parameter1 value],parameter2 name[parameter2 value],...` These event
* parameters are associated with a specific `eventName`. An empty report is returned if the
* filtered request's parameter does not belong to the `eventName`. For more information about
* `eventName` parameters, see the list of event names for various applications above in
* `applicationName`. In the following Admin Activity example, the <> operator is URL-encoded
* in the request's query string (%3C%3E): GET...=CHANGE_CALENDAR_SETTING
* =NEW_VALUE%3C%3EREAD_ONLY_ACCESS In the following Drive example, the list can be a view or
* edit event's `doc_id` parameter with a value that is manipulated by an 'equal to' (==) or
* 'not equal to' (<>) relational operator. In the first example, the report returns each
* edited document's `doc_id`. In the second example, the report returns each viewed
* document's `doc_id` that equals the value 12345 and does not return any viewed document's
* which have a `doc_id` value of 98765. The <> operator is URL-encoded in the request's query
* string (%3C%3E): GET...=edit=doc_id GET...=view=doc_id==12345,doc_id%3C%3E98765 The
* relational operators include: - `==` - 'equal to'. - `<>` - 'not equal to'. It is URL-
* encoded (%3C%3E). - `<` - 'less than'. It is URL-encoded (%3C). - `<=` - 'less than or
* equal to'. It is URL-encoded (%3C=). - `>` - 'greater than'. It is URL-encoded (%3E). -
* `>=` - 'greater than or equal to'. It is URL-encoded (%3E=). *Note:* The API doesn't accept
* multiple values of a parameter. If a particular parameter is supplied more than once in the
* API request, the API only accepts the last value of that request parameter. In addition, if
* an invalid request parameter is supplied in the API request, the API ignores that request
* parameter and returns the response corresponding to the remaining valid request parameters.
* If no parameters are requested, all parameters are returned.
*/
public List setFilters(java.lang.String filters) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(FILTERS_PATTERN.matcher(filters).matches(),
"Parameter filters must conform to the pattern " +
"(.+[<,<=,==,>=,>,<>].+,)*(.+[<,<=,==,>=,>,<>].+)");
}
this.filters = filters;
return this;
}
/**
* Comma separated group ids (obfuscated) on which user activities are filtered, i.e. the
* response will contain activities for only those users that are a part of at least one of
* the group ids mentioned here. Format: "id:abc123,id:xyz456"
*/
@com.google.api.client.util.Key
private java.lang.String groupIdFilter;
/** Comma separated group ids (obfuscated) on which user activities are filtered, i.e. the response
will contain activities for only those users that are a part of at least one of the group ids
mentioned here. Format: "id:abc123,id:xyz456"
*/
public java.lang.String getGroupIdFilter() {
return groupIdFilter;
}
/**
* Comma separated group ids (obfuscated) on which user activities are filtered, i.e. the
* response will contain activities for only those users that are a part of at least one of
* the group ids mentioned here. Format: "id:abc123,id:xyz456"
*/
public List setGroupIdFilter(java.lang.String groupIdFilter) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(GROUP_ID_FILTER_PATTERN.matcher(groupIdFilter).matches(),
"Parameter groupIdFilter must conform to the pattern " +
"(id:[a-z0-9]+(,id:[a-z0-9]+)*)");
}
this.groupIdFilter = groupIdFilter;
return this;
}
/**
* Determines how many activity records are shown on each response page. For example, if the
* request sets `maxResults=1` and the report has two activities, the report has two pages.
* The response's `nextPageToken` property has the token to the second page. The `maxResults`
* query string is optional in the request. The default value is 1000.
*/
@com.google.api.client.util.Key
private java.lang.Integer maxResults;
/** Determines how many activity records are shown on each response page. For example, if the request
sets `maxResults=1` and the report has two activities, the report has two pages. The response's
`nextPageToken` property has the token to the second page. The `maxResults` query string is
optional in the request. The default value is 1000. [default: 1000] [minimum: 1] [maximum: 1000]
*/
public java.lang.Integer getMaxResults() {
return maxResults;
}
/**
* Determines how many activity records are shown on each response page. For example, if the
* request sets `maxResults=1` and the report has two activities, the report has two pages.
* The response's `nextPageToken` property has the token to the second page. The `maxResults`
* query string is optional in the request. The default value is 1000.
*/
public List setMaxResults(java.lang.Integer maxResults) {
this.maxResults = maxResults;
return this;
}
/**
* ID of the organizational unit to report on. Activity records will be shown only for users
* who belong to the specified organizational unit. Data before Dec 17, 2018 doesn't appear in
* the filtered results.
*/
@com.google.api.client.util.Key
private java.lang.String orgUnitID;
/** ID of the organizational unit to report on. Activity records will be shown only for users who
belong to the specified organizational unit. Data before Dec 17, 2018 doesn't appear in the
filtered results.
*/
public java.lang.String getOrgUnitID() {
return orgUnitID;
}
/**
* ID of the organizational unit to report on. Activity records will be shown only for users
* who belong to the specified organizational unit. Data before Dec 17, 2018 doesn't appear in
* the filtered results.
*/
public List setOrgUnitID(java.lang.String orgUnitID) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(ORG_UNIT_ID_PATTERN.matcher(orgUnitID).matches(),
"Parameter orgUnitID must conform to the pattern " +
"(id:[a-z0-9]+)");
}
this.orgUnitID = orgUnitID;
return this;
}
/**
* The token to specify next page. A report with multiple pages has a `nextPageToken` property
* in the response. In your follow-on request getting the next page of the report, enter the
* `nextPageToken` value in the `pageToken` query string.
*/
@com.google.api.client.util.Key
private java.lang.String pageToken;
/** The token to specify next page. A report with multiple pages has a `nextPageToken` property in the
response. In your follow-on request getting the next page of the report, enter the `nextPageToken`
value in the `pageToken` query string.
*/
public java.lang.String getPageToken() {
return pageToken;
}
/**
* The token to specify next page. A report with multiple pages has a `nextPageToken` property
* in the response. In your follow-on request getting the next page of the report, enter the
* `nextPageToken` value in the `pageToken` query string.
*/
public List setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
/**
* Sets the beginning of the range of time shown in the report. The date is in the RFC 3339
* format, for example 2010-10-28T10:26:35.000Z. The report returns all activities from
* `startTime` until `endTime`. The `startTime` must be before the `endTime` (if specified)
* and the current time when the request is made, or the API returns an error.
*/
@com.google.api.client.util.Key
private java.lang.String startTime;
/** Sets the beginning of the range of time shown in the report. The date is in the RFC 3339 format,
for example 2010-10-28T10:26:35.000Z. The report returns all activities from `startTime` until
`endTime`. The `startTime` must be before the `endTime` (if specified) and the current time when
the request is made, or the API returns an error.
*/
public java.lang.String getStartTime() {
return startTime;
}
/**
* Sets the beginning of the range of time shown in the report. The date is in the RFC 3339
* format, for example 2010-10-28T10:26:35.000Z. The report returns all activities from
* `startTime` until `endTime`. The `startTime` must be before the `endTime` (if specified)
* and the current time when the request is made, or the API returns an error.
*/
public List setStartTime(java.lang.String startTime) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(START_TIME_PATTERN.matcher(startTime).matches(),
"Parameter startTime must conform to the pattern " +
"(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))");
}
this.startTime = startTime;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
/**
* Start receiving notifications for account activities. For more information, see Receiving Push
* Notifications.
*
* Create a request for the method "activities.watch".
*
* This request holds the parameters needed by the admin server. After setting any optional
* parameters, call the {@link Watch#execute()} method to invoke the remote operation.
*
* @param userKey Represents the profile ID or the user email for which the data should be filtered. Can be `all` for
* all information, or `userKey` for a user's unique Google Workspace profile ID or their
* primary email address. Must not be a deleted user. For a deleted user, call `users.list`
* in Directory API with `showDeleted=true`, then use the returned `ID` as the `userKey`.
* @param applicationName Application name for which the events are to be retrieved.
* @param content the {@link com.google.api.services.reports.model.Channel}
* @return the request
*/
public Watch watch(java.lang.String userKey, java.lang.String applicationName, com.google.api.services.reports.model.Channel content) throws java.io.IOException {
Watch result = new Watch(userKey, applicationName, content);
initialize(result);
return result;
}
public class Watch extends ReportsRequest<com.google.api.services.reports.model.Channel> {
private static final String REST_PATH = "admin/reports/v1/activity/users/{userKey}/applications/{applicationName}/watch";
private final java.util.regex.Pattern APPLICATION_NAME_PATTERN =
java.util.regex.Pattern.compile("(access_transparency)|(admin)|(calendar)|(chat)|(chrome)|(context_aware_access)|(data_studio)|(drive)|(gcp)|(gplus)|(groups)|(groups_enterprise)|(jamboard)|(keep)|(login)|(meet)|(mobile)|(rules)|(saml)|(token)|(user_accounts)");
private final java.util.regex.Pattern CUSTOMER_ID_PATTERN =
java.util.regex.Pattern.compile("C.+|my_customer");
private final java.util.regex.Pattern END_TIME_PATTERN =
java.util.regex.Pattern.compile("(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))");
private final java.util.regex.Pattern FILTERS_PATTERN =
java.util.regex.Pattern.compile("(.+[<,<=,==,>=,>,<>].+,)*(.+[<,<=,==,>=,>,<>].+)");
private final java.util.regex.Pattern GROUP_ID_FILTER_PATTERN =
java.util.regex.Pattern.compile("(id:[a-z0-9]+(,id:[a-z0-9]+)*)");
private final java.util.regex.Pattern ORG_UNIT_ID_PATTERN =
java.util.regex.Pattern.compile("(id:[a-z0-9]+)");
private final java.util.regex.Pattern START_TIME_PATTERN =
java.util.regex.Pattern.compile("(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))");
/**
* Start receiving notifications for account activities. For more information, see Receiving Push
* Notifications.
*
* Create a request for the method "activities.watch".
*
* This request holds the parameters needed by the the admin server. After setting any optional
* parameters, call the {@link Watch#execute()} method to invoke the remote operation. <p> {@link
* Watch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param userKey Represents the profile ID or the user email for which the data should be filtered. Can be `all` for
* all information, or `userKey` for a user's unique Google Workspace profile ID or their
* primary email address. Must not be a deleted user. For a deleted user, call `users.list`
* in Directory API with `showDeleted=true`, then use the returned `ID` as the `userKey`.
* @param applicationName Application name for which the events are to be retrieved.
* @param content the {@link com.google.api.services.reports.model.Channel}
* @since 1.13
*/
protected Watch(java.lang.String userKey, java.lang.String applicationName, com.google.api.services.reports.model.Channel content) {
super(Reports.this, "POST", REST_PATH, content, com.google.api.services.reports.model.Channel.class);
this.userKey = com.google.api.client.util.Preconditions.checkNotNull(userKey, "Required parameter userKey must be specified.");
this.applicationName = com.google.api.client.util.Preconditions.checkNotNull(applicationName, "Required parameter applicationName must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(APPLICATION_NAME_PATTERN.matcher(applicationName).matches(),
"Parameter applicationName must conform to the pattern " +
"(access_transparency)|(admin)|(calendar)|(chat)|(chrome)|(context_aware_access)|(data_studio)|(drive)|(gcp)|(gplus)|(groups)|(groups_enterprise)|(jamboard)|(keep)|(login)|(meet)|(mobile)|(rules)|(saml)|(token)|(user_accounts)");
}
}
@Override
public Watch set$Xgafv(java.lang.String $Xgafv) {
return (Watch) super.set$Xgafv($Xgafv);
}
@Override
public Watch setAccessToken(java.lang.String accessToken) {
return (Watch) super.setAccessToken(accessToken);
}
@Override
public Watch setAlt(java.lang.String alt) {
return (Watch) super.setAlt(alt);
}
@Override
public Watch setCallback(java.lang.String callback) {
return (Watch) super.setCallback(callback);
}
@Override
public Watch setFields(java.lang.String fields) {
return (Watch) super.setFields(fields);
}
@Override
public Watch setKey(java.lang.String key) {
return (Watch) super.setKey(key);
}
@Override
public Watch setOauthToken(java.lang.String oauthToken) {
return (Watch) super.setOauthToken(oauthToken);
}
@Override
public Watch setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Watch) super.setPrettyPrint(prettyPrint);
}
@Override
public Watch setQuotaUser(java.lang.String quotaUser) {
return (Watch) super.setQuotaUser(quotaUser);
}
@Override
public Watch setUploadType(java.lang.String uploadType) {
return (Watch) super.setUploadType(uploadType);
}
@Override
public Watch setUploadProtocol(java.lang.String uploadProtocol) {
return (Watch) super.setUploadProtocol(uploadProtocol);
}
/**
* Represents the profile ID or the user email for which the data should be filtered. Can be
* `all` for all information, or `userKey` for a user's unique Google Workspace profile ID or
* their primary email address. Must not be a deleted user. For a deleted user, call
* `users.list` in Directory API with `showDeleted=true`, then use the returned `ID` as the
* `userKey`.
*/
@com.google.api.client.util.Key
private java.lang.String userKey;
/** Represents the profile ID or the user email for which the data should be filtered. Can be `all` for
all information, or `userKey` for a user's unique Google Workspace profile ID or their primary
email address. Must not be a deleted user. For a deleted user, call `users.list` in Directory API
with `showDeleted=true`, then use the returned `ID` as the `userKey`.
*/
public java.lang.String getUserKey() {
return userKey;
}
/**
* Represents the profile ID or the user email for which the data should be filtered. Can be
* `all` for all information, or `userKey` for a user's unique Google Workspace profile ID or
* their primary email address. Must not be a deleted user. For a deleted user, call
* `users.list` in Directory API with `showDeleted=true`, then use the returned `ID` as the
* `userKey`.
*/
public Watch setUserKey(java.lang.String userKey) {
this.userKey = userKey;
return this;
}
/** Application name for which the events are to be retrieved. */
@com.google.api.client.util.Key
private java.lang.String applicationName;
/** Application name for which the events are to be retrieved.
*/
public java.lang.String getApplicationName() {
return applicationName;
}
/** Application name for which the events are to be retrieved. */
public Watch setApplicationName(java.lang.String applicationName) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(APPLICATION_NAME_PATTERN.matcher(applicationName).matches(),
"Parameter applicationName must conform to the pattern " +
"(access_transparency)|(admin)|(calendar)|(chat)|(chrome)|(context_aware_access)|(data_studio)|(drive)|(gcp)|(gplus)|(groups)|(groups_enterprise)|(jamboard)|(keep)|(login)|(meet)|(mobile)|(rules)|(saml)|(token)|(user_accounts)");
}
this.applicationName = applicationName;
return this;
}
/**
* The Internet Protocol (IP) Address of host where the event was performed. This is an
* additional way to filter a report's summary using the IP address of the user whose activity
* is being reported. This IP address may or may not reflect the user's physical location. For
* example, the IP address can be the user's proxy server's address or a virtual private
* network (VPN) address. This parameter supports both IPv4 and IPv6 address versions.
*/
@com.google.api.client.util.Key
private java.lang.String actorIpAddress;
/** The Internet Protocol (IP) Address of host where the event was performed. This is an additional way
to filter a report's summary using the IP address of the user whose activity is being reported.
This IP address may or may not reflect the user's physical location. For example, the IP address
can be the user's proxy server's address or a virtual private network (VPN) address. This parameter
supports both IPv4 and IPv6 address versions.
*/
public java.lang.String getActorIpAddress() {
return actorIpAddress;
}
/**
* The Internet Protocol (IP) Address of host where the event was performed. This is an
* additional way to filter a report's summary using the IP address of the user whose activity
* is being reported. This IP address may or may not reflect the user's physical location. For
* example, the IP address can be the user's proxy server's address or a virtual private
* network (VPN) address. This parameter supports both IPv4 and IPv6 address versions.
*/
public Watch setActorIpAddress(java.lang.String actorIpAddress) {
this.actorIpAddress = actorIpAddress;
return this;
}
/** The unique ID of the customer to retrieve data for. */
@com.google.api.client.util.Key
private java.lang.String customerId;
/** The unique ID of the customer to retrieve data for.
*/
public java.lang.String getCustomerId() {
return customerId;
}
/** The unique ID of the customer to retrieve data for. */
public Watch setCustomerId(java.lang.String customerId) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(CUSTOMER_ID_PATTERN.matcher(customerId).matches(),
"Parameter customerId must conform to the pattern " +
"C.+|my_customer");
}
this.customerId = customerId;
return this;
}
/**
* Sets the end of the range of time shown in the report. The date is in the RFC 3339 format,
* for example 2010-10-28T10:26:35.000Z. The default value is the approximate time of the API
* request. An API report has three basic time concepts: - *Date of the API's request for a
* report*: When the API created and retrieved the report. - *Report's start time*: The
* beginning of the timespan shown in the report. The `startTime` must be before the `endTime`
* (if specified) and the current time when the request is made, or the API returns an error.
* - *Report's end time*: The end of the timespan shown in the report. For example, the
* timespan of events summarized in a report can start in April and end in May. The report
* itself can be requested in August. If the `endTime` is not specified, the report returns
* all activities from the `startTime` until the current time or the most recent 180 days if
* the `startTime` is more than 180 days in the past.
*/
@com.google.api.client.util.Key
private java.lang.String endTime;
/** Sets the end of the range of time shown in the report. The date is in the RFC 3339 format, for
example 2010-10-28T10:26:35.000Z. The default value is the approximate time of the API request. An
API report has three basic time concepts: - *Date of the API's request for a report*: When the API
created and retrieved the report. - *Report's start time*: The beginning of the timespan shown in
the report. The `startTime` must be before the `endTime` (if specified) and the current time when
the request is made, or the API returns an error. - *Report's end time*: The end of the timespan
shown in the report. For example, the timespan of events summarized in a report can start in April
and end in May. The report itself can be requested in August. If the `endTime` is not specified,
the report returns all activities from the `startTime` until the current time or the most recent
180 days if the `startTime` is more than 180 days in the past.
*/
public java.lang.String getEndTime() {
return endTime;
}
/**
* Sets the end of the range of time shown in the report. The date is in the RFC 3339 format,
* for example 2010-10-28T10:26:35.000Z. The default value is the approximate time of the API
* request. An API report has three basic time concepts: - *Date of the API's request for a
* report*: When the API created and retrieved the report. - *Report's start time*: The
* beginning of the timespan shown in the report. The `startTime` must be before the `endTime`
* (if specified) and the current time when the request is made, or the API returns an error.
* - *Report's end time*: The end of the timespan shown in the report. For example, the
* timespan of events summarized in a report can start in April and end in May. The report
* itself can be requested in August. If the `endTime` is not specified, the report returns
* all activities from the `startTime` until the current time or the most recent 180 days if
* the `startTime` is more than 180 days in the past.
*/
public Watch setEndTime(java.lang.String endTime) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(END_TIME_PATTERN.matcher(endTime).matches(),
"Parameter endTime must conform to the pattern " +
"(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))");
}
this.endTime = endTime;
return this;
}
/**
* The name of the event being queried by the API. Each `eventName` is related to a specific
* Google Workspace service or feature which the API organizes into types of events. An
* example is the Google Calendar events in the Admin console application's reports. The
* Calendar Settings `type` structure has all of the Calendar `eventName` activities reported
* by the API. When an administrator changes a Calendar setting, the API reports this activity
* in the Calendar Settings `type` and `eventName` parameters. For more information about
* `eventName` query strings and parameters, see the list of event names for various
* applications above in `applicationName`.
*/
@com.google.api.client.util.Key
private java.lang.String eventName;
/** The name of the event being queried by the API. Each `eventName` is related to a specific Google
Workspace service or feature which the API organizes into types of events. An example is the Google
Calendar events in the Admin console application's reports. The Calendar Settings `type` structure
has all of the Calendar `eventName` activities reported by the API. When an administrator changes a
Calendar setting, the API reports this activity in the Calendar Settings `type` and `eventName`
parameters. For more information about `eventName` query strings and parameters, see the list of
event names for various applications above in `applicationName`.
*/
public java.lang.String getEventName() {
return eventName;
}
/**
* The name of the event being queried by the API. Each `eventName` is related to a specific
* Google Workspace service or feature which the API organizes into types of events. An
* example is the Google Calendar events in the Admin console application's reports. The
* Calendar Settings `type` structure has all of the Calendar `eventName` activities reported
* by the API. When an administrator changes a Calendar setting, the API reports this activity
* in the Calendar Settings `type` and `eventName` parameters. For more information about
* `eventName` query strings and parameters, see the list of event names for various
* applications above in `applicationName`.
*/
public Watch setEventName(java.lang.String eventName) {
this.eventName = eventName;
return this;
}
/**
* The `filters` query string is a comma-separated list. The list is composed of event
* parameters that are manipulated by relational operators. Event parameters are in the form
* `parameter1 name[parameter1 value],parameter2 name[parameter2 value],...` These event
* parameters are associated with a specific `eventName`. An empty report is returned if the
* filtered request's parameter does not belong to the `eventName`. For more information about
* `eventName` parameters, see the list of event names for various applications above in
* `applicationName`. In the following Admin Activity example, the <> operator is URL-encoded
* in the request's query string (%3C%3E): GET...=CHANGE_CALENDAR_SETTING
* =NEW_VALUE%3C%3EREAD_ONLY_ACCESS In the following Drive example, the list can be a view or
* edit event's `doc_id` parameter with a value that is manipulated by an 'equal to' (==) or
* 'not equal to' (<>) relational operator. In the first example, the report returns each
* edited document's `doc_id`. In the second example, the report returns each viewed
* document's `doc_id` that equals the value 12345 and does not return any viewed document's
* which have a `doc_id` value of 98765. The <> operator is URL-encoded in the request's query
* string (%3C%3E): GET...=edit=doc_id GET...=view=doc_id==12345,doc_id%3C%3E98765 The
* relational operators include: - `==` - 'equal to'. - `<>` - 'not equal to'. It is URL-
* encoded (%3C%3E). - `<` - 'less than'. It is URL-encoded (%3C). - `<=` - 'less than or
* equal to'. It is URL-encoded (%3C=). - `>` - 'greater than'. It is URL-encoded (%3E). -
* `>=` - 'greater than or equal to'. It is URL-encoded (%3E=). *Note:* The API doesn't accept
* multiple values of a parameter. If a particular parameter is supplied more than once in the
* API request, the API only accepts the last value of that request parameter. In addition, if
* an invalid request parameter is supplied in the API request, the API ignores that request
* parameter and returns the response corresponding to the remaining valid request parameters.
* If no parameters are requested, all parameters are returned.
*/
@com.google.api.client.util.Key
private java.lang.String filters;
/** The `filters` query string is a comma-separated list. The list is composed of event parameters that
are manipulated by relational operators. Event parameters are in the form `parameter1
name[parameter1 value],parameter2 name[parameter2 value],...` These event parameters are associated
with a specific `eventName`. An empty report is returned if the filtered request's parameter does
not belong to the `eventName`. For more information about `eventName` parameters, see the list of
event names for various applications above in `applicationName`. In the following Admin Activity
example, the <> operator is URL-encoded in the request's query string (%3C%3E):
GET...=CHANGE_CALENDAR_SETTING =NEW_VALUE%3C%3EREAD_ONLY_ACCESS In the following Drive example, the
list can be a view or edit event's `doc_id` parameter with a value that is manipulated by an 'equal
to' (==) or 'not equal to' (<>) relational operator. In the first example, the report returns each
edited document's `doc_id`. In the second example, the report returns each viewed document's
`doc_id` that equals the value 12345 and does not return any viewed document's which have a
`doc_id` value of 98765. The <> operator is URL-encoded in the request's query string (%3C%3E):
GET...=edit=doc_id GET...=view=doc_id==12345,doc_id%3C%3E98765 The relational operators include: -
`==` - 'equal to'. - `<>` - 'not equal to'. It is URL-encoded (%3C%3E). - `<` - 'less than'. It is
URL-encoded (%3C). - `<=` - 'less than or equal to'. It is URL-encoded (%3C=). - `>` - 'greater
than'. It is URL-encoded (%3E). - `>=` - 'greater than or equal to'. It is URL-encoded (%3E=).
*Note:* The API doesn't accept multiple values of a parameter. If a particular parameter is
supplied more than once in the API request, the API only accepts the last value of that request
parameter. In addition, if an invalid request parameter is supplied in the API request, the API
ignores that request parameter and returns the response corresponding to the remaining valid
request parameters. If no parameters are requested, all parameters are returned.
*/
public java.lang.String getFilters() {
return filters;
}
/**
* The `filters` query string is a comma-separated list. The list is composed of event
* parameters that are manipulated by relational operators. Event parameters are in the form
* `parameter1 name[parameter1 value],parameter2 name[parameter2 value],...` These event
* parameters are associated with a specific `eventName`. An empty report is returned if the
* filtered request's parameter does not belong to the `eventName`. For more information about
* `eventName` parameters, see the list of event names for various applications above in
* `applicationName`. In the following Admin Activity example, the <> operator is URL-encoded
* in the request's query string (%3C%3E): GET...=CHANGE_CALENDAR_SETTING
* =NEW_VALUE%3C%3EREAD_ONLY_ACCESS In the following Drive example, the list can be a view or
* edit event's `doc_id` parameter with a value that is manipulated by an 'equal to' (==) or
* 'not equal to' (<>) relational operator. In the first example, the report returns each
* edited document's `doc_id`. In the second example, the report returns each viewed
* document's `doc_id` that equals the value 12345 and does not return any viewed document's
* which have a `doc_id` value of 98765. The <> operator is URL-encoded in the request's query
* string (%3C%3E): GET...=edit=doc_id GET...=view=doc_id==12345,doc_id%3C%3E98765 The
* relational operators include: - `==` - 'equal to'. - `<>` - 'not equal to'. It is URL-
* encoded (%3C%3E). - `<` - 'less than'. It is URL-encoded (%3C). - `<=` - 'less than or
* equal to'. It is URL-encoded (%3C=). - `>` - 'greater than'. It is URL-encoded (%3E). -
* `>=` - 'greater than or equal to'. It is URL-encoded (%3E=). *Note:* The API doesn't accept
* multiple values of a parameter. If a particular parameter is supplied more than once in the
* API request, the API only accepts the last value of that request parameter. In addition, if
* an invalid request parameter is supplied in the API request, the API ignores that request
* parameter and returns the response corresponding to the remaining valid request parameters.
* If no parameters are requested, all parameters are returned.
*/
public Watch setFilters(java.lang.String filters) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(FILTERS_PATTERN.matcher(filters).matches(),
"Parameter filters must conform to the pattern " +
"(.+[<,<=,==,>=,>,<>].+,)*(.+[<,<=,==,>=,>,<>].+)");
}
this.filters = filters;
return this;
}
/**
* Comma separated group ids (obfuscated) on which user activities are filtered, i.e. the
* response will contain activities for only those users that are a part of at least one of
* the group ids mentioned here. Format: "id:abc123,id:xyz456"
*/
@com.google.api.client.util.Key
private java.lang.String groupIdFilter;
/** Comma separated group ids (obfuscated) on which user activities are filtered, i.e. the response
will contain activities for only those users that are a part of at least one of the group ids
mentioned here. Format: "id:abc123,id:xyz456"
*/
public java.lang.String getGroupIdFilter() {
return groupIdFilter;
}
/**
* Comma separated group ids (obfuscated) on which user activities are filtered, i.e. the
* response will contain activities for only those users that are a part of at least one of
* the group ids mentioned here. Format: "id:abc123,id:xyz456"
*/
public Watch setGroupIdFilter(java.lang.String groupIdFilter) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(GROUP_ID_FILTER_PATTERN.matcher(groupIdFilter).matches(),
"Parameter groupIdFilter must conform to the pattern " +
"(id:[a-z0-9]+(,id:[a-z0-9]+)*)");
}
this.groupIdFilter = groupIdFilter;
return this;
}
/**
* Determines how many activity records are shown on each response page. For example, if the
* request sets `maxResults=1` and the report has two activities, the report has two pages.
* The response's `nextPageToken` property has the token to the second page. The `maxResults`
* query string is optional in the request. The default value is 1000.
*/
@com.google.api.client.util.Key
private java.lang.Integer maxResults;
/** Determines how many activity records are shown on each response page. For example, if the request
sets `maxResults=1` and the report has two activities, the report has two pages. The response's
`nextPageToken` property has the token to the second page. The `maxResults` query string is
optional in the request. The default value is 1000. [default: 1000] [minimum: 1] [maximum: 1000]
*/
public java.lang.Integer getMaxResults() {
return maxResults;
}
/**
* Determines how many activity records are shown on each response page. For example, if the
* request sets `maxResults=1` and the report has two activities, the report has two pages.
* The response's `nextPageToken` property has the token to the second page. The `maxResults`
* query string is optional in the request. The default value is 1000.
*/
public Watch setMaxResults(java.lang.Integer maxResults) {
this.maxResults = maxResults;
return this;
}
/**
* ID of the organizational unit to report on. Activity records will be shown only for users
* who belong to the specified organizational unit. Data before Dec 17, 2018 doesn't appear in
* the filtered results.
*/
@com.google.api.client.util.Key
private java.lang.String orgUnitID;
/** ID of the organizational unit to report on. Activity records will be shown only for users who
belong to the specified organizational unit. Data before Dec 17, 2018 doesn't appear in the
filtered results.
*/
public java.lang.String getOrgUnitID() {
return orgUnitID;
}
/**
* ID of the organizational unit to report on. Activity records will be shown only for users
* who belong to the specified organizational unit. Data before Dec 17, 2018 doesn't appear in
* the filtered results.
*/
public Watch setOrgUnitID(java.lang.String orgUnitID) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(ORG_UNIT_ID_PATTERN.matcher(orgUnitID).matches(),
"Parameter orgUnitID must conform to the pattern " +
"(id:[a-z0-9]+)");
}
this.orgUnitID = orgUnitID;
return this;
}
/**
* The token to specify next page. A report with multiple pages has a `nextPageToken` property
* in the response. In your follow-on request getting the next page of the report, enter the
* `nextPageToken` value in the `pageToken` query string.
*/
@com.google.api.client.util.Key
private java.lang.String pageToken;
/** The token to specify next page. A report with multiple pages has a `nextPageToken` property in the
response. In your follow-on request getting the next page of the report, enter the `nextPageToken`
value in the `pageToken` query string.
*/
public java.lang.String getPageToken() {
return pageToken;
}
/**
* The token to specify next page. A report with multiple pages has a `nextPageToken` property
* in the response. In your follow-on request getting the next page of the report, enter the
* `nextPageToken` value in the `pageToken` query string.
*/
public Watch setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
/**
* Sets the beginning of the range of time shown in the report. The date is in the RFC 3339
* format, for example 2010-10-28T10:26:35.000Z. The report returns all activities from
* `startTime` until `endTime`. The `startTime` must be before the `endTime` (if specified)
* and the current time when the request is made, or the API returns an error.
*/
@com.google.api.client.util.Key
private java.lang.String startTime;
/** Sets the beginning of the range of time shown in the report. The date is in the RFC 3339 format,
for example 2010-10-28T10:26:35.000Z. The report returns all activities from `startTime` until
`endTime`. The `startTime` must be before the `endTime` (if specified) and the current time when
the request is made, or the API returns an error.
*/
public java.lang.String getStartTime() {
return startTime;
}
/**
* Sets the beginning of the range of time shown in the report. The date is in the RFC 3339
* format, for example 2010-10-28T10:26:35.000Z. The report returns all activities from
* `startTime` until `endTime`. The `startTime` must be before the `endTime` (if specified)
* and the current time when the request is made, or the API returns an error.
*/
public Watch setStartTime(java.lang.String startTime) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(START_TIME_PATTERN.matcher(startTime).matches(),
"Parameter startTime must conform to the pattern " +
"(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))");
}
this.startTime = startTime;
return this;
}
@Override
public Watch set(String parameterName, Object value) {
return (Watch) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the Channels collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Reports admin = new Reports(...);}
* {@code Reports.Channels.List request = admin.channels().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Channels channels() {
return new Channels();
}
/**
* The "channels" collection of methods.
*/
public class Channels {
/**
* Stop watching resources through this channel.
*
* Create a request for the method "channels.stop".
*
* This request holds the parameters needed by the admin server. After setting any optional
* parameters, call the {@link Stop#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.reports.model.Channel}
* @return the request
*/
public Stop stop(com.google.api.services.reports.model.Channel content) throws java.io.IOException {
Stop result = new Stop(content);
initialize(result);
return result;
}
public class Stop extends ReportsRequest<Void> {
private static final String REST_PATH = "admin/reports_v1/channels/stop";
/**
* Stop watching resources through this channel.
*
* Create a request for the method "channels.stop".
*
* This request holds the parameters needed by the the admin server. After setting any optional
* parameters, call the {@link Stop#execute()} method to invoke the remote operation. <p> {@link
* Stop#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be
* called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.reports.model.Channel}
* @since 1.13
*/
protected Stop(com.google.api.services.reports.model.Channel content) {
super(Reports.this, "POST", REST_PATH, content, Void.class);
}
@Override
public Stop set$Xgafv(java.lang.String $Xgafv) {
return (Stop) super.set$Xgafv($Xgafv);
}
@Override
public Stop setAccessToken(java.lang.String accessToken) {
return (Stop) super.setAccessToken(accessToken);
}
@Override
public Stop setAlt(java.lang.String alt) {
return (Stop) super.setAlt(alt);
}
@Override
public Stop setCallback(java.lang.String callback) {
return (Stop) super.setCallback(callback);
}
@Override
public Stop setFields(java.lang.String fields) {
return (Stop) super.setFields(fields);
}
@Override
public Stop setKey(java.lang.String key) {
return (Stop) super.setKey(key);
}
@Override
public Stop setOauthToken(java.lang.String oauthToken) {
return (Stop) super.setOauthToken(oauthToken);
}
@Override
public Stop setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Stop) super.setPrettyPrint(prettyPrint);
}
@Override
public Stop setQuotaUser(java.lang.String quotaUser) {
return (Stop) super.setQuotaUser(quotaUser);
}
@Override
public Stop setUploadType(java.lang.String uploadType) {
return (Stop) super.setUploadType(uploadType);
}
@Override
public Stop setUploadProtocol(java.lang.String uploadProtocol) {
return (Stop) super.setUploadProtocol(uploadProtocol);
}
@Override
public Stop set(String parameterName, Object value) {
return (Stop) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the CustomerUsageReports collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Reports admin = new Reports(...);}
* {@code Reports.CustomerUsageReports.List request = admin.customerUsageReports().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public CustomerUsageReports customerUsageReports() {
return new CustomerUsageReports();
}
/**
* The "customerUsageReports" collection of methods.
*/
public class CustomerUsageReports {
/**
* Retrieves a report which is a collection of properties and statistics for a specific customer's
* account. For more information, see the Customers Usage Report guide. For more information about
* the customer report's parameters, see the Customers Usage parameters reference guides.
*
* Create a request for the method "customerUsageReports.get".
*
* This request holds the parameters needed by the admin server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param date Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-dd. We
* recommend you use your account's time zone for this.
* @return the request
*/
public Get get(java.lang.String date) throws java.io.IOException {
Get result = new Get(date);
initialize(result);
return result;
}
public class Get extends ReportsRequest<com.google.api.services.reports.model.UsageReports> {
private static final String REST_PATH = "admin/reports/v1/usage/dates/{date}";
private final java.util.regex.Pattern DATE_PATTERN =
java.util.regex.Pattern.compile("(\\d){4}-(\\d){2}-(\\d){2}");
private final java.util.regex.Pattern CUSTOMER_ID_PATTERN =
java.util.regex.Pattern.compile("C.+|my_customer");
private final java.util.regex.Pattern PARAMETERS_PATTERN =
java.util.regex.Pattern.compile("(((accounts)|(app_maker)|(apps_scripts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)|(meet)):[^,]+,)*(((accounts)|(app_maker)|(apps_scripts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)|(meet)):[^,]+)");
/**
* Retrieves a report which is a collection of properties and statistics for a specific customer's
* account. For more information, see the Customers Usage Report guide. For more information about
* the customer report's parameters, see the Customers Usage parameters reference guides.
*
* Create a request for the method "customerUsageReports.get".
*
* This request holds the parameters needed by the the admin server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link
* Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be
* called to initialize this instance immediately after invoking the constructor. </p>
*
* @param date Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-dd. We
* recommend you use your account's time zone for this.
* @since 1.13
*/
protected Get(java.lang.String date) {
super(Reports.this, "GET", REST_PATH, null, com.google.api.services.reports.model.UsageReports.class);
this.date = com.google.api.client.util.Preconditions.checkNotNull(date, "Required parameter date must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(DATE_PATTERN.matcher(date).matches(),
"Parameter date must conform to the pattern " +
"(\\d){4}-(\\d){2}-(\\d){2}");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/**
* Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-
* dd. We recommend you use your account's time zone for this.
*/
@com.google.api.client.util.Key
private java.lang.String date;
/** Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-dd. We
recommend you use your account's time zone for this.
*/
public java.lang.String getDate() {
return date;
}
/**
* Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-
* dd. We recommend you use your account's time zone for this.
*/
public Get setDate(java.lang.String date) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(DATE_PATTERN.matcher(date).matches(),
"Parameter date must conform to the pattern " +
"(\\d){4}-(\\d){2}-(\\d){2}");
}
this.date = date;
return this;
}
/** The unique ID of the customer to retrieve data for. */
@com.google.api.client.util.Key
private java.lang.String customerId;
/** The unique ID of the customer to retrieve data for.
*/
public java.lang.String getCustomerId() {
return customerId;
}
/** The unique ID of the customer to retrieve data for. */
public Get setCustomerId(java.lang.String customerId) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(CUSTOMER_ID_PATTERN.matcher(customerId).matches(),
"Parameter customerId must conform to the pattern " +
"C.+|my_customer");
}
this.customerId = customerId;
return this;
}
/**
* Token to specify next page. A report with multiple pages has a `nextPageToken` property in
* the response. For your follow-on requests getting all of the report's pages, enter the
* `nextPageToken` value in the `pageToken` query string.
*/
@com.google.api.client.util.Key
private java.lang.String pageToken;
/** Token to specify next page. A report with multiple pages has a `nextPageToken` property in the
response. For your follow-on requests getting all of the report's pages, enter the `nextPageToken`
value in the `pageToken` query string.
*/
public java.lang.String getPageToken() {
return pageToken;
}
/**
* Token to specify next page. A report with multiple pages has a `nextPageToken` property in
* the response. For your follow-on requests getting all of the report's pages, enter the
* `nextPageToken` value in the `pageToken` query string.
*/
public Get setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
/**
* The `parameters` query string is a comma-separated list of event parameters that refine a
* report's results. The parameter is associated with a specific application. The application
* values for the Customers usage report include `accounts`, `app_maker`, `apps_scripts`,
* `calendar`, `classroom`, `cros`, `docs`, `gmail`, `gplus`, `device_management`, `meet`, and
* `sites`. A `parameters` query string is in the CSV form of `app_name1:param_name1,
* app_name2:param_name2`. *Note:* The API doesn't accept multiple values of a parameter. If a
* particular parameter is supplied more than once in the API request, the API only accepts
* the last value of that request parameter. In addition, if an invalid request parameter is
* supplied in the API request, the API ignores that request parameter and returns the
* response corresponding to the remaining valid request parameters. An example of an invalid
* request parameter is one that does not belong to the application. If no parameters are
* requested, all parameters are returned.
*/
@com.google.api.client.util.Key
private java.lang.String parameters;
/** The `parameters` query string is a comma-separated list of event parameters that refine a report's
results. The parameter is associated with a specific application. The application values for the
Customers usage report include `accounts`, `app_maker`, `apps_scripts`, `calendar`, `classroom`,
`cros`, `docs`, `gmail`, `gplus`, `device_management`, `meet`, and `sites`. A `parameters` query
string is in the CSV form of `app_name1:param_name1, app_name2:param_name2`. *Note:* The API
doesn't accept multiple values of a parameter. If a particular parameter is supplied more than once
in the API request, the API only accepts the last value of that request parameter. In addition, if
an invalid request parameter is supplied in the API request, the API ignores that request parameter
and returns the response corresponding to the remaining valid request parameters. An example of an
invalid request parameter is one that does not belong to the application. If no parameters are
requested, all parameters are returned.
*/
public java.lang.String getParameters() {
return parameters;
}
/**
* The `parameters` query string is a comma-separated list of event parameters that refine a
* report's results. The parameter is associated with a specific application. The application
* values for the Customers usage report include `accounts`, `app_maker`, `apps_scripts`,
* `calendar`, `classroom`, `cros`, `docs`, `gmail`, `gplus`, `device_management`, `meet`, and
* `sites`. A `parameters` query string is in the CSV form of `app_name1:param_name1,
* app_name2:param_name2`. *Note:* The API doesn't accept multiple values of a parameter. If a
* particular parameter is supplied more than once in the API request, the API only accepts
* the last value of that request parameter. In addition, if an invalid request parameter is
* supplied in the API request, the API ignores that request parameter and returns the
* response corresponding to the remaining valid request parameters. An example of an invalid
* request parameter is one that does not belong to the application. If no parameters are
* requested, all parameters are returned.
*/
public Get setParameters(java.lang.String parameters) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARAMETERS_PATTERN.matcher(parameters).matches(),
"Parameter parameters must conform to the pattern " +
"(((accounts)|(app_maker)|(apps_scripts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)|(meet)):[^,]+,)*(((accounts)|(app_maker)|(apps_scripts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)|(meet)):[^,]+)");
}
this.parameters = parameters;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the EntityUsageReports collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Reports admin = new Reports(...);}
* {@code Reports.EntityUsageReports.List request = admin.entityUsageReports().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public EntityUsageReports entityUsageReports() {
return new EntityUsageReports();
}
/**
* The "entityUsageReports" collection of methods.
*/
public class EntityUsageReports {
/**
* Retrieves a report which is a collection of properties and statistics for entities used by users
* within the account. For more information, see the Entities Usage Report guide. For more
* information about the entities report's parameters, see the Entities Usage parameters reference
* guides.
*
* Create a request for the method "entityUsageReports.get".
*
* This request holds the parameters needed by the admin server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param entityType Represents the type of entity for the report.
* @param entityKey Represents the key of the object to filter the data with. It is a string which can take the value
* `all` to get activity events for all users, or any other value for an app-specific entity.
* For details on how to obtain the `entityKey` for a particular `entityType`, see the
* Entities Usage parameters reference guides.
* @param date Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-dd. We
* recommend you use your account's time zone for this.
* @return the request
*/
public Get get(java.lang.String entityType, java.lang.String entityKey, java.lang.String date) throws java.io.IOException {
Get result = new Get(entityType, entityKey, date);
initialize(result);
return result;
}
public class Get extends ReportsRequest<com.google.api.services.reports.model.UsageReports> {
private static final String REST_PATH = "admin/reports/v1/usage/{entityType}/{entityKey}/dates/{date}";
private final java.util.regex.Pattern ENTITY_TYPE_PATTERN =
java.util.regex.Pattern.compile("(gplus_communities)");
private final java.util.regex.Pattern DATE_PATTERN =
java.util.regex.Pattern.compile("(\\d){4}-(\\d){2}-(\\d){2}");
private final java.util.regex.Pattern CUSTOMER_ID_PATTERN =
java.util.regex.Pattern.compile("C.+|my_customer");
private final java.util.regex.Pattern FILTERS_PATTERN =
java.util.regex.Pattern.compile("(((gplus)):[a-z0-9_]+[<,<=,==,>=,>,!=][^,]+,)*(((gplus)):[a-z0-9_]+[<,<=,==,>=,>,!=][^,]+)");
private final java.util.regex.Pattern PARAMETERS_PATTERN =
java.util.regex.Pattern.compile("(((gplus)):[^,]+,)*(((gplus)):[^,]+)");
/**
* Retrieves a report which is a collection of properties and statistics for entities used by
* users within the account. For more information, see the Entities Usage Report guide. For more
* information about the entities report's parameters, see the Entities Usage parameters reference
* guides.
*
* Create a request for the method "entityUsageReports.get".
*
* This request holds the parameters needed by the the admin server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link
* Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be
* called to initialize this instance immediately after invoking the constructor. </p>
*
* @param entityType Represents the type of entity for the report.
* @param entityKey Represents the key of the object to filter the data with. It is a string which can take the value
* `all` to get activity events for all users, or any other value for an app-specific entity.
* For details on how to obtain the `entityKey` for a particular `entityType`, see the
* Entities Usage parameters reference guides.
* @param date Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-dd. We
* recommend you use your account's time zone for this.
* @since 1.13
*/
protected Get(java.lang.String entityType, java.lang.String entityKey, java.lang.String date) {
super(Reports.this, "GET", REST_PATH, null, com.google.api.services.reports.model.UsageReports.class);
this.entityType = com.google.api.client.util.Preconditions.checkNotNull(entityType, "Required parameter entityType must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(ENTITY_TYPE_PATTERN.matcher(entityType).matches(),
"Parameter entityType must conform to the pattern " +
"(gplus_communities)");
}
this.entityKey = com.google.api.client.util.Preconditions.checkNotNull(entityKey, "Required parameter entityKey must be specified.");
this.date = com.google.api.client.util.Preconditions.checkNotNull(date, "Required parameter date must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(DATE_PATTERN.matcher(date).matches(),
"Parameter date must conform to the pattern " +
"(\\d){4}-(\\d){2}-(\\d){2}");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/** Represents the type of entity for the report. */
@com.google.api.client.util.Key
private java.lang.String entityType;
/** Represents the type of entity for the report.
*/
public java.lang.String getEntityType() {
return entityType;
}
/** Represents the type of entity for the report. */
public Get setEntityType(java.lang.String entityType) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(ENTITY_TYPE_PATTERN.matcher(entityType).matches(),
"Parameter entityType must conform to the pattern " +
"(gplus_communities)");
}
this.entityType = entityType;
return this;
}
/**
* Represents the key of the object to filter the data with. It is a string which can take the
* value `all` to get activity events for all users, or any other value for an app-specific
* entity. For details on how to obtain the `entityKey` for a particular `entityType`, see the
* Entities Usage parameters reference guides.
*/
@com.google.api.client.util.Key
private java.lang.String entityKey;
/** Represents the key of the object to filter the data with. It is a string which can take the value
`all` to get activity events for all users, or any other value for an app-specific entity. For
details on how to obtain the `entityKey` for a particular `entityType`, see the Entities Usage
parameters reference guides.
*/
public java.lang.String getEntityKey() {
return entityKey;
}
/**
* Represents the key of the object to filter the data with. It is a string which can take the
* value `all` to get activity events for all users, or any other value for an app-specific
* entity. For details on how to obtain the `entityKey` for a particular `entityType`, see the
* Entities Usage parameters reference guides.
*/
public Get setEntityKey(java.lang.String entityKey) {
this.entityKey = entityKey;
return this;
}
/**
* Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-
* dd. We recommend you use your account's time zone for this.
*/
@com.google.api.client.util.Key
private java.lang.String date;
/** Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-dd. We
recommend you use your account's time zone for this.
*/
public java.lang.String getDate() {
return date;
}
/**
* Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-
* dd. We recommend you use your account's time zone for this.
*/
public Get setDate(java.lang.String date) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(DATE_PATTERN.matcher(date).matches(),
"Parameter date must conform to the pattern " +
"(\\d){4}-(\\d){2}-(\\d){2}");
}
this.date = date;
return this;
}
/** The unique ID of the customer to retrieve data for. */
@com.google.api.client.util.Key
private java.lang.String customerId;
/** The unique ID of the customer to retrieve data for.
*/
public java.lang.String getCustomerId() {
return customerId;
}
/** The unique ID of the customer to retrieve data for. */
public Get setCustomerId(java.lang.String customerId) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(CUSTOMER_ID_PATTERN.matcher(customerId).matches(),
"Parameter customerId must conform to the pattern " +
"C.+|my_customer");
}
this.customerId = customerId;
return this;
}
/**
* The `filters` query string is a comma-separated list of an application's event parameters
* where the parameter's value is manipulated by a relational operator. The `filters` query
* string includes the name of the application whose usage is returned in the report. The
* application values for the Entities usage report include `accounts`, `docs`, and `gmail`.
* Filters are in the form `[application name]:parameter name[parameter value],...`. In this
* example, the `<>` 'not equal to' operator is URL-encoded in the request's query string
* (%3C%3E): GET
* https://www.googleapis.com/admin/reports/v1/usage/gplus_communities/all/dates/2017-12-01
* ?parameters=gplus:community_name,gplus:num_total_members =gplus:num_total_members%3C%3E0
* The relational operators include: - `==` - 'equal to'. - `<>` - 'not equal to'. It is URL-
* encoded (%3C%3E). - `<` - 'less than'. It is URL-encoded (%3C). - `<=` - 'less than or
* equal to'. It is URL-encoded (%3C=). - `>` - 'greater than'. It is URL-encoded (%3E). -
* `>=` - 'greater than or equal to'. It is URL-encoded (%3E=). Filters can only be applied to
* numeric parameters.
*/
@com.google.api.client.util.Key
private java.lang.String filters;
/** The `filters` query string is a comma-separated list of an application's event parameters where the
parameter's value is manipulated by a relational operator. The `filters` query string includes the
name of the application whose usage is returned in the report. The application values for the
Entities usage report include `accounts`, `docs`, and `gmail`. Filters are in the form
`[application name]:parameter name[parameter value],...`. In this example, the `<>` 'not equal to'
operator is URL-encoded in the request's query string (%3C%3E): GET
https://www.googleapis.com/admin/reports/v1/usage/gplus_communities/all/dates/2017-12-01
?parameters=gplus:community_name,gplus:num_total_members =gplus:num_total_members%3C%3E0 The
relational operators include: - `==` - 'equal to'. - `<>` - 'not equal to'. It is URL-encoded
(%3C%3E). - `<` - 'less than'. It is URL-encoded (%3C). - `<=` - 'less than or equal to'. It is
URL-encoded (%3C=). - `>` - 'greater than'. It is URL-encoded (%3E). - `>=` - 'greater than or
equal to'. It is URL-encoded (%3E=). Filters can only be applied to numeric parameters.
*/
public java.lang.String getFilters() {
return filters;
}
/**
* The `filters` query string is a comma-separated list of an application's event parameters
* where the parameter's value is manipulated by a relational operator. The `filters` query
* string includes the name of the application whose usage is returned in the report. The
* application values for the Entities usage report include `accounts`, `docs`, and `gmail`.
* Filters are in the form `[application name]:parameter name[parameter value],...`. In this
* example, the `<>` 'not equal to' operator is URL-encoded in the request's query string
* (%3C%3E): GET
* https://www.googleapis.com/admin/reports/v1/usage/gplus_communities/all/dates/2017-12-01
* ?parameters=gplus:community_name,gplus:num_total_members =gplus:num_total_members%3C%3E0
* The relational operators include: - `==` - 'equal to'. - `<>` - 'not equal to'. It is URL-
* encoded (%3C%3E). - `<` - 'less than'. It is URL-encoded (%3C). - `<=` - 'less than or
* equal to'. It is URL-encoded (%3C=). - `>` - 'greater than'. It is URL-encoded (%3E). -
* `>=` - 'greater than or equal to'. It is URL-encoded (%3E=). Filters can only be applied to
* numeric parameters.
*/
public Get setFilters(java.lang.String filters) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(FILTERS_PATTERN.matcher(filters).matches(),
"Parameter filters must conform to the pattern " +
"(((gplus)):[a-z0-9_]+[<,<=,==,>=,>,!=][^,]+,)*(((gplus)):[a-z0-9_]+[<,<=,==,>=,>,!=][^,]+)");
}
this.filters = filters;
return this;
}
/**
* Determines how many activity records are shown on each response page. For example, if the
* request sets `maxResults=1` and the report has two activities, the report has two pages.
* The response's `nextPageToken` property has the token to the second page.
*/
@com.google.api.client.util.Key
private java.lang.Long maxResults;
/** Determines how many activity records are shown on each response page. For example, if the request
sets `maxResults=1` and the report has two activities, the report has two pages. The response's
`nextPageToken` property has the token to the second page. [default: 1000] [minimum: 1] [maximum:
1000]
*/
public java.lang.Long getMaxResults() {
return maxResults;
}
/**
* Determines how many activity records are shown on each response page. For example, if the
* request sets `maxResults=1` and the report has two activities, the report has two pages.
* The response's `nextPageToken` property has the token to the second page.
*/
public Get setMaxResults(java.lang.Long maxResults) {
this.maxResults = maxResults;
return this;
}
/**
* Token to specify next page. A report with multiple pages has a `nextPageToken` property in
* the response. In your follow-on request getting the next page of the report, enter the
* `nextPageToken` value in the `pageToken` query string.
*/
@com.google.api.client.util.Key
private java.lang.String pageToken;
/** Token to specify next page. A report with multiple pages has a `nextPageToken` property in the
response. In your follow-on request getting the next page of the report, enter the `nextPageToken`
value in the `pageToken` query string.
*/
public java.lang.String getPageToken() {
return pageToken;
}
/**
* Token to specify next page. A report with multiple pages has a `nextPageToken` property in
* the response. In your follow-on request getting the next page of the report, enter the
* `nextPageToken` value in the `pageToken` query string.
*/
public Get setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
/**
* The `parameters` query string is a comma-separated list of event parameters that refine a
* report's results. The parameter is associated with a specific application. The application
* values for the Entities usage report are only `gplus`. A `parameter` query string is in the
* CSV form of `[app_name1:param_name1], [app_name2:param_name2]...`. *Note:* The API doesn't
* accept multiple values of a parameter. If a particular parameter is supplied more than once
* in the API request, the API only accepts the last value of that request parameter. In
* addition, if an invalid request parameter is supplied in the API request, the API ignores
* that request parameter and returns the response corresponding to the remaining valid
* request parameters. An example of an invalid request parameter is one that does not belong
* to the application. If no parameters are requested, all parameters are returned.
*/
@com.google.api.client.util.Key
private java.lang.String parameters;
/** The `parameters` query string is a comma-separated list of event parameters that refine a report's
results. The parameter is associated with a specific application. The application values for the
Entities usage report are only `gplus`. A `parameter` query string is in the CSV form of
`[app_name1:param_name1], [app_name2:param_name2]...`. *Note:* The API doesn't accept multiple
values of a parameter. If a particular parameter is supplied more than once in the API request, the
API only accepts the last value of that request parameter. In addition, if an invalid request
parameter is supplied in the API request, the API ignores that request parameter and returns the
response corresponding to the remaining valid request parameters. An example of an invalid request
parameter is one that does not belong to the application. If no parameters are requested, all
parameters are returned.
*/
public java.lang.String getParameters() {
return parameters;
}
/**
* The `parameters` query string is a comma-separated list of event parameters that refine a
* report's results. The parameter is associated with a specific application. The application
* values for the Entities usage report are only `gplus`. A `parameter` query string is in the
* CSV form of `[app_name1:param_name1], [app_name2:param_name2]...`. *Note:* The API doesn't
* accept multiple values of a parameter. If a particular parameter is supplied more than once
* in the API request, the API only accepts the last value of that request parameter. In
* addition, if an invalid request parameter is supplied in the API request, the API ignores
* that request parameter and returns the response corresponding to the remaining valid
* request parameters. An example of an invalid request parameter is one that does not belong
* to the application. If no parameters are requested, all parameters are returned.
*/
public Get setParameters(java.lang.String parameters) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARAMETERS_PATTERN.matcher(parameters).matches(),
"Parameter parameters must conform to the pattern " +
"(((gplus)):[^,]+,)*(((gplus)):[^,]+)");
}
this.parameters = parameters;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the UserUsageReport collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Reports admin = new Reports(...);}
* {@code Reports.UserUsageReport.List request = admin.userUsageReport().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public UserUsageReport userUsageReport() {
return new UserUsageReport();
}
/**
* The "userUsageReport" collection of methods.
*/
public class UserUsageReport {
/**
* Retrieves a report which is a collection of properties and statistics for a set of users with the
* account. For more information, see the User Usage Report guide. For more information about the
* user report's parameters, see the Users Usage parameters reference guides.
*
* Create a request for the method "userUsageReport.get".
*
* This request holds the parameters needed by the admin server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param userKey Represents the profile ID or the user email for which the data should be filtered. Can be `all` for
* all information, or `userKey` for a user's unique Google Workspace profile ID or their
* primary email address. Must not be a deleted user. For a deleted user, call `users.list`
* in Directory API with `showDeleted=true`, then use the returned `ID` as the `userKey`.
* @param date Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-dd. We
* recommend you use your account's time zone for this.
* @return the request
*/
public Get get(java.lang.String userKey, java.lang.String date) throws java.io.IOException {
Get result = new Get(userKey, date);
initialize(result);
return result;
}
public class Get extends ReportsRequest<com.google.api.services.reports.model.UsageReports> {
private static final String REST_PATH = "admin/reports/v1/usage/users/{userKey}/dates/{date}";
private final java.util.regex.Pattern DATE_PATTERN =
java.util.regex.Pattern.compile("(\\d){4}-(\\d){2}-(\\d){2}");
private final java.util.regex.Pattern CUSTOMER_ID_PATTERN =
java.util.regex.Pattern.compile("C.+|my_customer");
private final java.util.regex.Pattern FILTERS_PATTERN =
java.util.regex.Pattern.compile("(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[a-z0-9_]+[<,<=,==,>=,>,!=][^,]+,)*(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[a-z0-9_]+[<,<=,==,>=,>,!=][^,]+)");
private final java.util.regex.Pattern GROUP_ID_FILTER_PATTERN =
java.util.regex.Pattern.compile("(id:[a-z0-9]+(,id:[a-z0-9]+)*)");
private final java.util.regex.Pattern ORG_UNIT_ID_PATTERN =
java.util.regex.Pattern.compile("(id:[a-z0-9]+)");
private final java.util.regex.Pattern PARAMETERS_PATTERN =
java.util.regex.Pattern.compile("(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[^,]+,)*(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[^,]+)");
/**
* Retrieves a report which is a collection of properties and statistics for a set of users with
* the account. For more information, see the User Usage Report guide. For more information about
* the user report's parameters, see the Users Usage parameters reference guides.
*
* Create a request for the method "userUsageReport.get".
*
* This request holds the parameters needed by the the admin server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link
* Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be
* called to initialize this instance immediately after invoking the constructor. </p>
*
* @param userKey Represents the profile ID or the user email for which the data should be filtered. Can be `all` for
* all information, or `userKey` for a user's unique Google Workspace profile ID or their
* primary email address. Must not be a deleted user. For a deleted user, call `users.list`
* in Directory API with `showDeleted=true`, then use the returned `ID` as the `userKey`.
* @param date Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-dd. We
* recommend you use your account's time zone for this.
* @since 1.13
*/
protected Get(java.lang.String userKey, java.lang.String date) {
super(Reports.this, "GET", REST_PATH, null, com.google.api.services.reports.model.UsageReports.class);
this.userKey = com.google.api.client.util.Preconditions.checkNotNull(userKey, "Required parameter userKey must be specified.");
this.date = com.google.api.client.util.Preconditions.checkNotNull(date, "Required parameter date must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(DATE_PATTERN.matcher(date).matches(),
"Parameter date must conform to the pattern " +
"(\\d){4}-(\\d){2}-(\\d){2}");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/**
* Represents the profile ID or the user email for which the data should be filtered. Can be
* `all` for all information, or `userKey` for a user's unique Google Workspace profile ID or
* their primary email address. Must not be a deleted user. For a deleted user, call
* `users.list` in Directory API with `showDeleted=true`, then use the returned `ID` as the
* `userKey`.
*/
@com.google.api.client.util.Key
private java.lang.String userKey;
/** Represents the profile ID or the user email for which the data should be filtered. Can be `all` for
all information, or `userKey` for a user's unique Google Workspace profile ID or their primary
email address. Must not be a deleted user. For a deleted user, call `users.list` in Directory API
with `showDeleted=true`, then use the returned `ID` as the `userKey`.
*/
public java.lang.String getUserKey() {
return userKey;
}
/**
* Represents the profile ID or the user email for which the data should be filtered. Can be
* `all` for all information, or `userKey` for a user's unique Google Workspace profile ID or
* their primary email address. Must not be a deleted user. For a deleted user, call
* `users.list` in Directory API with `showDeleted=true`, then use the returned `ID` as the
* `userKey`.
*/
public Get setUserKey(java.lang.String userKey) {
this.userKey = userKey;
return this;
}
/**
* Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-
* dd. We recommend you use your account's time zone for this.
*/
@com.google.api.client.util.Key
private java.lang.String date;
/** Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-dd. We
recommend you use your account's time zone for this.
*/
public java.lang.String getDate() {
return date;
}
/**
* Represents the date the usage occurred. The timestamp is in the ISO 8601 format, yyyy-mm-
* dd. We recommend you use your account's time zone for this.
*/
public Get setDate(java.lang.String date) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(DATE_PATTERN.matcher(date).matches(),
"Parameter date must conform to the pattern " +
"(\\d){4}-(\\d){2}-(\\d){2}");
}
this.date = date;
return this;
}
/** The unique ID of the customer to retrieve data for. */
@com.google.api.client.util.Key
private java.lang.String customerId;
/** The unique ID of the customer to retrieve data for.
*/
public java.lang.String getCustomerId() {
return customerId;
}
/** The unique ID of the customer to retrieve data for. */
public Get setCustomerId(java.lang.String customerId) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(CUSTOMER_ID_PATTERN.matcher(customerId).matches(),
"Parameter customerId must conform to the pattern " +
"C.+|my_customer");
}
this.customerId = customerId;
return this;
}
/**
* The `filters` query string is a comma-separated list of an application's event parameters
* where the parameter's value is manipulated by a relational operator. The `filters` query
* string includes the name of the application whose usage is returned in the report. The
* application values for the Users Usage Report include `accounts`, `docs`, and `gmail`.
* Filters are in the form `[application name]:parameter name[parameter value],...`. In this
* example, the `<>` 'not equal to' operator is URL-encoded in the request's query string
* (%3C%3E): GET https://www.googleapis.com/admin/reports/v1/usage/users/all/dates/2013-03-03
* ?parameters=accounts:last_login_time
* =accounts:last_login_time%3C%3E2010-10-28T10:26:35.000Z The relational operators include: -
* `==` - 'equal to'. - `<>` - 'not equal to'. It is URL-encoded (%3C%3E). - `<` - 'less
* than'. It is URL-encoded (%3C). - `<=` - 'less than or equal to'. It is URL-encoded (%3C=).
* - `>` - 'greater than'. It is URL-encoded (%3E). - `>=` - 'greater than or equal to'. It is
* URL-encoded (%3E=).
*/
@com.google.api.client.util.Key
private java.lang.String filters;
/** The `filters` query string is a comma-separated list of an application's event parameters where the
parameter's value is manipulated by a relational operator. The `filters` query string includes the
name of the application whose usage is returned in the report. The application values for the Users
Usage Report include `accounts`, `docs`, and `gmail`. Filters are in the form `[application
name]:parameter name[parameter value],...`. In this example, the `<>` 'not equal to' operator is
URL-encoded in the request's query string (%3C%3E): GET
https://www.googleapis.com/admin/reports/v1/usage/users/all/dates/2013-03-03
?parameters=accounts:last_login_time =accounts:last_login_time%3C%3E2010-10-28T10:26:35.000Z The
relational operators include: - `==` - 'equal to'. - `<>` - 'not equal to'. It is URL-encoded
(%3C%3E). - `<` - 'less than'. It is URL-encoded (%3C). - `<=` - 'less than or equal to'. It is
URL-encoded (%3C=). - `>` - 'greater than'. It is URL-encoded (%3E). - `>=` - 'greater than or
equal to'. It is URL-encoded (%3E=).
*/
public java.lang.String getFilters() {
return filters;
}
/**
* The `filters` query string is a comma-separated list of an application's event parameters
* where the parameter's value is manipulated by a relational operator. The `filters` query
* string includes the name of the application whose usage is returned in the report. The
* application values for the Users Usage Report include `accounts`, `docs`, and `gmail`.
* Filters are in the form `[application name]:parameter name[parameter value],...`. In this
* example, the `<>` 'not equal to' operator is URL-encoded in the request's query string
* (%3C%3E): GET https://www.googleapis.com/admin/reports/v1/usage/users/all/dates/2013-03-03
* ?parameters=accounts:last_login_time
* =accounts:last_login_time%3C%3E2010-10-28T10:26:35.000Z The relational operators include: -
* `==` - 'equal to'. - `<>` - 'not equal to'. It is URL-encoded (%3C%3E). - `<` - 'less
* than'. It is URL-encoded (%3C). - `<=` - 'less than or equal to'. It is URL-encoded (%3C=).
* - `>` - 'greater than'. It is URL-encoded (%3E). - `>=` - 'greater than or equal to'. It is
* URL-encoded (%3E=).
*/
public Get setFilters(java.lang.String filters) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(FILTERS_PATTERN.matcher(filters).matches(),
"Parameter filters must conform to the pattern " +
"(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[a-z0-9_]+[<,<=,==,>=,>,!=][^,]+,)*(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[a-z0-9_]+[<,<=,==,>=,>,!=][^,]+)");
}
this.filters = filters;
return this;
}
/**
* Comma separated group ids (obfuscated) on which user activities are filtered, i.e. the
* response will contain activities for only those users that are a part of at least one of
* the group ids mentioned here. Format: "id:abc123,id:xyz456"
*/
@com.google.api.client.util.Key
private java.lang.String groupIdFilter;
/** Comma separated group ids (obfuscated) on which user activities are filtered, i.e. the response
will contain activities for only those users that are a part of at least one of the group ids
mentioned here. Format: "id:abc123,id:xyz456"
*/
public java.lang.String getGroupIdFilter() {
return groupIdFilter;
}
/**
* Comma separated group ids (obfuscated) on which user activities are filtered, i.e. the
* response will contain activities for only those users that are a part of at least one of
* the group ids mentioned here. Format: "id:abc123,id:xyz456"
*/
public Get setGroupIdFilter(java.lang.String groupIdFilter) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(GROUP_ID_FILTER_PATTERN.matcher(groupIdFilter).matches(),
"Parameter groupIdFilter must conform to the pattern " +
"(id:[a-z0-9]+(,id:[a-z0-9]+)*)");
}
this.groupIdFilter = groupIdFilter;
return this;
}
/**
* Determines how many activity records are shown on each response page. For example, if the
* request sets `maxResults=1` and the report has two activities, the report has two pages.
* The response's `nextPageToken` property has the token to the second page. The `maxResults`
* query string is optional.
*/
@com.google.api.client.util.Key
private java.lang.Long maxResults;
/** Determines how many activity records are shown on each response page. For example, if the request
sets `maxResults=1` and the report has two activities, the report has two pages. The response's
`nextPageToken` property has the token to the second page. The `maxResults` query string is
optional. [default: 1000] [minimum: 1] [maximum: 1000]
*/
public java.lang.Long getMaxResults() {
return maxResults;
}
/**
* Determines how many activity records are shown on each response page. For example, if the
* request sets `maxResults=1` and the report has two activities, the report has two pages.
* The response's `nextPageToken` property has the token to the second page. The `maxResults`
* query string is optional.
*/
public Get setMaxResults(java.lang.Long maxResults) {
this.maxResults = maxResults;
return this;
}
/**
* ID of the organizational unit to report on. User activity will be shown only for users who
* belong to the specified organizational unit. Data before Dec 17, 2018 doesn't appear in the
* filtered results.
*/
@com.google.api.client.util.Key
private java.lang.String orgUnitID;
/** ID of the organizational unit to report on. User activity will be shown only for users who belong
to the specified organizational unit. Data before Dec 17, 2018 doesn't appear in the filtered
results.
*/
public java.lang.String getOrgUnitID() {
return orgUnitID;
}
/**
* ID of the organizational unit to report on. User activity will be shown only for users who
* belong to the specified organizational unit. Data before Dec 17, 2018 doesn't appear in the
* filtered results.
*/
public Get setOrgUnitID(java.lang.String orgUnitID) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(ORG_UNIT_ID_PATTERN.matcher(orgUnitID).matches(),
"Parameter orgUnitID must conform to the pattern " +
"(id:[a-z0-9]+)");
}
this.orgUnitID = orgUnitID;
return this;
}
/**
* Token to specify next page. A report with multiple pages has a `nextPageToken` property in
* the response. In your follow-on request getting the next page of the report, enter the
* `nextPageToken` value in the `pageToken` query string.
*/
@com.google.api.client.util.Key
private java.lang.String pageToken;
/** Token to specify next page. A report with multiple pages has a `nextPageToken` property in the
response. In your follow-on request getting the next page of the report, enter the `nextPageToken`
value in the `pageToken` query string.
*/
public java.lang.String getPageToken() {
return pageToken;
}
/**
* Token to specify next page. A report with multiple pages has a `nextPageToken` property in
* the response. In your follow-on request getting the next page of the report, enter the
* `nextPageToken` value in the `pageToken` query string.
*/
public Get setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
/**
* The `parameters` query string is a comma-separated list of event parameters that refine a
* report's results. The parameter is associated with a specific application. The application
* values for the Customers Usage report include `accounts`, `app_maker`, `apps_scripts`,
* `calendar`, `classroom`, `cros`, `docs`, `gmail`, `gplus`, `device_management`, `meet`, and
* `sites`. A `parameters` query string is in the CSV form of `app_name1:param_name1,
* app_name2:param_name2`. *Note:* The API doesn't accept multiple values of a parameter. If a
* particular parameter is supplied more than once in the API request, the API only accepts
* the last value of that request parameter. In addition, if an invalid request parameter is
* supplied in the API request, the API ignores that request parameter and returns the
* response corresponding to the remaining valid request parameters. An example of an invalid
* request parameter is one that does not belong to the application. If no parameters are
* requested, all parameters are returned.
*/
@com.google.api.client.util.Key
private java.lang.String parameters;
/** The `parameters` query string is a comma-separated list of event parameters that refine a report's
results. The parameter is associated with a specific application. The application values for the
Customers Usage report include `accounts`, `app_maker`, `apps_scripts`, `calendar`, `classroom`,
`cros`, `docs`, `gmail`, `gplus`, `device_management`, `meet`, and `sites`. A `parameters` query
string is in the CSV form of `app_name1:param_name1, app_name2:param_name2`. *Note:* The API
doesn't accept multiple values of a parameter. If a particular parameter is supplied more than once
in the API request, the API only accepts the last value of that request parameter. In addition, if
an invalid request parameter is supplied in the API request, the API ignores that request parameter
and returns the response corresponding to the remaining valid request parameters. An example of an
invalid request parameter is one that does not belong to the application. If no parameters are
requested, all parameters are returned.
*/
public java.lang.String getParameters() {
return parameters;
}
/**
* The `parameters` query string is a comma-separated list of event parameters that refine a
* report's results. The parameter is associated with a specific application. The application
* values for the Customers Usage report include `accounts`, `app_maker`, `apps_scripts`,
* `calendar`, `classroom`, `cros`, `docs`, `gmail`, `gplus`, `device_management`, `meet`, and
* `sites`. A `parameters` query string is in the CSV form of `app_name1:param_name1,
* app_name2:param_name2`. *Note:* The API doesn't accept multiple values of a parameter. If a
* particular parameter is supplied more than once in the API request, the API only accepts
* the last value of that request parameter. In addition, if an invalid request parameter is
* supplied in the API request, the API ignores that request parameter and returns the
* response corresponding to the remaining valid request parameters. An example of an invalid
* request parameter is one that does not belong to the application. If no parameters are
* requested, all parameters are returned.
*/
public Get setParameters(java.lang.String parameters) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARAMETERS_PATTERN.matcher(parameters).matches(),
"Parameter parameters must conform to the pattern " +
"(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[^,]+,)*(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[^,]+)");
}
this.parameters = parameters;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
/**
* Builder for {@link Reports}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
private static String chooseEndpoint(com.google.api.client.http.HttpTransport transport) {
// If the GOOGLE_API_USE_MTLS_ENDPOINT environment variable value is "always", use mTLS endpoint.
// If the env variable is "auto", use mTLS endpoint if and only if the transport is mTLS.
// Use the regular endpoint for all other cases.
String useMtlsEndpoint = System.getenv("GOOGLE_API_USE_MTLS_ENDPOINT");
useMtlsEndpoint = useMtlsEndpoint == null ? "auto" : useMtlsEndpoint;
if ("always".equals(useMtlsEndpoint) || ("auto".equals(useMtlsEndpoint) && transport != null && transport.isMtls())) {
return DEFAULT_MTLS_ROOT_URL;
}
return DEFAULT_ROOT_URL;
}
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
Builder.chooseEndpoint(transport),
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link Reports}. */
@Override
public Reports build() {
return new Reports(this);
}
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setBatchPath(String batchPath) {
return (Builder) super.setBatchPath(batchPath);
}
@Override
public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
@Override
public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) {
return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks);
}
@Override
public Builder setSuppressAllChecks(boolean suppressAllChecks) {
return (Builder) super.setSuppressAllChecks(suppressAllChecks);
}
/**
* Set the {@link ReportsRequestInitializer}.
*
* @since 1.12
*/
public Builder setReportsRequestInitializer(
ReportsRequestInitializer reportsRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(reportsRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
| [
"\"GOOGLE_API_USE_MTLS_ENDPOINT\""
]
| []
| [
"GOOGLE_API_USE_MTLS_ENDPOINT"
]
| [] | ["GOOGLE_API_USE_MTLS_ENDPOINT"] | java | 1 | 0 | |
module/lib/go-common/os.go | package common
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"os/signal"
"strings"
)
var (
GoPath = os.Getenv("GOPATH")
)
func TrapSignal(cb func()) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, os.Kill)
go func() {
for sig := range c {
fmt.Printf("captured %v, exiting...\n", sig)
if cb != nil {
cb()
}
os.Exit(1)
}
}()
select {}
}
func Exit(s string) {
fmt.Printf(s + "\n")
os.Exit(1)
}
func EnsureDir(dir string, mode os.FileMode) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err := os.MkdirAll(dir, mode)
if err != nil {
return fmt.Errorf("Could not create directory %v. %v", dir, err)
}
}
return nil
}
func FileExists(filePath string) bool {
_, err := os.Stat(filePath)
return !os.IsNotExist(err)
}
func ReadFile(filePath string) ([]byte, error) {
return ioutil.ReadFile(filePath)
}
func MustReadFile(filePath string) []byte {
fileBytes, err := ioutil.ReadFile(filePath)
if err != nil {
Exit(Fmt("MustReadFile failed: %v", err))
return nil
}
return fileBytes
}
func WriteFile(filePath string, contents []byte, mode os.FileMode) error {
err := ioutil.WriteFile(filePath, contents, mode)
if err != nil {
return err
}
// fmt.Printf("File written to %v.\n", filePath)
return nil
}
func MustWriteFile(filePath string, contents []byte, mode os.FileMode) {
err := WriteFile(filePath, contents, mode)
if err != nil {
Exit(Fmt("MustWriteFile failed: %v", err))
}
}
// Writes to newBytes to filePath.
// Guaranteed not to lose *both* oldBytes and newBytes,
// (assuming that the OS is perfect)
func WriteFileAtomic(filePath string, newBytes []byte, mode os.FileMode) error {
// If a file already exists there, copy to filePath+".bak" (overwrite anything)
if _, err := os.Stat(filePath); !os.IsNotExist(err) {
fileBytes, err := ioutil.ReadFile(filePath)
if err != nil {
return fmt.Errorf("Could not read file %v. %v", filePath, err)
}
err = ioutil.WriteFile(filePath+".bak", fileBytes, mode)
if err != nil {
return fmt.Errorf("Could not write file %v. %v", filePath+".bak", err)
}
}
// Write newBytes to filePath.new
err := ioutil.WriteFile(filePath+".new", newBytes, mode)
if err != nil {
return fmt.Errorf("Could not write file %v. %v", filePath+".new", err)
}
// Move filePath.new to filePath
err = os.Rename(filePath+".new", filePath)
return err
}
//--------------------------------------------------------------------------------
func Tempfile(prefix string) (*os.File, string) {
file, err := ioutil.TempFile("", prefix)
if err != nil {
PanicCrisis(err)
}
return file, file.Name()
}
func Tempdir(prefix string) (*os.File, string) {
tempDir := os.TempDir() + "/" + prefix + RandStr(12)
err := EnsureDir(tempDir, 0700)
if err != nil {
panic(Fmt("Error creating temp dir: %v", err))
}
dir, err := os.Open(tempDir)
if err != nil {
panic(Fmt("Error opening temp dir: %v", err))
}
return dir, tempDir
}
//--------------------------------------------------------------------------------
func Prompt(prompt string, defaultValue string) (string, error) {
fmt.Print(prompt)
reader := bufio.NewReader(os.Stdin)
line, err := reader.ReadString('\n')
if err != nil {
return defaultValue, err
} else {
line = strings.TrimSpace(line)
if line == "" {
return defaultValue, nil
}
return line, nil
}
}
| [
"\"GOPATH\""
]
| []
| [
"GOPATH"
]
| [] | ["GOPATH"] | go | 1 | 0 | |
test/iptables/iptables_test.go | // Copyright 2019 The gVisor 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 iptables
import (
"fmt"
"net"
"os"
"path"
"testing"
"time"
"flag"
"gvisor.dev/gvisor/pkg/log"
"gvisor.dev/gvisor/runsc/dockerutil"
"gvisor.dev/gvisor/runsc/testutil"
)
const timeout = 18 * time.Second
var image = flag.String("image", "bazel/test/iptables/runner:runner", "image to run tests in")
type result struct {
output string
err error
}
// singleTest runs a TestCase. Each test follows a pattern:
// - Create a container.
// - Get the container's IP.
// - Send the container our IP.
// - Start a new goroutine running the local action of the test.
// - Wait for both the container and local actions to finish.
//
// Container output is logged to $TEST_UNDECLARED_OUTPUTS_DIR if it exists, or
// to stderr.
func singleTest(test TestCase) error {
if _, ok := Tests[test.Name()]; !ok {
return fmt.Errorf("no test found with name %q. Has it been registered?", test.Name())
}
// Create and start the container.
cont := dockerutil.MakeDocker("gvisor-iptables")
defer cont.CleanUp()
resultChan := make(chan *result)
go func() {
output, err := cont.RunFg("--cap-add=NET_ADMIN", *image, "-name", test.Name())
logContainer(output, err)
resultChan <- &result{output, err}
}()
// Get the container IP.
ip, err := getIP(cont)
if err != nil {
return fmt.Errorf("failed to get container IP: %v", err)
}
// Give the container our IP.
if err := sendIP(ip); err != nil {
return fmt.Errorf("failed to send IP to container: %v", err)
}
// Run our side of the test.
errChan := make(chan error)
go func() {
errChan <- test.LocalAction(ip)
}()
// Wait for both the container and local tests to finish.
var res *result
to := time.After(timeout)
for localDone := false; res == nil || !localDone; {
select {
case res = <-resultChan:
log.Infof("Container finished.")
case err, localDone = <-errChan:
log.Infof("Local finished.")
if err != nil {
return fmt.Errorf("local test failed: %v", err)
}
case <-to:
return fmt.Errorf("timed out after %f seconds", timeout.Seconds())
}
}
return res.err
}
func getIP(cont dockerutil.Docker) (net.IP, error) {
// The container might not have started yet, so retry a few times.
var ipStr string
to := time.After(timeout)
for ipStr == "" {
ipStr, _ = cont.FindIP()
select {
case <-to:
return net.IP{}, fmt.Errorf("timed out getting IP after %f seconds", timeout.Seconds())
default:
time.Sleep(250 * time.Millisecond)
}
}
ip := net.ParseIP(ipStr)
if ip == nil {
return net.IP{}, fmt.Errorf("invalid IP: %q", ipStr)
}
log.Infof("Container has IP of %s", ipStr)
return ip, nil
}
func sendIP(ip net.IP) error {
contAddr := net.TCPAddr{
IP: ip,
Port: IPExchangePort,
}
var conn *net.TCPConn
// The container may not be listening when we first connect, so retry
// upon error.
cb := func() error {
c, err := net.DialTCP("tcp4", nil, &contAddr)
conn = c
return err
}
if err := testutil.Poll(cb, timeout); err != nil {
return fmt.Errorf("timed out waiting to send IP, most recent error: %v", err)
}
if _, err := conn.Write([]byte{0}); err != nil {
return fmt.Errorf("error writing to container: %v", err)
}
return nil
}
func logContainer(output string, err error) {
msg := fmt.Sprintf("Container error: %v\nContainer output:\n%v", err, output)
if artifactsDir := os.Getenv("TEST_UNDECLARED_OUTPUTS_DIR"); artifactsDir != "" {
fpath := path.Join(artifactsDir, "container.log")
if file, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE, 0644); err != nil {
log.Warningf("Failed to open log file %q: %v", fpath, err)
} else {
defer file.Close()
if _, err := file.Write([]byte(msg)); err == nil {
return
}
log.Warningf("Failed to write to log file %s: %v", fpath, err)
}
}
// We couldn't write to the output directory -- just log to stderr.
log.Infof(msg)
}
func TestFilterInputDropUDP(t *testing.T) {
if err := singleTest(FilterInputDropUDP{}); err != nil {
t.Fatal(err)
}
}
func TestFilterInputDropUDPPort(t *testing.T) {
if err := singleTest(FilterInputDropUDPPort{}); err != nil {
t.Fatal(err)
}
}
func TestFilterInputDropDifferentUDPPort(t *testing.T) {
if err := singleTest(FilterInputDropDifferentUDPPort{}); err != nil {
t.Fatal(err)
}
}
func TestFilterInputDropAll(t *testing.T) {
if err := singleTest(FilterInputDropAll{}); err != nil {
t.Fatal(err)
}
}
func TestNATRedirectUDPPort(t *testing.T) {
if err := singleTest(NATRedirectUDPPort{}); err != nil {
t.Fatal(err)
}
}
func TestNATDropUDP(t *testing.T) {
if err := singleTest(NATDropUDP{}); err != nil {
t.Fatal(err)
}
}
func TestFilterInputDropTCPDestPort(t *testing.T) {
if err := singleTest(FilterInputDropTCPDestPort{}); err != nil {
t.Fatal(err)
}
}
func TestFilterInputDropTCPSrcPort(t *testing.T) {
if err := singleTest(FilterInputDropTCPSrcPort{}); err != nil {
t.Fatal(err)
}
}
func TestFilterOutputDropTCPDestPort(t *testing.T) {
if err := singleTest(FilterOutputDropTCPDestPort{}); err != nil {
t.Fatal(err)
}
}
func TestFilterOutputDropTCPSrcPort(t *testing.T) {
if err := singleTest(FilterOutputDropTCPSrcPort{}); err != nil {
t.Fatal(err)
}
}
| [
"\"TEST_UNDECLARED_OUTPUTS_DIR\""
]
| []
| [
"TEST_UNDECLARED_OUTPUTS_DIR"
]
| [] | ["TEST_UNDECLARED_OUTPUTS_DIR"] | go | 1 | 0 | |
g2021516/feature/os/os01.go | package main
import (
"os"
"strings"
)
// https://coolshell.cn/articles/8489.html
// GO 语言简介(下)— 特性
func main() {
os.Setenv("WEB", "https://coolshell.cn") // 设置环境变量
println(os.Getenv("WEB")) // 读出来
for _, env := range os.Environ() { // 穷举环境变量
e := strings.Split(env, "=")
println(e[0], "=", e[1])
}
}
| [
"\"WEB\""
]
| []
| [
"WEB"
]
| [] | ["WEB"] | go | 1 | 0 | |
dbms/tests/external_models/catboost/test_apply_catboost_model/test.py | from helpers.server_with_models import ClickHouseServerWithCatboostModels
from helpers.generate import generate_uniform_string_column, generate_uniform_float_column, generate_uniform_int_column
from helpers.train import train_catboost_model
import os
import numpy as np
from pandas import DataFrame
PORT = int(os.environ.get('CLICKHOUSE_TESTS_PORT', '9000'))
CLICKHOUSE_TESTS_SERVER_BIN_PATH = os.environ.get('CLICKHOUSE_TESTS_SERVER_BIN_PATH', '/usr/bin/clickhouse')
def add_noise_to_target(target, seed, threshold=0.05):
col = generate_uniform_float_column(len(target), 0., 1., seed + 1) < threshold
return target * (1 - col) + (1 - target) * col
def check_predictions(test_name, target, pred_python, pred_ch, acc_threshold):
ch_class = pred_ch.astype(int)
python_class = pred_python.astype(int)
if not np.array_equal(ch_class, python_class):
raise Exception('Got different results:\npython:\n' + str(python_class) + '\nClickHouse:\n' + str(ch_class))
acc = 1 - np.sum(np.abs(ch_class - np.array(target))) / (len(target) + .0)
assert acc >= acc_threshold
print test_name, 'accuracy: {:.10f}'.format(acc)
def test_apply_float_features_only():
name = 'test_apply_float_features_only'
train_size = 10000
test_size = 10000
def gen_data(size, seed):
data = {
'a': generate_uniform_float_column(size, 0., 1., seed + 1),
'b': generate_uniform_float_column(size, 0., 1., seed + 2),
'c': generate_uniform_float_column(size, 0., 1., seed + 3)
}
return DataFrame.from_dict(data)
def get_target(df):
def target_filter(row):
return 1 if (row['a'] > .3 and row['b'] > .3) or (row['c'] < .4 and row['a'] * row['b'] > 0.1) else 0
return df.apply(target_filter, axis=1).as_matrix()
train_df = gen_data(train_size, 42)
test_df = gen_data(test_size, 43)
train_target = get_target(train_df)
test_target = get_target(test_df)
print
print 'train target', train_target
print 'test target', test_target
params = {
'iterations': 4,
'depth': 2,
'learning_rate': 1,
'loss_function': 'Logloss'
}
model = train_catboost_model(train_df, train_target, [], params)
pred_python = model.predict(test_df)
server = ClickHouseServerWithCatboostModels(name, CLICKHOUSE_TESTS_SERVER_BIN_PATH, PORT)
server.add_model(name, model)
with server:
pred_ch = (np.array(server.apply_model(name, test_df, [])) > 0).astype(int)
print 'python predictions', pred_python
print 'clickhouse predictions', pred_ch
check_predictions(name, test_target, pred_python, pred_ch, 0.9)
def test_apply_float_features_with_string_cat_features():
name = 'test_apply_float_features_with_string_cat_features'
train_size = 10000
test_size = 10000
def gen_data(size, seed):
data = {
'a': generate_uniform_float_column(size, 0., 1., seed + 1),
'b': generate_uniform_float_column(size, 0., 1., seed + 2),
'c': generate_uniform_string_column(size, ['a', 'b', 'c'], seed + 3),
'd': generate_uniform_string_column(size, ['e', 'f', 'g'], seed + 4)
}
return DataFrame.from_dict(data)
def get_target(df):
def target_filter(row):
return 1 if (row['a'] > .3 and row['b'] > .3 and row['c'] != 'a') \
or (row['a'] * row['b'] > 0.1 and row['c'] != 'b' and row['d'] != 'e') else 0
return df.apply(target_filter, axis=1).as_matrix()
train_df = gen_data(train_size, 42)
test_df = gen_data(test_size, 43)
train_target = get_target(train_df)
test_target = get_target(test_df)
print
print 'train target', train_target
print 'test target', test_target
params = {
'iterations': 6,
'depth': 2,
'learning_rate': 1,
'loss_function': 'Logloss'
}
model = train_catboost_model(train_df, train_target, ['c', 'd'], params)
pred_python = model.predict(test_df)
server = ClickHouseServerWithCatboostModels(name, CLICKHOUSE_TESTS_SERVER_BIN_PATH, PORT)
server.add_model(name, model)
with server:
pred_ch = (np.array(server.apply_model(name, test_df, [])) > 0).astype(int)
print 'python predictions', pred_python
print 'clickhouse predictions', pred_ch
check_predictions(name, test_target, pred_python, pred_ch, 0.9)
def test_apply_float_features_with_int_cat_features():
name = 'test_apply_float_features_with_int_cat_features'
train_size = 10000
test_size = 10000
def gen_data(size, seed):
data = {
'a': generate_uniform_float_column(size, 0., 1., seed + 1),
'b': generate_uniform_float_column(size, 0., 1., seed + 2),
'c': generate_uniform_int_column(size, 1, 4, seed + 3),
'd': generate_uniform_int_column(size, 1, 4, seed + 4)
}
return DataFrame.from_dict(data)
def get_target(df):
def target_filter(row):
return 1 if (row['a'] > .3 and row['b'] > .3 and row['c'] != 1) \
or (row['a'] * row['b'] > 0.1 and row['c'] != 2 and row['d'] != 3) else 0
return df.apply(target_filter, axis=1).as_matrix()
train_df = gen_data(train_size, 42)
test_df = gen_data(test_size, 43)
train_target = get_target(train_df)
test_target = get_target(test_df)
print
print 'train target', train_target
print 'test target', test_target
params = {
'iterations': 6,
'depth': 4,
'learning_rate': 1,
'loss_function': 'Logloss'
}
model = train_catboost_model(train_df, train_target, ['c', 'd'], params)
pred_python = model.predict(test_df)
server = ClickHouseServerWithCatboostModels(name, CLICKHOUSE_TESTS_SERVER_BIN_PATH, PORT)
server.add_model(name, model)
with server:
pred_ch = (np.array(server.apply_model(name, test_df, [])) > 0).astype(int)
print 'python predictions', pred_python
print 'clickhouse predictions', pred_ch
check_predictions(name, test_target, pred_python, pred_ch, 0.9)
def test_apply_float_features_with_mixed_cat_features():
name = 'test_apply_float_features_with_mixed_cat_features'
train_size = 10000
test_size = 10000
def gen_data(size, seed):
data = {
'a': generate_uniform_float_column(size, 0., 1., seed + 1),
'b': generate_uniform_float_column(size, 0., 1., seed + 2),
'c': generate_uniform_string_column(size, ['a', 'b', 'c'], seed + 3),
'd': generate_uniform_int_column(size, 1, 4, seed + 4)
}
return DataFrame.from_dict(data)
def get_target(df):
def target_filter(row):
return 1 if (row['a'] > .3 and row['b'] > .3 and row['c'] != 'a') \
or (row['a'] * row['b'] > 0.1 and row['c'] != 'b' and row['d'] != 2) else 0
return df.apply(target_filter, axis=1).as_matrix()
train_df = gen_data(train_size, 42)
test_df = gen_data(test_size, 43)
train_target = get_target(train_df)
test_target = get_target(test_df)
print
print 'train target', train_target
print 'test target', test_target
params = {
'iterations': 6,
'depth': 4,
'learning_rate': 1,
'loss_function': 'Logloss'
}
model = train_catboost_model(train_df, train_target, ['c', 'd'], params)
pred_python = model.predict(test_df)
server = ClickHouseServerWithCatboostModels(name, CLICKHOUSE_TESTS_SERVER_BIN_PATH, PORT)
server.add_model(name, model)
with server:
pred_ch = (np.array(server.apply_model(name, test_df, [])) > 0).astype(int)
print 'python predictions', pred_python
print 'clickhouse predictions', pred_ch
check_predictions(name, test_target, pred_python, pred_ch, 0.9)
| []
| []
| [
"CLICKHOUSE_TESTS_SERVER_BIN_PATH",
"CLICKHOUSE_TESTS_PORT"
]
| [] | ["CLICKHOUSE_TESTS_SERVER_BIN_PATH", "CLICKHOUSE_TESTS_PORT"] | python | 2 | 0 | |
lib/dispatchcloud/container/queue_test.go | // Copyright (C) The Arvados Authors. All rights reserved.
//
// SPDX-License-Identifier: AGPL-3.0
package container
import (
"errors"
"os"
"sync"
"testing"
"time"
"git.curoverse.com/arvados.git/sdk/go/arvados"
"git.curoverse.com/arvados.git/sdk/go/arvadostest"
"github.com/sirupsen/logrus"
check "gopkg.in/check.v1"
)
// Gocheck boilerplate
func Test(t *testing.T) {
check.TestingT(t)
}
var _ = check.Suite(&IntegrationSuite{})
func logger() logrus.FieldLogger {
logger := logrus.StandardLogger()
if os.Getenv("ARVADOS_DEBUG") != "" {
logger.SetLevel(logrus.DebugLevel)
}
return logger
}
type IntegrationSuite struct{}
func (suite *IntegrationSuite) TearDownTest(c *check.C) {
err := arvados.NewClientFromEnv().RequestAndDecode(nil, "POST", "database/reset", nil, nil)
c.Check(err, check.IsNil)
}
func (suite *IntegrationSuite) TestGetLockUnlockCancel(c *check.C) {
typeChooser := func(ctr *arvados.Container) (arvados.InstanceType, error) {
return arvados.InstanceType{Name: "testType"}, nil
}
client := arvados.NewClientFromEnv()
cq := NewQueue(logger(), nil, typeChooser, client)
err := cq.Update()
c.Check(err, check.IsNil)
ents, threshold := cq.Entries()
c.Check(len(ents), check.Not(check.Equals), 0)
c.Check(time.Since(threshold) < time.Minute, check.Equals, true)
c.Check(time.Since(threshold) > 0, check.Equals, true)
_, ok := ents[arvadostest.QueuedContainerUUID]
c.Check(ok, check.Equals, true)
var wg sync.WaitGroup
for uuid, ent := range ents {
c.Check(ent.Container.UUID, check.Equals, uuid)
c.Check(ent.InstanceType.Name, check.Equals, "testType")
c.Check(ent.Container.State, check.Equals, arvados.ContainerStateQueued)
c.Check(ent.Container.Priority > 0, check.Equals, true)
ctr, ok := cq.Get(uuid)
c.Check(ok, check.Equals, true)
c.Check(ctr.UUID, check.Equals, uuid)
wg.Add(1)
go func() {
defer wg.Done()
err := cq.Unlock(uuid)
c.Check(err, check.NotNil)
c.Check(err, check.ErrorMatches, ".*cannot unlock when Queued.*")
err = cq.Lock(uuid)
c.Check(err, check.IsNil)
ctr, ok := cq.Get(uuid)
c.Check(ok, check.Equals, true)
c.Check(ctr.State, check.Equals, arvados.ContainerStateLocked)
err = cq.Lock(uuid)
c.Check(err, check.NotNil)
err = cq.Unlock(uuid)
c.Check(err, check.IsNil)
ctr, ok = cq.Get(uuid)
c.Check(ok, check.Equals, true)
c.Check(ctr.State, check.Equals, arvados.ContainerStateQueued)
err = cq.Unlock(uuid)
c.Check(err, check.NotNil)
err = cq.Cancel(uuid)
c.Check(err, check.IsNil)
ctr, ok = cq.Get(uuid)
c.Check(ok, check.Equals, true)
c.Check(ctr.State, check.Equals, arvados.ContainerStateCancelled)
err = cq.Lock(uuid)
c.Check(err, check.NotNil)
}()
}
wg.Wait()
}
func (suite *IntegrationSuite) TestCancelIfNoInstanceType(c *check.C) {
errorTypeChooser := func(ctr *arvados.Container) (arvados.InstanceType, error) {
return arvados.InstanceType{}, errors.New("no suitable instance type")
}
client := arvados.NewClientFromEnv()
cq := NewQueue(logger(), nil, errorTypeChooser, client)
var ctr arvados.Container
err := client.RequestAndDecode(&ctr, "GET", "arvados/v1/containers/"+arvadostest.QueuedContainerUUID, nil, nil)
c.Check(err, check.IsNil)
c.Check(ctr.State, check.Equals, arvados.ContainerStateQueued)
cq.Update()
// Wait for the cancel operation to take effect. Container
// will have state=Cancelled or just disappear from the queue.
suite.waitfor(c, time.Second, func() bool {
err := client.RequestAndDecode(&ctr, "GET", "arvados/v1/containers/"+arvadostest.QueuedContainerUUID, nil, nil)
return err == nil && ctr.State == arvados.ContainerStateCancelled
})
c.Check(ctr.RuntimeStatus["error"], check.Equals, `no suitable instance type`)
}
func (suite *IntegrationSuite) waitfor(c *check.C, timeout time.Duration, fn func() bool) {
defer func() {
c.Check(fn(), check.Equals, true)
}()
deadline := time.Now().Add(timeout)
for !fn() && time.Now().Before(deadline) {
time.Sleep(timeout / 1000)
}
}
| [
"\"ARVADOS_DEBUG\""
]
| []
| [
"ARVADOS_DEBUG"
]
| [] | ["ARVADOS_DEBUG"] | go | 1 | 0 | |
cmd/emp/util.go | package main
import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/chzyer/readline"
"github.com/mgutz/ansi"
"github.com/remind101/empire/cmd/emp/hkclient"
"github.com/getfiit/empire/pkg/heroku"
)
var nrc *hkclient.NetRc
func hkHome() string {
return filepath.Join(hkclient.HomePath(), ".hk")
}
func netrcPath() string {
if s := os.Getenv("NETRC_PATH"); s != "" {
return s
}
return filepath.Join(hkclient.HomePath(), netrcFilename)
}
func loadNetrc() {
var err error
if nrc == nil {
if nrc, err = hkclient.LoadNetRc(); err != nil {
if os.IsNotExist(err) {
nrc = &hkclient.NetRc{}
return
}
printFatal("loading netrc: " + err.Error())
}
}
}
func getCreds(u string) (user, pass string) {
loadNetrc()
if nrc == nil {
return "", ""
}
apiURL, err := url.Parse(u)
if err != nil {
printFatal("invalid API URL: %s", err)
}
user, pass, err = nrc.GetCreds(apiURL)
if err != nil {
printError(err.Error())
}
return user, pass
}
func saveCreds(host, user, pass string) error {
loadNetrc()
m := nrc.FindMachine(host)
if m == nil || m.IsDefault() {
m = nrc.NewMachine(host, user, pass, "")
}
m.UpdateLogin(user)
m.UpdatePassword(pass)
body, err := nrc.MarshalText()
if err != nil {
return err
}
return ioutil.WriteFile(netrcPath(), body, 0600)
}
func removeCreds(host string) error {
loadNetrc()
nrc.RemoveMachine(host)
body, err := nrc.MarshalText()
if err != nil {
return err
}
return ioutil.WriteFile(netrcPath(), body, 0600)
}
// exists returns whether the given file or directory exists or not
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func must(err error) {
if err != nil {
if herror, ok := err.(heroku.Error); ok {
switch herror.Id {
case "two_factor":
printError(err.Error() + " Authorize with `emp authorize`.")
os.Exit(79)
case "unauthorized":
printFatal(err.Error() + " Log in with `emp login`.")
}
}
printFatal(err.Error())
}
}
func printError(message string, args ...interface{}) {
log.Println(colorizeMessage("red", "error:", message, args...))
}
func printFatal(message string, args ...interface{}) {
log.Fatal(colorizeMessage("red", "error:", message, args...))
}
func printWarning(message string, args ...interface{}) {
log.Println(colorizeMessage("yellow", "warning:", message, args...))
}
func mustConfirm(warning, desired string) {
if isTerminalIn {
printWarning(warning)
fmt.Printf("> ")
}
var confirm string
if _, err := fmt.Scanln(&confirm); err != nil {
printFatal(err.Error())
}
if confirm != desired {
printFatal("Confirmation did not match %q.", desired)
}
}
func askForMessage() (string, error) {
if !isTerminalIn {
return "", errors.New("Can't ask for message")
}
fmt.Println("A commit message is required, enter one below:")
reader, err := readline.New("> ")
if err != nil {
return "", err
}
message, err := reader.Readline()
return strings.Trim(message, " \n"), err
}
func colorizeMessage(color, prefix, message string, args ...interface{}) string {
prefResult := ""
if prefix != "" {
prefResult = ansi.Color(prefix, color+"+b") + " " + ansi.ColorCode("reset")
}
return prefResult + ansi.Color(fmt.Sprintf(message, args...), color) + ansi.ColorCode("reset")
}
func listRec(w io.Writer, a ...interface{}) {
for i, x := range a {
fmt.Fprint(w, x)
if i+1 < len(a) {
w.Write([]byte{'\t'})
} else {
w.Write([]byte{'\n'})
}
}
}
type prettyTime struct {
time.Time
}
func (s prettyTime) String() string {
if time.Now().Sub(s.Time) < 12*30*24*time.Hour {
return s.Local().Format("Jan _2 15:04")
}
return s.Local().Format("Jan _2 2006")
}
type prettyDuration struct {
time.Duration
}
func (a prettyDuration) String() string {
switch d := a.Duration; {
case d > 2*24*time.Hour:
return a.Unit(24*time.Hour, "d")
case d > 2*time.Hour:
return a.Unit(time.Hour, "h")
case d > 2*time.Minute:
return a.Unit(time.Minute, "m")
}
return a.Unit(time.Second, "s")
}
func (a prettyDuration) Unit(u time.Duration, s string) string {
return fmt.Sprintf("%2d", roundDur(a.Duration, u)) + s
}
func roundDur(d, k time.Duration) int {
return int((d + k/2 - 1) / k)
}
func abbrev(s string, n int) string {
if len(s) > n {
return s[:n-1] + "…"
}
return s
}
func ensurePrefix(val, prefix string) string {
if !strings.HasPrefix(val, prefix) {
return prefix + val
}
return val
}
func ensureSuffix(val, suffix string) string {
if !strings.HasSuffix(val, suffix) {
return val + suffix
}
return val
}
func openURL(url string) error {
var command string
var args []string
switch runtime.GOOS {
case "darwin":
command = "open"
args = []string{command, url}
case "windows":
command = "cmd"
args = []string{"/c", "start " + strings.Replace(url, "&", "^&", -1)}
default:
if _, err := exec.LookPath("xdg-open"); err != nil {
log.Println("xdg-open is required to open web pages on " + runtime.GOOS)
os.Exit(2)
}
command = "xdg-open"
args = []string{command, url}
}
return runCommand(command, args, os.Environ())
}
func runCommand(command string, args, env []string) error {
if runtime.GOOS != "windows" {
p, err := exec.LookPath(command)
if err != nil {
log.Printf("Error finding path to %q: %s\n", command, err)
os.Exit(2)
}
command = p
}
return sysExec(command, args, env)
}
func stringsIndex(s []string, item string) int {
for i := range s {
if s[i] == item {
return i
}
}
return -1
}
func retryMessageRequired(retry func(), cleanup func()) {
if r := recover(); r != nil {
e := r.(heroku.Error)
if e.Id == "message_required" {
message, err := askForMessage()
if message == "" || err != nil {
printFatal("A message is required for this action, please run again with '-m'.")
}
flagMessage = message
retry()
}
}
if cleanup != nil {
cleanup()
}
}
func maybeMessage(action func(cmd *Command, args []string)) func(cmd *Command, args []string) {
return func(cmd *Command, args []string) {
retry := func() {
action(cmd, args)
}
defer retryMessageRequired(retry, nil)
action(cmd, args)
}
}
| [
"\"NETRC_PATH\""
]
| []
| [
"NETRC_PATH"
]
| [] | ["NETRC_PATH"] | go | 1 | 0 | |
.github/cyd.py | import requests
import os
import time
base_url = 'https://redtest.ca/api/'
response = requests.post(f'{base_url}users/login/', data={'username': os.getenv('CYDERIAN_USERNAME'), 'password': os.getenv('CYDERIAN_PASSWORD')})
access = response.json()['access']
headers = {'Authorization': f'Bearer {access}'}
print(access)
response = requests.get(f'{base_url}users/self', headers=headers)
user_id = response.json()['id']
print(user_id)
response = requests.post(f'{base_url}users/{user_id}/git/', data={'repo': os.getenv('REPO'),
'commit': os.getenv('GITHUB_SHA')},headers=headers)
analysis_id = response.json()['analysis']
while True:
response = requests.get(f'{base_url}users/{user_id}/analyses/{analysis_id}', headers=headers)
data = response.json()
if data['total_crashes'] > 0:
response = requests.get(f'{base_url}analyses/{analysis_id}/crashes', headers=headers)
for crash in response.json():
print(f"Crash Stack Trace: {crash['stackTrace']}")
print(f'Analysis Page: https://redtest.ca/{os.getenv("GITHUB_REPOSITORY").split("/")[-1]}/{analysis_id}/report')
exit(1)
if data['status'] == 'T':
exit(0)
time.sleep(3)
| []
| []
| [
"REPO",
"CYDERIAN_PASSWORD",
"CYDERIAN_USERNAME",
"GITHUB_REPOSITORY",
"GITHUB_SHA"
]
| [] | ["REPO", "CYDERIAN_PASSWORD", "CYDERIAN_USERNAME", "GITHUB_REPOSITORY", "GITHUB_SHA"] | python | 5 | 0 | |
tests/unit/test_jarbas_tasks.py | import io
import os
import sys
from contextlib import contextmanager
import pytest
from mock import patch, Mock
import jarbas_tasks
from jarbas_tasks import main
basepath = os.path.dirname(os.path.dirname(__file__))
@contextmanager
def capture_print():
stdout = sys.stdout
out = sys.stdout = io.StringIO()
try:
yield lambda: out.getvalue()
finally:
sys.stdout = stdout
@contextmanager
def capture_exit():
ex = None
def result():
nonlocal ex
data = out()
if ex is not None:
data += '\n%s' % ex
return data
try:
with capture_print() as out:
yield result
except SystemExit as ex_:
ex = ex_
def with_dir(newdir):
"""
Common implementation to with_tasks and without_tasks
"""
curr_dir = os.getcwd()
try:
yield os.chdir(os.path.join(basepath, newdir))
finally:
os.chdir(curr_dir)
@pytest.yield_fixture
def with_tasks():
yield from with_dir('project_with_tasks')
@pytest.yield_fixture
def without_tasks():
yield from with_dir('project_without_tasks')
@pytest.fixture(params=[False, True])
def toggle_docker(request):
return request.param
@pytest.fixture(params=['run', 'bash'])
def task_name(request):
return request.param
def test_project_defines_author_and_version():
assert hasattr(jarbas_tasks, '__author__')
assert hasattr(jarbas_tasks, '__version__')
def test_recognize_tasks(without_tasks):
with capture_exit() as output:
main.main(['jarbas-tasks'])
assert output() == """
Usage: jarbas-tasks COMMAND
Execute a jarbas standard command or a task from tasks.py
Commands:
bash Start a bash shell
tasks List all available tasks
run Execute the "run" task or start a bash shell
jarbas-tasks reads all tasks in the tasks.py file and make
them available as sub-commands.
"""
def test_run_bash(without_tasks, toggle_docker, task_name):
mock = Mock()
if toggle_docker:
os.environ['RUNNING_ON_DOCKER'] = 'true'
else:
os.environ.pop('RUNNING_ON_DOCKER', None)
with capture_exit() as output:
with patch('jarbas_tasks.tasks._execvp', mock):
main.main(['jarbas-tasks', task_name])
assert mock.called
(cmd, args), kwargs = mock.call_args
assert cmd == 'bash'
assert args[0:2] == ['bash', '--rcfile']
if toggle_docker:
assert args[2].endswith(os.path.sep + 'docker-bashrc')
else:
assert args[2].endswith(os.path.sep + 'bashrc')
| []
| []
| [
"RUNNING_ON_DOCKER"
]
| [] | ["RUNNING_ON_DOCKER"] | python | 1 | 0 | |
examples/segmentscan/main.go | package main
import (
"encoding/json"
"fmt"
"os"
lytics "github.com/lytics/go-lytics"
)
func main() {
lyticsBanner()
apikey := os.Getenv("LIOKEY")
if apikey == "" {
fmt.Println("must have LIOKEY env set")
usageExit()
os.Exit(1)
}
if len(os.Args) < 2 {
usageExit()
}
// create the client
client := lytics.NewLytics(apikey, nil)
// create the scanner
scan := client.PageSegment(os.Args[1])
// handle processing the entities
for {
e := scan.Next()
if e == nil {
break
}
by, _ := json.MarshalIndent(e.Fields, "", " ")
fmt.Println(string(by))
}
fmt.Printf("*** COMPLETED SCAN: Loaded %d total entities\n\n", scan.Total)
}
func lyticsBanner() {
fmt.Printf(`
__ __ _
/ / __ __/ /_(_)_________
/ / / / / / __/ / ___/ ___/
/ /___/ /_/ / /_/ / /__(__ )
/_____/\__, /\__/_/\___/____/
/____/
`)
}
func usageExit() {
fmt.Printf(`
************** Page Segment of Users HELP **************
export LIOKEY="mykey"
# change directory to this segment scan
cd segmentscan
# build this example tool
go build
segmentscan segment_id
`)
os.Exit(1)
}
| [
"\"LIOKEY\""
]
| []
| [
"LIOKEY"
]
| [] | ["LIOKEY"] | go | 1 | 0 | |
kafka.go | package kafka
import (
"bytes"
"fmt"
"log"
"os"
"strconv"
"strings"
"text/template"
"time"
"github.com/gliderlabs/logspout/router"
"gopkg.in/Shopify/sarama.v1"
)
func init() {
router.AdapterFactories.Register(NewKafkaAdapter, "kafka")
}
type KafkaAdapter struct {
route *router.Route
brokers []string
topic string
producer sarama.AsyncProducer
tmpl *template.Template
}
func NewKafkaAdapter(route *router.Route) (router.LogAdapter, error) {
brokers := readBrokers(route.Address)
if len(brokers) == 0 {
return nil, errorf("The Kafka broker host:port is missing. Did you specify it as a route address?")
}
topic := readTopic(route.Address, route.Options)
if topic == "" {
return nil, errorf("The Kafka topic is missing. Did you specify it as a route option?")
}
var err error
var tmpl *template.Template
if text := os.Getenv("KAFKA_TEMPLATE"); text != "" {
tmpl, err = template.New("kafka").Parse(text)
if err != nil {
return nil, errorf("Couldn't parse Kafka message template. %v", err)
}
}
if os.Getenv("DEBUG") != "" {
log.Printf("Starting Kafka producer for address: %s, topic: %s.\n", brokers, topic)
}
var retries int
retries, err = strconv.Atoi(os.Getenv("KAFKA_CONNECT_RETRIES"))
if err != nil {
retries = 3
}
var producer sarama.AsyncProducer
for i := 0; i < retries; i++ {
producer, err = sarama.NewAsyncProducer(brokers, newConfig())
if err != nil {
if os.Getenv("DEBUG") != "" {
log.Println("Couldn't create Kafka producer. Retrying...", err)
}
if i == retries-1 {
return nil, errorf("Couldn't create Kafka producer. %v", err)
}
} else {
time.Sleep(1 * time.Second)
}
}
return &KafkaAdapter{
route: route,
brokers: brokers,
topic: topic,
producer: producer,
tmpl: tmpl,
}, nil
}
func (a *KafkaAdapter) Stream(logstream chan *router.Message) {
defer a.producer.Close()
for rm := range logstream {
message, err := a.formatMessage(rm)
if err != nil {
log.Println("kafka:", err)
a.route.Close()
break
}
a.producer.Input() <- message
}
}
func newConfig() *sarama.Config {
config := sarama.NewConfig()
config.ClientID = "logspout"
config.Producer.Return.Errors = false
config.Producer.Return.Successes = false
config.Producer.Flush.Frequency = 1 * time.Second
config.Producer.RequiredAcks = sarama.WaitForLocal
if opt := os.Getenv("KAFKA_COMPRESSION_CODEC"); opt != "" {
switch opt {
case "gzip":
config.Producer.Compression = sarama.CompressionGZIP
case "snappy":
config.Producer.Compression = sarama.CompressionSnappy
}
}
return config
}
func (a *KafkaAdapter) formatMessage(message *router.Message) (*sarama.ProducerMessage, error) {
var encoder sarama.Encoder
if a.tmpl != nil {
var w bytes.Buffer
if err := a.tmpl.Execute(&w, message); err != nil {
return nil, err
}
encoder = sarama.ByteEncoder(w.Bytes())
} else {
encoder = sarama.StringEncoder(message.Data)
}
return &sarama.ProducerMessage{
Topic: a.topic,
Value: encoder,
}, nil
}
func readBrokers(address string) []string {
if strings.Contains(address, "/") {
slash := strings.Index(address, "/")
address = address[:slash]
}
return strings.Split(address, ",")
}
func readTopic(address string, options map[string]string) string {
var topic string
if !strings.Contains(address, "/") {
topic = options["topic"]
} else {
slash := strings.Index(address, "/")
topic = address[slash+1:]
}
return topic
}
func errorf(format string, a ...interface{}) (err error) {
err = fmt.Errorf(format, a...)
if os.Getenv("DEBUG") != "" {
fmt.Println(err.Error())
}
return
}
| [
"\"KAFKA_TEMPLATE\"",
"\"DEBUG\"",
"\"KAFKA_CONNECT_RETRIES\"",
"\"DEBUG\"",
"\"KAFKA_COMPRESSION_CODEC\"",
"\"DEBUG\""
]
| []
| [
"KAFKA_TEMPLATE",
"KAFKA_CONNECT_RETRIES",
"KAFKA_COMPRESSION_CODEC",
"DEBUG"
]
| [] | ["KAFKA_TEMPLATE", "KAFKA_CONNECT_RETRIES", "KAFKA_COMPRESSION_CODEC", "DEBUG"] | go | 4 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.