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
Primer/Primer/asgi.py
""" ASGI config for Primer 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', 'Primer.settings') application = get_asgi_application()
[]
[]
[]
[]
[]
python
0
0
examples/deployment_plan.go
package main import ( "encoding/json" "fmt" "github.com/HewlettPackard/oneview-golang/i3s" "github.com/HewlettPackard/oneview-golang/ov" "github.com/HewlettPackard/oneview-golang/utils" "io/ioutil" "os" ) func main() { var ( clientOV *ov.OVClient i3sClient *i3s.I3SClient endpoint = os.Getenv("ONEVIEW_OV_ENDPOINT") i3sc_endpoint = os.Getenv("ONEVIEW_I3S_ENDPOINT") username = os.Getenv("ONEVIEW_OV_USER") password = os.Getenv("ONEVIEW_OV_PASSWORD") domain = os.Getenv("ONEVIEW_OV_DOMAIN") api_version = 1600 deployment_plan_name = "DemoDeploymentPlan" new_name = "RenamedDeploymentPlan" ) ovc := clientOV.NewOVClient( username, password, domain, endpoint, false, api_version, "*") ovc.RefreshLogin() i3sc := i3sClient.NewI3SClient(i3sc_endpoint, false, api_version, ovc.APIKey) customAttributes := new([]i3s.CustomAttribute) var ca1, ca2, ca3, ca4, ca5, ca6, ca7, ca8, ca9, ca10, ca11 i3s.CustomAttribute ca1.Constraints = "{\"options\":[\"English (United States)\",\"French (France)\",\"German (Germany)\",\"Japanese (Japan)\",\"Arabic " + "(Saudi Arabia)\",\"Chinese (PRC)\",\"Korean (Korea)\",\"Portuguese (Brazil)\",\"Russian (Russia)\"]}" ca1.Editable = true ca1.ID = "4509965b-fcdb-4ab2-9e20-1b80294ce94f" ca1.Name = "DisplayLanguage" ca1.Type = "option" ca1.Value = "English (United States)" ca1.Visible = true *customAttributes = append(*customAttributes, ca1) ca2.Constraints = "{\"options\":[\"English (United States)\",\"Arabic (101)\",\"Chinese (Traditional) - US Keyboard\",\"Japanese\",\"Korean\",\"United" + " Kingdom Extended\",\"United States - Dvorak\"]}" ca2.Editable = true ca2.ID = "c6ef28cc-0562-4c1e-8454-8e295f4df00d" ca2.Name = "KeyboardLayout" ca2.Type = "option" ca2.Value = "English (United States)" ca2.Visible = true *customAttributes = append(*customAttributes, ca2) ca3.Constraints = "{}" ca3.Editable = true ca3.ID = "e084491d-e476-4660-b231-b45a6cf2d42d" ca3.Name = "User1Password" ca3.Type = "string" ca3.Visible = true *customAttributes = append(*customAttributes, ca3) ca4.Constraints = "{}" ca4.Editable = true ca4.ID = "056c6f33-6509-4b1c-bb93-17685e631f4d" ca4.Name = "User1DisplayName" ca4.Type = "string" ca4.Visible = true *customAttributes = append(*customAttributes, ca4) ca5.Constraints = "{\"ipv4static\":true,\"ipv4dhcp\":true,\"ipv4disable\":false,\"parameters\":[\"mac\"]}" ca5.Editable = true ca5.ID = "8303c168-3e23-4025-9e63-2bddd644b461" ca5.Name = "ManagementNIC2" ca5.Type = "nic" ca5.Visible = true *customAttributes = append(*customAttributes, ca5) ca6.Constraints = "{\"options\":[\"Disallow\",\"Allow (Network Level Authentication)\",\"Allow\"]}" ca6.Editable = true ca6.ID = "ab0aa2b0-6b4f-433c-a6a6-abcb949ac286" ca6.Name = "RemoteDesktop" ca6.Type = "option" ca6.Value = "Disallow" ca6.Visible = true *customAttributes = append(*customAttributes, ca6) ca7.Constraints = "{}" ca7.Editable = true ca7.ID = "3c7c8229-1dc6-4656-857d-3392a26585ee" ca7.Name = "Hostname" ca7.Type = "string" ca7.Visible = true *customAttributes = append(*customAttributes, ca7) ca8.Constraints = "{\"ipv4static\":true,\"ipv4dhcp\":true,\"ipv4disable\":false,\"parameters\":[\"dhcp\",\"dns1\",\"dns2\",\"gateway\",\"ipaddress\",\"mac\",\"netmask\"]}" ca8.Editable = true ca8.ID = "ec1d95d0-690a-482b-8efd-53bec6e9bfce" ca8.Name = "ManagementNIC1" ca8.Type = "nic" ca8.Visible = true *customAttributes = append(*customAttributes, ca8) ca9.Constraints = "{\"maxlen\":\"20\"}" ca9.Editable = true ca9.Description = "Administrator Password" ca9.ID = "a881b1af-9034-4c69-a890-5e8c83a13d25" ca9.Name = "Password" ca9.Type = "password" ca9.Visible = true *customAttributes = append(*customAttributes, ca9) ca10.Constraints = "{\"options\":[\"GMT Standard Time\",\"Arabian Standard Time\",\"AUS Eastern Standard Time\",\"Central Standard Time\",\"China " + "Standard Time\",\"Eastern Standard Time\",\"India Standard Time\",\"Mountain Standard Time\",\"Singapore Standard " + "Time\",\"Tokyo Standard Time\"]}" ca10.Editable = true ca10.ID = "0d629c3e-23d0-49e1-950c-ecfcb9d5610d" ca10.Name = "TimeZone" ca10.Type = "option" ca10.Value = "GMT Standard Time" ca10.Visible = true *customAttributes = append(*customAttributes, ca10) ca11.Constraints = "{}" ca11.Editable = true ca11.ID = "1075adb8-5399-41fe-b6b3-71bea8836615" ca11.Name = "User1Name" ca11.Type = "string" ca11.Visible = true *customAttributes = append(*customAttributes, ca11) var deploymentPlan i3s.DeploymentPlan deploymentPlan.Name = deployment_plan_name deploymentPlan.Type = "OEDeploymentPlanV5" deploymentPlan.OEBuildPlanURI = "/rest/build-plans/1cfc2cc7-85c7-4db8-8213-854c0bfa3ff7" deploymentPlan.CustomAttributes = *customAttributes deploymentPlan.HPProvided = false fmt.Println("HPProvided:", deploymentPlan.HPProvided) file, _ := json.MarshalIndent(deploymentPlan, "", " ") ioutil.WriteFile("inut.json", file, 0644) fmt.Println("***********Creating Deployment Plan****************") err := i3sc.CreateDeploymentPlan(deploymentPlan) if err != nil { fmt.Println("Deployment Plan Creation Failed: ", err) } else { fmt.Println("Deployment Plan created successfully...") } sort := "name:desc" count := "5" fmt.Println("**************Get Deployment Plans sorted by name in descending order****************") dps, err := i3sc.GetDeploymentPlans(count, "", "", sort, "") if err != nil { fmt.Println("Error while getting deployment plans:", err) } else { for i := range dps.Members { fmt.Println(dps.Members[i].Name) } } fmt.Println("***********Getting Deployment Plan By Name****************") deployment_plan, err := i3sc.GetDeploymentPlanByName(deployment_plan_name) if err != nil { fmt.Println("Error in getting deployment plan ", err) } fmt.Println(deployment_plan) fmt.Println("***********Updating Deployment Plan****************") deployment_plan.Name = new_name deployment_plan.GoldenImageUri = "/rest/golden-images/7e709af9-5446-426e-9ca1-df06c63df2cd" deployment_plan.Description = utils.NewNstring("Testing Deployment plan") err = i3sc.UpdateDeploymentPlan(deployment_plan) if err != nil { //panic(err) fmt.Println("Error whilw updating Deployment Plan:", err) } else { fmt.Println("Deployment Plan has been updated with name: " + deploymentPlan.Name) } fmt.Println("***********Deleting Deployment Plan****************") err = i3sc.DeleteDeploymentPlan(new_name) if err != nil { panic(err) } else { fmt.Println("Deleteed Deployment Plan successfully...") } }
[ "\"ONEVIEW_OV_ENDPOINT\"", "\"ONEVIEW_I3S_ENDPOINT\"", "\"ONEVIEW_OV_USER\"", "\"ONEVIEW_OV_PASSWORD\"", "\"ONEVIEW_OV_DOMAIN\"" ]
[]
[ "ONEVIEW_OV_ENDPOINT", "ONEVIEW_OV_DOMAIN", "ONEVIEW_I3S_ENDPOINT", "ONEVIEW_OV_PASSWORD", "ONEVIEW_OV_USER" ]
[]
["ONEVIEW_OV_ENDPOINT", "ONEVIEW_OV_DOMAIN", "ONEVIEW_I3S_ENDPOINT", "ONEVIEW_OV_PASSWORD", "ONEVIEW_OV_USER"]
go
5
0
internal/orchestrationapi/orchestration.go
/******************************************************************************* * Copyright 2019-2020 Samsung Electronics 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 orchestrationapi provides orchestration functionalities to handle distributed service in multi-device environment package orchestrationapi import ( "errors" "os" "time" "github.com/lf-edge/edge-home-orchestration-go/internal/common/logmgr" "github.com/lf-edge/edge-home-orchestration-go/internal/common/mqtt" "github.com/lf-edge/edge-home-orchestration-go/internal/controller/cloudsyncmgr" "github.com/lf-edge/edge-home-orchestration-go/internal/controller/storagemgr" "github.com/lf-edge/edge-home-orchestration-go/internal/common/commandvalidator" "github.com/lf-edge/edge-home-orchestration-go/internal/common/networkhelper" "github.com/lf-edge/edge-home-orchestration-go/internal/common/requestervalidator" "github.com/lf-edge/edge-home-orchestration-go/internal/common/resourceutil" "github.com/lf-edge/edge-home-orchestration-go/internal/common/types/configuremgrtypes" "github.com/lf-edge/edge-home-orchestration-go/internal/controller/configuremgr" "github.com/lf-edge/edge-home-orchestration-go/internal/controller/discoverymgr" "github.com/lf-edge/edge-home-orchestration-go/internal/controller/scoringmgr" "github.com/lf-edge/edge-home-orchestration-go/internal/controller/securemgr/verifier" "github.com/lf-edge/edge-home-orchestration-go/internal/controller/servicemgr" "github.com/lf-edge/edge-home-orchestration-go/internal/controller/servicemgr/executor" "github.com/lf-edge/edge-home-orchestration-go/internal/controller/servicemgr/notification" "github.com/lf-edge/edge-home-orchestration-go/internal/restinterface/client" ) const logtag = "Orchestration" // Orche is the interface implemented by orchestration start function type Orche interface { Start(deviceIDPath string, platform string, executionType string) } // OrcheExternalAPI is the interface implemented by external REST API type OrcheExternalAPI interface { RequestService(serviceInfo ReqeustService) ResponseService verifier.Conf RequestCloudSync(message mqtt.Message, topic string, clientID string) string } // OrcheInternalAPI is the interface implemented by internal REST API type OrcheInternalAPI interface { configuremgr.Notifier ExecuteAppOnLocal(appInfo map[string]interface{}) HandleNotificationOnLocal(serviceID float64, status string) error GetScore(target string) (scoreValue float64, err error) GetOrchestrationInfo() (platform string, executionType string, serviceList []string, err error) HandleDeviceInfo(deviceID string, virtualAddr string, privateAddr string) GetScoreWithResource(target map[string]interface{}) (scoreValue float64, err error) GetResource(target string) (resourceMsg map[string]interface{}, err error) } var ( orcheIns *orcheImpl resourceMonitorImpl resourceutil.Monitor log = logmgr.GetInstance() ) func init() { orcheIns = new(orcheImpl) orcheIns.networkhelper = networkhelper.GetInstance() } // GetExternalAPI registers the orchestration external API func GetExternalAPI() (OrcheExternalAPI, error) { if !orcheIns.Ready { return orcheIns, errors.New("orchestration engine does not ready") } return orcheIns, nil } // GetInternalAPI registers the orchestration internal API func GetInternalAPI() (OrcheInternalAPI, error) { if !orcheIns.Ready { return orcheIns, errors.New("orchestration engine does not ready") } return orcheIns, nil } func getOrcheImple() *orcheImpl { return orcheIns } // OrchestrationBuilder has every interface to run orchestration type OrchestrationBuilder struct { isSetScoring bool scoringIns scoringmgr.Scoring isSetVerifierConf bool verifierIns verifier.Conf isSetDiscovery bool discoveryIns discoverymgr.Discovery isSetStorage bool storageIns storagemgr.Storage isSetCloudSync bool cloudsyncIns cloudsyncmgr.CloudSync isSetWatcher bool watcherIns configuremgr.Watcher isSetService bool serviceIns servicemgr.ServiceMgr isSetExecutor bool executorIns executor.ServiceExecutor isSetClient bool clientAPI client.Clienter } // SetVerifierConf registers the interface to setting up verifier configuration func (o *OrchestrationBuilder) SetVerifierConf(d verifier.Conf) { o.isSetVerifierConf = true o.verifierIns = d } // SetScoring registers the interface to handle resource scoring func (o *OrchestrationBuilder) SetScoring(s scoringmgr.Scoring) { o.isSetScoring = true o.scoringIns = s } // SetDiscovery registers the interface to handle orchestration discovery func (o *OrchestrationBuilder) SetDiscovery(d discoverymgr.Discovery) { o.isSetDiscovery = true o.discoveryIns = d } // SetStorage registers the interface to handle orchestration Storage func (o *OrchestrationBuilder) SetStorage(d storagemgr.Storage) { o.isSetStorage = true o.storageIns = d } // SetCloudSync registers the interface to handle orchestration CloudSync func (o *OrchestrationBuilder) SetCloudSync(d cloudsyncmgr.CloudSync) { o.isSetCloudSync = true o.cloudsyncIns = d } // SetWatcher registers the interface to check if service applications are installed func (o *OrchestrationBuilder) SetWatcher(w configuremgr.Watcher) { o.isSetWatcher = true o.watcherIns = w } // SetService registers the interface to handle executed service applications func (o *OrchestrationBuilder) SetService(s servicemgr.ServiceMgr) { o.isSetService = true o.serviceIns = s } // SetExecutor registers the interface to execute platform-specific service application func (o *OrchestrationBuilder) SetExecutor(e executor.ServiceExecutor) { o.isSetExecutor = true o.executorIns = e } // SetClient registers the interface to send request to remote device func (o *OrchestrationBuilder) SetClient(c client.Clienter) { o.isSetClient = true o.clientAPI = c } // Build registers every interface to run orchestration func (o OrchestrationBuilder) Build() Orche { if !o.isSetWatcher || !o.isSetDiscovery || !o.isSetScoring || !o.isSetService || !o.isSetExecutor || !o.isSetClient || !o.isSetVerifierConf || !o.isSetStorage { return nil } orcheIns.Ready = false orcheIns.scoringIns = o.scoringIns orcheIns.discoverIns = o.discoveryIns orcheIns.storageIns = o.storageIns orcheIns.cloudsyncIns = o.cloudsyncIns orcheIns.verifierIns = o.verifierIns orcheIns.watcher = o.watcherIns orcheIns.serviceIns = o.serviceIns orcheIns.clientAPI = o.clientAPI resourceMonitorImpl = resourceutil.GetMonitoringInstance() orcheIns.notificationIns = notification.GetInstance() orcheIns.serviceIns.SetLocalServiceExecutor(o.executorIns) orcheIns.discoverIns.SetRestResource() return orcheIns } // Start runs the orchestration service itself func (o *orcheImpl) Start(deviceIDPath string, platform string, executionType string) { resourceMonitorImpl.StartMonitoringResource() o.discoverIns.StartDiscovery(deviceIDPath, platform, executionType) o.storageIns.StartStorage("") cloudSyncState := os.Getenv("CLOUD_SYNC") o.cloudsyncIns.InitiateCloudSync(cloudSyncState) o.watcher.Watch(o) o.Ready = true time.Sleep(1000) } func (o orcheImpl) Notify(serviceInfo configuremgrtypes.ServiceInfo) { validator := commandvalidator.CommandValidator{} if err := validator.AddWhiteCommand(serviceInfo); err != nil { log.Println(logtag, "[Error]", err.Error()) return } requestervalidator.RequesterValidator{}. StoreRequesterInfo(serviceInfo.ServiceName, serviceInfo.AllowedRequester) if err := o.discoverIns.AddNewServiceName(serviceInfo.ServiceName); err != nil { log.Println(logtag, "[Error]", err.Error()) return } } // ExecuteAppOnLocal executes a service application on local device func (o orcheImpl) ExecuteAppOnLocal(appInfo map[string]interface{}) { o.serviceIns.ExecuteAppOnLocal(appInfo) } // HandleNotificationOnLocal handles notifications from local device after executing service application func (o orcheImpl) HandleNotificationOnLocal(serviceID float64, status string) error { return o.notificationIns.HandleNotificationOnLocal(serviceID, status) } // GetScore gets a resource score of local device for specific app func (o orcheImpl) GetScore(devID string) (scoreValue float64, err error) { return o.scoringIns.GetScore(devID) } // GetScoreWithResource gets a resource score of local device for specific app func (o orcheImpl) GetScoreWithResource(resource map[string]interface{}) (scoreValue float64, err error) { return o.scoringIns.GetScoreWithResource(resource) } // GetResource gets resource values of local device for running apps func (o orcheImpl) GetResource(devID string) (resourceMsg map[string]interface{}, err error) { return o.scoringIns.GetResource(devID) } // RequestVerifierConf setting up configuration of white list containers func (o orcheImpl) RequestVerifierConf(containerInfo verifier.RequestVerifierConf) verifier.ResponseVerifierConf { return o.verifierIns.RequestVerifierConf(containerInfo) } //GetOrchestrationInfo gets orchestration info of the device func (o orcheImpl) GetOrchestrationInfo() (platform string, executionType string, serviceList []string, err error) { return o.discoverIns.GetOrchestrationInfo() } //HandleDeviceInfo gets the peer's public and private Ip from relay server func (o orcheImpl) HandleDeviceInfo(deviceID string, virtualAddr string, privateAddr string) { o.discoverIns.AddDeviceInfo(deviceID, virtualAddr, privateAddr) }
[ "\"CLOUD_SYNC\"" ]
[]
[ "CLOUD_SYNC" ]
[]
["CLOUD_SYNC"]
go
1
0
cmd/apex/root/root.go
package root import ( "os" "github.com/apex/log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/lambda" "github.com/pkg/errors" "github.com/tj/cobra" "github.com/apex/apex/dryrun" "github.com/apex/apex/project" "github.com/apex/apex/utils" "fmt" ) // environment for project. var environment string var configFile string // chdir working directory. var chdir string // dryRun enabled. var dryRun bool // logLevel specified. var logLevel string // profile for AWS. var profile string // iamrole for AWS. var iamrole string // region for AWS. var region string // Session instance. var Session *session.Session // Project instance. var Project *project.Project // Config for AWS. var Config *aws.Config // Register `cmd`. func Register(cmd *cobra.Command) { Command.AddCommand(cmd) } // Command config. var Command = &cobra.Command{ Use: "apex", PersistentPreRunE: preRun, SilenceErrors: true, SilenceUsage: true, } // Initialize. func init() { f := Command.PersistentFlags() f.StringVarP(&environment, "env", "e", "", "Environment name") f.StringVarP(&chdir, "chdir", "C", "", "Working directory") f.BoolVarP(&dryRun, "dry-run", "D", false, "Perform a dry-run") f.StringVarP(&logLevel, "log-level", "l", "info", "Log severity level") f.StringVarP(&profile, "profile", "p", "", "AWS profile") f.StringVarP(&iamrole, "iamrole", "i", "", "AWS iamrole") f.StringVarP(&region, "region", "r", "", "AWS region") } // PreRunNoop noop for other commands. func PreRunNoop(c *cobra.Command, args []string) { // TODO: ew... better way to disable in cobra? } // preRun sets up global tasks used for most commands, some use PreRunNoop // to remove this default behaviour. func preRun(c *cobra.Command, args []string) error { err := Prepare(c, args) if err != nil { return err } return Project.Open() } // Prepare handles the global CLI flags and shared functionality without // the assumption that a Project has already been initialized. // // Precedence is currently: // // - flags such as --profile // - env vars such as AWS_PROFILE // - files such as ~/.aws/config // func Prepare(c *cobra.Command, args []string) error { if l, err := log.ParseLevel(logLevel); err == nil { log.SetLevel(l) } // config defaults Config = aws.NewConfig() if chdir != "" { if err := os.Chdir(chdir); err != nil { return err } } // profile from flag, config, env, "default" if profile == "" { profile, _ = utils.ProfileFromConfig(environment) if profile == "" { profile = os.Getenv("AWS_PROFILE") if profile == "" { profile = "default" } } } // the default SharedCredentialsProvider checks the env os.Setenv("AWS_PROFILE", profile) // region from flag, env, file if region == "" { region = os.Getenv("AWS_REGION") if region == "" { region, _ = utils.GetRegion(profile) } } if region != "" { Config = Config.WithRegion(region) } // environment from flag or env if environment == "" { environment = os.Getenv("APEX_ENVIRONMENT") } if environment == "" { configFile = "project.json" } else { configFile = fmt.Sprintf("project.%s.json", environment) } // iamrole from flag, env if iamrole == "" { iamrole = os.Getenv("AWS_ROLE") } if iamrole != "" { config, err := utils.AssumeRole(iamrole, Config) if err != nil { return errors.Wrap(err, "assuming role") } Config = config } Session = session.New(Config) Project = &project.Project{ Environment: environment, InfraEnvironment: environment, Log: log.Log, Path: ".", ConfigFile: configFile, } if dryRun { log.SetLevel(log.WarnLevel) Project.Service = dryrun.New(Session) Project.Concurrency = 1 } else { Project.Service = lambda.New(Session) } return nil }
[ "\"AWS_PROFILE\"", "\"AWS_REGION\"", "\"APEX_ENVIRONMENT\"", "\"AWS_ROLE\"" ]
[]
[ "AWS_PROFILE", "AWS_ROLE", "APEX_ENVIRONMENT", "AWS_REGION" ]
[]
["AWS_PROFILE", "AWS_ROLE", "APEX_ENVIRONMENT", "AWS_REGION"]
go
4
0
dl_tensorLayer/tl_vgg16.py
# -*- coding: utf-8 -*- """ VGG-16 for ImageNet. Introduction ---------------- VGG is a convolutional neural network model proposed by K. Simonyan and A. Zisserman from the University of Oxford in the paper “Very Deep Convolutional Networks for Large-Scale Image Recognition” . The model achieves 92.7% top-5 test accuracy in ImageNet, which is a dataset of over 14 million images belonging to 1000 classes. Download Pre-trained Model ---------------------------- - Model weights in this example - vgg16_weights.npz : http://www.cs.toronto.edu/~frossard/post/vgg16/ - Caffe VGG 16 model : https://gist.github.com/ksimonyan/211839e770f7b538e2d8#file-readme-md - Tool to convert the Caffe models to TensorFlow's : https://github.com/ethereon/caffe-tensorflow Note ------ - For simplified CNN layer see "Convolutional layer (Simplified)" in read the docs website. - When feeding other images to the model be sure to properly resize or crop them beforehand. Distorted images might end up being misclassified. One way of safely feeding images of multiple sizes is by doing center cropping, as shown in the following snippet: >>> image_h, image_w, _ = np.shape(img) >>> shorter_side = min(image_h, image_w) >>> scale = 224. / shorter_side >>> image_h, image_w = np.ceil([scale * image_h, scale * image_w]).astype('int32') >>> img = imresize(img, (image_h, image_w)) >>> crop_x = (image_w - 224) / 2 >>> crop_y = (image_h - 224) / 2 >>> img = img[crop_y:crop_y+224,crop_x:crop_x+224,:] """ import os import time import numpy as np import tensorflow as tf import tensorlayer as tl from scipy.misc import imread, imresize from tensorlayer.layers import * try: import sys sys.path.append("./") from utility.data.imagenet_classes import * except Exception as e: raise Exception( "{} / download the file from: https://github.com/zsdonghao/tensorlayer/tree/master/example/data".format(e)) os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" def conv_layers(net_in): """ professional CNN APIs """ with tf.name_scope('preprocess'): # Notice that we include a preprocessing layer that takes the RGB image # with pixels values in the range of 0-255 and subtracts the mean image # values (calculated over the entire ImageNet training set). mean = tf.constant([123.68, 116.779, 103.939], dtype=tf.float32, shape=[ 1, 1, 1, 3], name='img_mean') net_in.outputs = net_in.outputs - mean # conv1 network = Conv2dLayer( net_in, act=tf.nn.relu, shape=[3, 3, 3, 64], # 64 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv1_1') network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 64, 64], # 64 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv1_2') network = PoolLayer(network, ksize=[1, 2, 2, 1], strides=[ 1, 2, 2, 1], padding='SAME', pool=tf.nn.max_pool, name='pool1') # conv2 network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 64, 128], # 128 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv2_1') network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 128, 128], # 128 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv2_2') network = PoolLayer(network, ksize=[1, 2, 2, 1], strides=[ 1, 2, 2, 1], padding='SAME', pool=tf.nn.max_pool, name='pool2') # conv3 network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 128, 256], # 256 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv3_1') network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 256, 256], # 256 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv3_2') network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 256, 256], # 256 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv3_3') network = PoolLayer(network, ksize=[1, 2, 2, 1], strides=[ 1, 2, 2, 1], padding='SAME', pool=tf.nn.max_pool, name='pool3') # conv4 network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 256, 512], # 512 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv4_1') network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 512, 512], # 512 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv4_2') network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 512, 512], # 512 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv4_3') network = PoolLayer(network, ksize=[1, 2, 2, 1], strides=[ 1, 2, 2, 1], padding='SAME', pool=tf.nn.max_pool, name='pool4') # conv5 network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 512, 512], # 512 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv5_1') network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 512, 512], # 512 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv5_2') network = Conv2dLayer( network, act=tf.nn.relu, shape=[3, 3, 512, 512], # 512 features for each 3x3 patch strides=[1, 1, 1, 1], padding='SAME', name='conv5_3') network = PoolLayer(network, ksize=[1, 2, 2, 1], strides=[ 1, 2, 2, 1], padding='SAME', pool=tf.nn.max_pool, name='pool5') return network def conv_layers_simple_api(net_in): """ simplified CNN APIs 简化后的 """ with tf.name_scope('preprocess'): # Notice that we include a preprocessing layer that takes the RGB image # with pixels values in the range of 0-255 and subtracts the mean image # values (calculated over the entire ImageNet training set). mean = tf.constant([123.68, 116.779, 103.939], dtype=tf.float32, shape=[ 1, 1, 1, 3], name='img_mean') net_in.outputs = net_in.outputs - mean # conv1 network = Conv2d(net_in, n_filter=64, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv1_1') network = Conv2d(network, n_filter=64, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv1_2') network = MaxPool2d(network, filter_size=( 2, 2), strides=(2, 2), padding='SAME', name='pool1') # conv2 network = Conv2d(network, n_filter=128, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv2_1') network = Conv2d(network, n_filter=128, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv2_2') network = MaxPool2d(network, filter_size=( 2, 2), strides=(2, 2), padding='SAME', name='pool2') # conv3 network = Conv2d(network, n_filter=256, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv3_1') network = Conv2d(network, n_filter=256, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv3_2') network = Conv2d(network, n_filter=256, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv3_3') network = MaxPool2d(network, filter_size=( 2, 2), strides=(2, 2), padding='SAME', name='pool3') # conv4 network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv4_1') network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv4_2') network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv4_3') network = MaxPool2d(network, filter_size=( 2, 2), strides=(2, 2), padding='SAME', name='pool4') # conv5 network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv5_1') network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv5_2') network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=( 1, 1), act=tf.nn.relu, padding='SAME', name='conv5_3') network = MaxPool2d(network, filter_size=( 2, 2), strides=(2, 2), padding='SAME', name='pool5') return network def fc_layers(net): """ 全连接层 """ network = FlattenLayer(net, name='flatten') network = DenseLayer(network, n_units=4096, act=tf.nn.relu, name='fc1_relu') network = DenseLayer(network, n_units=4096, act=tf.nn.relu, name='fc2_relu') network = DenseLayer(network, n_units=1000, act=tf.identity, name='fc3_relu') return network def main(): sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, [None, 224, 224, 3]) # y_ = tf.placeholder(tf.int32, shape=[None, ], name='y_') net_in = InputLayer(x, name='input') # net_cnn = conv_layers(net_in) # professional CNN APIs net_cnn = conv_layers_simple_api(net_in) # simplified CNN APIs network = fc_layers(net_cnn) y = network.outputs probs = tf.nn.softmax(y) # y_op = tf.argmax(tf.nn.softmax(y), 1) # cost = tl.cost.cross_entropy(y, y_, name='cost') # correct_prediction = tf.equal(tf.cast(tf.argmax(y, 1), tf.float32), tf.cast(y_, tf.float32)) # acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tl.layers.initialize_global_variables(sess) # network.print_params() # network.print_layers() if not os.path.isfile("./models/vgg16_weights.npz"): print("Please download vgg16_weights.npz from : http://www.cs.toronto.edu/~frossard/post/vgg16/") exit() npz = np.load('./models/vgg16_weights.npz') params = [] for val in sorted(npz.items()): print("Loading %s" % str(val[1].shape)) params.append(val[1]) # 网络分配给定的参数。 tl.files.assign_params(sess, params, network) img1 = imread('./utility/data/laska.png',mode='RGB') # test data in github img1 = imresize(img1, (224, 224)) start_time = time.time() prob = sess.run(probs, feed_dict={x: [img1]})[0] print("End time : %.5ss" % (time.time() - start_time)) preds = (np.argsort(prob)[::-1])[0:5] for p in preds: print(class_names[p], prob[p]) if __name__ == '__main__': main()
[]
[]
[ "TF_CPP_MIN_LOG_LEVEL" ]
[]
["TF_CPP_MIN_LOG_LEVEL"]
python
1
0
api/client.go
package api import ( "crypto/tls" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/http" "net/http/httputil" "os" "strings" ) type errorResponse struct { Code int Description string } func newClient() *http.Client { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } return &http.Client{Transport: tr} } func NewAuthorizedRequest(method, path, accessToken string, body io.Reader) (request *http.Request, err error) { request, err = http.NewRequest(method, path, body) if err != nil { return nil, err } request.Header.Set("Authorization", accessToken) request.Header.Set("accept", "application/json") return } func PerformRequest(request *http.Request) (errorCode int, err error) { _, errorCode, err = doRequest(request) return } func PerformRequestAndParseResponse(request *http.Request, response interface{}) (errorCode int, err error) { rawResponse, errorCode, err := doRequest(request) if err != nil { return } jsonBytes, err := ioutil.ReadAll(rawResponse.Body) if err != nil { err = errors.New(fmt.Sprintf("Could not read response body: %s", err.Error())) return } err = json.Unmarshal(jsonBytes, &response) if err != nil { err = errors.New(fmt.Sprintf("Invalid JSON response from server: %s", err.Error())) } return } func doRequest(request *http.Request) (response *http.Response, errorCode int, err error) { client := newClient() if traceEnabled() { dumpedRequest, err := httputil.DumpRequest(request, true) if err != nil { fmt.Println("Error dumping request") } else { fmt.Printf("\n%s\n%s\n", "REQUEST:", string(dumpedRequest)) } } response, err = client.Do(request) if traceEnabled() { dumpedResponse, err := httputil.DumpResponse(response, true) if err != nil { fmt.Println("Error dumping response") } else { fmt.Printf("\n%s\n%s\n", "RESPONSE:", string(dumpedResponse)) } } if err != nil { err = errors.New(fmt.Sprintf("Error performing request: %s", err.Error())) return } if response.StatusCode > 299 { errorResponse := getErrorResponse(response) errorCode = errorResponse.Code message := fmt.Sprintf("Server error, status code: %d, error code: %d, message: %s", response.StatusCode, errorResponse.Code, errorResponse.Description) err = errors.New(message) } return } func traceEnabled() bool { traceEnv := strings.ToLower(os.Getenv("CF_TRACE")) return traceEnv == "true" || traceEnv == "yes" } func getErrorResponse(response *http.Response) (eR errorResponse) { jsonBytes, _ := ioutil.ReadAll(response.Body) response.Body.Close() eR = errorResponse{} _ = json.Unmarshal(jsonBytes, &eR) return }
[ "\"CF_TRACE\"" ]
[]
[ "CF_TRACE" ]
[]
["CF_TRACE"]
go
1
0
pkg/errors/errors.go
/* Copyright 2017 The Nuclio 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 errors provides an api similar to github.com/nuclio/nuclio/pkg/errors package errors // All error values returned from this package implement fmt.Formatter and can // be formatted by the fmt package. The following verbs are supported // // %s print the error // %+v extended format. Will print stack trace of errors import ( "fmt" "io" "os" "runtime" "strings" ) var ( // ShowLineInfo sets if we collect location information (file, line) // (getting location information makes creating error slower ~550ns vs 2ns) ShowLineInfo bool ) // Error implements error interface with call stack type Error struct { message string cause error fileName string lineNumber int } func init() { ShowLineInfo = len(os.Getenv("NUCLIO_NO_ERROR_LINE_INFO")) == 0 } // caller return the caller informatin (file, line) // Note this is sensitive to where it's called func caller() (string, int) { pcs := make([]uintptr, 1) // skip 3 levels to get to the caller n := runtime.Callers(3, pcs) if n == 0 { return "", 0 } pc := pcs[0] - 1 fn := runtime.FuncForPC(pc) if fn == nil { return "", 0 } return fn.FileLine(pc) } // New returns a new error func New(message string) error { err := &Error{message: message} if ShowLineInfo { err.fileName, err.lineNumber = caller() } return err } // Errorf returns a new Error func Errorf(format string, args ...interface{}) error { err := &Error{message: fmt.Sprintf(format, args...)} if ShowLineInfo { err.fileName, err.lineNumber = caller() } return err } // Wrap returns a new error with err as cause, if err is nil will return nil func Wrap(err error, message string) error { if err == nil { return nil } errObj := &Error{ message: message, cause: err, } if ShowLineInfo { errObj.fileName, errObj.lineNumber = caller() } return errObj } // Wrapf returns a new error with err as cause, if err is nil will return nil func Wrapf(err error, format string, args ...interface{}) error { if err == nil { return nil } message := fmt.Sprintf(format, args...) errObj := &Error{ message: message, cause: err, } if ShowLineInfo { errObj.fileName, errObj.lineNumber = caller() } return errObj } // Error is the string representation of the error func (err *Error) Error() string { return err.message } func asError(err error) *Error { errObj, ok := err.(*Error) if !ok { return nil } return errObj } // LineInfo info returns the location (file, line) where the error was created func (err *Error) LineInfo() (string, int) { return err.fileName, err.lineNumber } // reverse reverses a slice in place func reverse(slice []error) { for left, right := 0, len(slice)-1; left < right; left, right = left+1, right-1 { slice[left], slice[right] = slice[right], slice[left] } } // GetErrorStack return stack of messges (oldest on top) // if n == -1 returns the whole stack func GetErrorStack(err error, depth int) []error { errObj := asError(err) if errObj == nil { return []error{err} } var errors []error for errObj = asError(errObj.cause); errObj != nil; errObj = asError(errObj.cause) { errors = append(errors, errObj) } reverse(errors) if depth > 0 { if depth > len(errors) { depth = len(errors) } errors = errors[:depth] } return errors } // PrintErrorStack prints the error stack into out upto depth levels // If n == 1 then prints the whole stack func PrintErrorStack(out io.Writer, err error, depth int) { pathLen := 20 //stack := GetErrorStack(err, 3) stack := GetErrorStack(err, depth) fmt.Fprintf(out, "\nError - %s", stack[0].Error()) errObj := asError(stack[0]) if errObj != nil && errObj.lineNumber != 0 { fmt.Fprintf(out, "\n %s:%d\n", trimPath(errObj.fileName, pathLen), errObj.lineNumber) } fmt.Fprintf(out, "\nCall stack:") for _, e := range stack { errObj := asError(e) fmt.Fprintf(out, "\n%s", e.Error()) if errObj != nil && errObj.lineNumber != 0 { fmt.Fprintf(out, "\n %s:%d", trimPath(errObj.fileName, pathLen), errObj.lineNumber) } } out.Write([]byte{'\n'}) } // Cause is the cause of the error func Cause(err error) error { errObj := asError(err) if errObj == nil { return nil } return errObj.cause } // sumLengths return sum of lenghts of strings func sumLengths(parts []string) int { total := 0 for _, s := range parts { total += len(s) } return total } // trimPath shortens fileName to be at most size characters func trimPath(fileName string, size int) string { if len(fileName) <= size { return fileName } // We'd like to cut at directory boundary parts := strings.Split(fileName, "/") for sumLengths(parts) > size && len(parts) > 1 { parts = parts[1:] } return ".../" + strings.Join(parts, "/") } // Format formats an error func (err *Error) Format(s fmt.State, verb rune) { switch verb { case 'v': if s.Flag('+') { PrintErrorStack(s, err, -1) } fallthrough case 's': fmt.Fprintf(s, err.Error()) case 'q': fmt.Fprintf(s, "%q", err.Error()) } }
[ "\"NUCLIO_NO_ERROR_LINE_INFO\"" ]
[]
[ "NUCLIO_NO_ERROR_LINE_INFO" ]
[]
["NUCLIO_NO_ERROR_LINE_INFO"]
go
1
0
03C_Basic_OAuth/starter/app.py
from flask import Flask, g, url_for, redirect, abort, render_template import flask import requests import os from functools import wraps from auth import auth, require_authentication from db import FakeDatabase import werkzeug app = Flask(__name__) app.register_blueprint(auth) SECRET_KEY = os.environ.get("SECRET_KEY") if not SECRET_KEY: raise ValueError("No SECRET_KEY set for Flask application") GITHUB_CLIENT_ID = os.environ.get("GITHUB_CLIENT_ID") GITHUB_CLIENT_SECRET = os.environ.get("GITHUB_CLIENT_SECRET") if not GITHUB_CLIENT_ID or not GITHUB_CLIENT_SECRET: raise ValueError("No GITHUB_CLIENT_ID or GITHUB_CLIENT_SECRET set for Flask application") app.config.update( SECRET_KEY=SECRET_KEY, GITHUB_CLIENT_ID=GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET=GITHUB_CLIENT_SECRET, ) db = FakeDatabase() @app.before_request def set_db_context(): flask.g.db = db @app.before_request def set_user_context(): if 'user_id' in flask.session: flask.g.user = flask.g.db.get_user(flask.session['user_id']) @app.route('/profile') @require_authentication def get_profile(): user = flask.g.db.get_user(flask.session['user_id']) print(user) return render_template( 'profile.html', profile_image_url=user['avatar_url'], username=user['username'] ) @app.errorhandler(werkzeug.exceptions.Forbidden) def forbidden_error_handler(e): return render_template('403-forbidden.html'), 403 @app.route('/signup') def signup(): if 'github_id' not in flask.session: return render_template('signup.html') github_profile = flask.g.db.get_github_profile(flask.session['github_id']) if not github_profile: return render_template('signup.html') print(github_profile) return render_template( 'create-account.html', github_username=github_profile['login'] or '', github_email=github_profile['email'] or '' ) @app.route('/users', methods=['POST']) def create_account(): if 'github_id' not in flask.session: return render_template('signup.html') github_id = flask.session['github_id'] github_profile = flask.g.db.get_github_profile(github_id) username = flask.request.form['username'] email = flask.request.form['email'] avatar_url = github_profile['avatar_url'] flask.g.db.create_user(username, email, avatar_url, github_id=github_id) flask.session['user_id'] = username return redirect(url_for('get_profile')) @app.route('/') def login(): return render_template( 'login.html' ) application = app
[]
[]
[ "SECRET_KEY", "GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET" ]
[]
["SECRET_KEY", "GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET"]
python
3
0
cmd/run_test.go
package cmd_test import ( "encoding/json" "errors" "fmt" "io" "net/http" "net/http/httptest" "os" "os/exec" "testing" "time" "github.com/wakatime/wakatime-cli/cmd" "github.com/wakatime/wakatime-cli/pkg/version" "github.com/spf13/viper" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" bolt "go.etcd.io/bbolt" ) func TestRunCmd_SendDiagnostics_Error(t *testing.T) { // this is exclusively run in subprocess if os.Getenv("TEST_RUN") == "1" { version.OS = "some os" version.Arch = "some architecture" version.Version = "some version" offlineQueueFile, err := os.CreateTemp(os.TempDir(), "") require.NoError(t, err) defer os.Remove(offlineQueueFile.Name()) logFile, err := os.CreateTemp(os.TempDir(), "") require.NoError(t, err) defer os.Remove(logFile.Name()) v := viper.New() v.Set("api-url", os.Getenv("TEST_SERVER_URL")) v.Set("entity", "/path/to/file") v.Set("key", "00000000-0000-4000-8000-000000000000") v.Set("log-file", logFile.Name()) v.Set("log-to-stdout", true) v.Set("offline-queue-file", offlineQueueFile.Name()) v.Set("plugin", "vim") cmd.RunCmd(v, true, func(v *viper.Viper) (int, error) { return 42, errors.New("fail") }) return } testServerURL, router, tearDown := setupTestServer() defer tearDown() router.HandleFunc("/plugins/errors", func(w http.ResponseWriter, req *http.Request) { // check request assert.Equal(t, http.MethodPost, req.Method) assert.Nil(t, req.Header["Authorization"]) assert.Equal(t, []string{"application/json"}, req.Header["Content-Type"]) expectedBodyTpl, err := os.ReadFile("testdata/diagnostics_request_template.json") require.NoError(t, err) body, err := io.ReadAll(req.Body) require.NoError(t, err) var diagnostics struct { Platform string `json:"platform"` Architecture string `json:"architecture"` CliVersion string `json:"cli_version"` Editor string `json:"editor"` Logs string `json:"logs"` Stack string `json:"stacktrace"` } err = json.Unmarshal(body, &diagnostics) require.NoError(t, err) expectedBodyStr := fmt.Sprintf( string(expectedBodyTpl), jsonEscape(t, diagnostics.Logs), jsonEscape(t, diagnostics.Stack), ) assert.JSONEq(t, expectedBodyStr, string(body)) // send response w.WriteHeader(http.StatusCreated) }) // run command in another runner, to effectively test os.Exit() cmd := exec.Command(os.Args[0], "-test.run=TestRunCmd_SendDiagnostics_Error") // nolint:gosec cmd.Env = append(os.Environ(), "TEST_RUN=1") cmd.Env = append(cmd.Env, fmt.Sprintf("TEST_SERVER_URL=%s", testServerURL)) err := cmd.Run() e, ok := err.(*exec.ExitError) require.True(t, ok) assert.Equal(t, 42, e.ExitCode()) } func TestRunCmd_SendDiagnostics_Panic(t *testing.T) { // this is exclusively run in subprocess if os.Getenv("TEST_RUN") == "1" { version.OS = "some os" version.Arch = "some architecture" version.Version = "some version" offlineQueueFile, err := os.CreateTemp(os.TempDir(), "") require.NoError(t, err) defer os.Remove(offlineQueueFile.Name()) logFile, err := os.CreateTemp(os.TempDir(), "") require.NoError(t, err) defer os.Remove(logFile.Name()) v := viper.New() v.Set("api-url", os.Getenv("TEST_SERVER_URL")) v.Set("entity", "/path/to/file") v.Set("key", "00000000-0000-4000-8000-000000000000") v.Set("log-file", logFile.Name()) v.Set("log-to-stdout", true) v.Set("offline-queue-file", offlineQueueFile.Name()) v.Set("plugin", "vim") cmd.RunCmd(v, true, func(v *viper.Viper) (int, error) { panic("fail") }) return } testServerURL, router, tearDown := setupTestServer() defer tearDown() router.HandleFunc("/plugins/errors", func(w http.ResponseWriter, req *http.Request) { // check request assert.Equal(t, http.MethodPost, req.Method) assert.Nil(t, req.Header["Authorization"]) assert.Equal(t, []string{"application/json"}, req.Header["Content-Type"]) expectedBodyTpl, err := os.ReadFile("testdata/diagnostics_request_template_no_logs.json") require.NoError(t, err) body, err := io.ReadAll(req.Body) require.NoError(t, err) var diagnostics struct { Platform string `json:"platform"` Architecture string `json:"architecture"` CliVersion string `json:"cli_version"` Editor string `json:"editor"` Logs string `json:"logs"` Stack string `json:"stacktrace"` } err = json.Unmarshal(body, &diagnostics) require.NoError(t, err) expectedBodyStr := fmt.Sprintf( string(expectedBodyTpl), jsonEscape(t, diagnostics.Stack), ) assert.JSONEq(t, expectedBodyStr, string(body)) // send response w.WriteHeader(http.StatusCreated) }) // run command in another runner, to effectively test os.Exit() cmd := exec.Command(os.Args[0], "-test.run=TestRunCmd_SendDiagnostics_Panic") // nolint:gosec cmd.Env = append(os.Environ(), "TEST_RUN=1") cmd.Env = append(cmd.Env, fmt.Sprintf("TEST_SERVER_URL=%s", testServerURL)) err := cmd.Run() e, ok := err.(*exec.ExitError) require.True(t, ok) assert.Equal(t, 1, e.ExitCode()) } func TestRunCmdWithOfflineSync(t *testing.T) { // this is exclusively run in subprocess if os.Getenv("TEST_RUN") == "1" { version.OS = "some os" version.Arch = "some architecture" version.Version = "some version" logFile, err := os.CreateTemp(os.TempDir(), "") require.NoError(t, err) defer os.Remove(logFile.Name()) v := viper.New() v.Set("api-url", os.Getenv("TEST_SERVER_URL")) v.Set("entity", "/path/to/file") v.Set("key", "00000000-0000-4000-8000-000000000000") v.Set("log-file", logFile.Name()) v.Set("log-to-stdout", true) v.Set("offline-queue-file", os.Getenv("OFFLINE_QUEUE_FILE")) v.SetDefault("sync-offline-activity", 24) v.Set("plugin", "vim") cmd.RunCmdWithOfflineSync(v, false, func(v *viper.Viper) (int, error) { return 0, nil }) return } // setup test queue offlineQueueFile, err := os.CreateTemp(os.TempDir(), "") require.NoError(t, err) defer os.RemoveAll(offlineQueueFile.Name()) db, err := bolt.Open(offlineQueueFile.Name(), 0600, nil) require.NoError(t, err) dataGo, err := os.ReadFile("testdata/heartbeat_go.json") require.NoError(t, err) dataPy, err := os.ReadFile("testdata/heartbeat_py.json") require.NoError(t, err) insertHeartbeatRecords(t, db, "heartbeats", []heartbeatRecord{ { ID: "1592868367.219124-file-coding-wakatime-cli-heartbeat-/tmp/main.go-true", Heartbeat: string(dataGo), }, { ID: "1592868386.079084-file-debugging-wakatime-summary-/tmp/main.py-false", Heartbeat: string(dataPy), }, }) db.Close() // setup test server testServerURL, router, tearDown := setupTestServer() defer tearDown() var numCalls int router.HandleFunc("/users/current/heartbeats.bulk", func(w http.ResponseWriter, req *http.Request) { numCalls++ // check headers assert.Equal(t, http.MethodPost, req.Method) assert.Equal(t, []string{"application/json"}, req.Header["Accept"]) assert.Equal(t, []string{"application/json"}, req.Header["Content-Type"]) // check body expectedBody, err := os.ReadFile("testdata/api_heartbeats_request.json") require.NoError(t, err) body, err := io.ReadAll(req.Body) require.NoError(t, err) assert.JSONEq(t, string(expectedBody), string(body)) // send response f, err := os.Open("testdata/api_heartbeats_response.json") require.NoError(t, err) w.WriteHeader(http.StatusCreated) _, err = io.Copy(w, f) require.NoError(t, err) }) // run command in another runner, to effectively test os.Exit() cmd := exec.Command(os.Args[0], "-test.run=TestRunCmdWithOfflineSync") // nolint:gosec cmd.Env = append(os.Environ(), "TEST_RUN=1") cmd.Env = append(cmd.Env, fmt.Sprintf("TEST_SERVER_URL=%s", testServerURL)) cmd.Env = append(cmd.Env, fmt.Sprintf("OFFLINE_QUEUE_FILE=%s", offlineQueueFile.Name())) err = cmd.Run() require.NoError(t, err) // check db db, err = bolt.Open(offlineQueueFile.Name(), 0600, nil) require.NoError(t, err) var stored []heartbeatRecord err = db.View(func(tx *bolt.Tx) error { c := tx.Bucket([]byte("heartbeats")).Cursor() for key, value := c.First(); key != nil; key, value = c.Next() { stored = append(stored, heartbeatRecord{ ID: string(key), Heartbeat: string(value), }) } return nil }) require.NoError(t, err) db.Close() require.Len(t, stored, 0) assert.Eventually(t, func() bool { return numCalls == 1 }, time.Second, 50*time.Millisecond) } func jsonEscape(t *testing.T, i string) string { b, err := json.Marshal(i) require.NoError(t, err) s := string(b) return s[1 : len(s)-1] } func setupTestServer() (string, *http.ServeMux, func()) { router := http.NewServeMux() srv := httptest.NewServer(router) return srv.URL, router, func() { srv.Close() } } type heartbeatRecord struct { ID string Heartbeat string } func insertHeartbeatRecords(t *testing.T, db *bolt.DB, bucket string, hh []heartbeatRecord) { for _, h := range hh { insertHeartbeatRecord(t, db, bucket, h) } } func insertHeartbeatRecord(t *testing.T, db *bolt.DB, bucket string, h heartbeatRecord) { t.Helper() err := db.Update(func(tx *bolt.Tx) error { b, err := tx.CreateBucketIfNotExists([]byte(bucket)) if err != nil { return fmt.Errorf("failed to create bucket: %s", err) } err = b.Put([]byte(h.ID), []byte(h.Heartbeat)) if err != nil { return fmt.Errorf("failed put hearbeat: %s", err) } return nil }) require.NoError(t, err) }
[ "\"TEST_RUN\"", "\"TEST_SERVER_URL\"", "\"TEST_RUN\"", "\"TEST_SERVER_URL\"", "\"TEST_RUN\"", "\"TEST_SERVER_URL\"", "\"OFFLINE_QUEUE_FILE\"" ]
[]
[ "OFFLINE_QUEUE_FILE", "TEST_RUN", "TEST_SERVER_URL" ]
[]
["OFFLINE_QUEUE_FILE", "TEST_RUN", "TEST_SERVER_URL"]
go
3
0
ui/agender_ui/agender_ui/wsgi.py
""" WSGI config for agender_ui 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.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'agender_ui.settings') application = get_wsgi_application()
[]
[]
[]
[]
[]
python
0
0
viper.go
// Copyright © 2014 Steve Francia <[email protected]>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // Viper is an application configuration system. // It believes that applications can be configured a variety of ways // via flags, ENVIRONMENT variables, configuration files retrieved // from the file system, or a remote key/value store. // Each item takes precedence over the item below it: // overrides // flag // env // config // key/value store // default package viper import ( "bytes" "encoding/csv" "encoding/json" "errors" "fmt" "io" "log" "os" "path/filepath" "reflect" "strings" "sync" "time" "github.com/fsnotify/fsnotify" "github.com/hashicorp/hcl" "github.com/hashicorp/hcl/hcl/printer" "github.com/magiconair/properties" "github.com/mitchellh/mapstructure" "github.com/pelletier/go-toml" "github.com/spf13/afero" "github.com/spf13/cast" jww "github.com/spf13/jwalterweatherman" "github.com/spf13/pflag" "github.com/subosito/gotenv" "gopkg.in/ini.v1" "gopkg.in/yaml.v2" ) // ConfigMarshalError happens when failing to marshal the configuration. type ConfigMarshalError struct { err error } // Error returns the formatted configuration error. func (e ConfigMarshalError) Error() string { return fmt.Sprintf("While marshaling config: %s", e.err.Error()) } var v *Viper type RemoteResponse struct { Value []byte Error error } func init() { v = New() } type remoteConfigFactory interface { Get(rp RemoteProvider) (io.Reader, error) Watch(rp RemoteProvider) (io.Reader, error) WatchChannel(rp RemoteProvider) (<-chan *RemoteResponse, chan bool) } // RemoteConfig is optional, see the remote package var RemoteConfig remoteConfigFactory // UnsupportedConfigError denotes encountering an unsupported // configuration filetype. type UnsupportedConfigError string // Error returns the formatted configuration error. func (str UnsupportedConfigError) Error() string { return fmt.Sprintf("Unsupported Config Type %q", string(str)) } // Denotes encountering an unsupported remote // provider. Currently only etcd, etcd clientv3, Consul, zookeeper are // supported. type UnsupportedRemoteProviderError string // Error returns the formatted remote provider error. func (str UnsupportedRemoteProviderError) Error() string { return fmt.Sprintf("Unsupported Remote Provider Type %q", string(str)) } // RemoteConfigError denotes encountering an error while trying to // pull the configuration from the remote provider. type RemoteConfigError string // Error returns the formatted remote provider error func (rce RemoteConfigError) Error() string { return fmt.Sprintf("Remote Configurations Error: %s", string(rce)) } // ConfigFileNotFoundError denotes failing to find configuration file. type ConfigFileNotFoundError struct { name, locations string } // Error returns the formatted configuration error. func (fnfe ConfigFileNotFoundError) Error() string { return fmt.Sprintf("Config File %q Not Found in %q", fnfe.name, fnfe.locations) } // ConfigFileAlreadyExistsError denotes failure to write new configuration file. type ConfigFileAlreadyExistsError string // Error returns the formatted error when configuration already exists. func (faee ConfigFileAlreadyExistsError) Error() string { return fmt.Sprintf("Config File %q Already Exists", string(faee)) } // A DecoderConfigOption can be passed to viper.Unmarshal to configure // mapstructure.DecoderConfig options type DecoderConfigOption func(*mapstructure.DecoderConfig) // DecodeHook returns a DecoderConfigOption which overrides the default // DecoderConfig.DecodeHook value, the default is: // // mapstructure.ComposeDecodeHookFunc( // mapstructure.StringToTimeDurationHookFunc(), // mapstructure.StringToSliceHookFunc(","), // ) func DecodeHook(hook mapstructure.DecodeHookFunc) DecoderConfigOption { return func(c *mapstructure.DecoderConfig) { c.DecodeHook = hook } } // Viper is a prioritized configuration registry. It // maintains a set of configuration sources, fetches // values to populate those, and provides them according // to the source's priority. // The priority of the sources is the following: // 1. overrides // 2. flags // 3. env. variables // 4. config file // 5. key/value store // 6. defaults // // For example, if values from the following sources were loaded: // // Defaults : { // "secret": "", // "user": "default", // "endpoint": "https://localhost" // } // Config : { // "user": "root" // "secret": "defaultsecret" // } // Env : { // "secret": "somesecretkey" // } // // The resulting config will have the following values: // // { // "secret": "somesecretkey", // "user": "root", // "endpoint": "https://localhost" // } type Viper struct { // Delimiter that separates a list of keys // used to access a nested value in one go keyDelim string // A set of paths to look for the config file in configPaths []string // The filesystem to read config from. fs afero.Fs // A set of remote providers to search for the configuration remoteProviders []*defaultRemoteProvider // Name of file to look for inside the path configName string configFile string configType string configPermissions os.FileMode envPrefix string automaticEnvApplied bool envKeyReplacer StringReplacer allowEmptyEnv bool config map[string]interface{} override map[string]interface{} defaults map[string]interface{} kvstore map[string]interface{} pflags map[string]FlagValue env map[string]string aliases map[string]string typeByDefValue bool // Store read properties on the object so that we can write back in order with comments. // This will only be used if the configuration read is a properties file. properties *properties.Properties onConfigChange func(fsnotify.Event) } // New returns an initialized Viper instance. func New() *Viper { v := new(Viper) v.keyDelim = "." v.configName = "config" v.configPermissions = os.FileMode(0644) v.fs = afero.NewOsFs() v.config = make(map[string]interface{}) v.override = make(map[string]interface{}) v.defaults = make(map[string]interface{}) v.kvstore = make(map[string]interface{}) v.pflags = make(map[string]FlagValue) v.env = make(map[string]string) v.aliases = make(map[string]string) v.typeByDefValue = false return v } // Option configures Viper using the functional options paradigm popularized by Rob Pike and Dave Cheney. // If you're unfamiliar with this style, // see https://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html and // https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis. type Option interface { apply(v *Viper) } type optionFunc func(v *Viper) func (fn optionFunc) apply(v *Viper) { fn(v) } // KeyDelimiter sets the delimiter used for determining key parts. // By default it's value is ".". func KeyDelimiter(d string) Option { return optionFunc(func(v *Viper) { v.keyDelim = d }) } // StringReplacer applies a set of replacements to a string. type StringReplacer interface { // Replace returns a copy of s with all replacements performed. Replace(s string) string } // EnvKeyReplacer sets a replacer used for mapping environment variables to internal keys. func EnvKeyReplacer(r StringReplacer) Option { return optionFunc(func(v *Viper) { v.envKeyReplacer = r }) } // NewWithOptions creates a new Viper instance. func NewWithOptions(opts ...Option) *Viper { v := New() for _, opt := range opts { opt.apply(v) } return v } // Reset is intended for testing, will reset all to default settings. // In the public interface for the viper package so applications // can use it in their testing as well. func Reset() { v = New() SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "dotenv", "env", "ini"} SupportedRemoteProviders = []string{"etcd", "etcd3", "consul", "zookeeper"} } type defaultRemoteProvider struct { provider string endpoint string path string secretKeyring string } func (rp defaultRemoteProvider) Provider() string { return rp.provider } func (rp defaultRemoteProvider) Endpoint() string { return rp.endpoint } func (rp defaultRemoteProvider) Path() string { return rp.path } func (rp defaultRemoteProvider) SecretKeyring() string { return rp.secretKeyring } // RemoteProvider stores the configuration necessary // to connect to a remote key/value store. // Optional secretKeyring to unencrypt encrypted values // can be provided. type RemoteProvider interface { Provider() string Endpoint() string Path() string SecretKeyring() string } // SupportedExts are universally supported extensions. var SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "dotenv", "env", "ini"} // Universally supported remote providers. var SupportedRemoteProviders []string = []string{"etcd", "etcd3", "consul", "zookeeper"} func OnConfigChange(run func(in fsnotify.Event)) { v.OnConfigChange(run) } func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) { v.onConfigChange = run } func WatchConfig() { v.WatchConfig() } func (v *Viper) WatchConfig() { initWG := sync.WaitGroup{} initWG.Add(1) go func() { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() // we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way filename, err := v.getConfigFile() if err != nil { log.Printf("error: %v\n", err) initWG.Done() return } configFile := filepath.Clean(filename) configDir, _ := filepath.Split(configFile) realConfigFile, _ := filepath.EvalSymlinks(filename) eventsWG := sync.WaitGroup{} eventsWG.Add(1) go func() { for { select { case event, ok := <-watcher.Events: if !ok { // 'Events' channel is closed eventsWG.Done() return } currentConfigFile, _ := filepath.EvalSymlinks(filename) // we only care about the config file with the following cases: // 1 - if the config file was modified or created // 2 - if the real path to the config file changed (eg: k8s ConfigMap replacement) const writeOrCreateMask = fsnotify.Write | fsnotify.Create if (filepath.Clean(event.Name) == configFile && event.Op&writeOrCreateMask != 0) || (currentConfigFile != "" && currentConfigFile != realConfigFile) { realConfigFile = currentConfigFile err := v.ReadInConfig() if err != nil { log.Printf("error reading config file: %v\n", err) } if v.onConfigChange != nil { v.onConfigChange(event) } } else if filepath.Clean(event.Name) == configFile && event.Op&fsnotify.Remove&fsnotify.Remove != 0 { eventsWG.Done() return } case err, ok := <-watcher.Errors: if ok { // 'Errors' channel is not closed log.Printf("watcher error: %v\n", err) } eventsWG.Done() return } } }() watcher.Add(configDir) initWG.Done() // done initializing the watch in this go routine, so the parent routine can move on... eventsWG.Wait() // now, wait for event loop to end in this go-routine... }() initWG.Wait() // make sure that the go routine above fully ended before returning } // SetConfigFile explicitly defines the path, name and extension of the config file. // Viper will use this and not check any of the config paths. func SetConfigFile(in string) { v.SetConfigFile(in) } func (v *Viper) SetConfigFile(in string) { if in != "" { v.configFile = in } } // SetEnvPrefix defines a prefix that ENVIRONMENT variables will use. // E.g. if your prefix is "spf", the env registry will look for env // variables that start with "SPF_". func SetEnvPrefix(in string) { v.SetEnvPrefix(in) } func (v *Viper) SetEnvPrefix(in string) { if in != "" { v.envPrefix = in } } func (v *Viper) mergeWithEnvPrefix(in string) string { if v.envPrefix != "" { return strings.ToUpper(v.envPrefix + "_" + in) } return strings.ToUpper(in) } // AllowEmptyEnv tells Viper to consider set, // but empty environment variables as valid values instead of falling back. // For backward compatibility reasons this is false by default. func AllowEmptyEnv(allowEmptyEnv bool) { v.AllowEmptyEnv(allowEmptyEnv) } func (v *Viper) AllowEmptyEnv(allowEmptyEnv bool) { v.allowEmptyEnv = allowEmptyEnv } // TODO: should getEnv logic be moved into find(). Can generalize the use of // rewriting keys many things, Ex: Get('someKey') -> some_key // (camel case to snake case for JSON keys perhaps) // getEnv is a wrapper around os.Getenv which replaces characters in the original // key. This allows env vars which have different keys than the config object // keys. func (v *Viper) getEnv(key string) (string, bool) { if v.envKeyReplacer != nil { key = v.envKeyReplacer.Replace(key) } val, ok := os.LookupEnv(key) return val, ok && (v.allowEmptyEnv || val != "") } // ConfigFileUsed returns the file used to populate the config registry. func ConfigFileUsed() string { return v.ConfigFileUsed() } func (v *Viper) ConfigFileUsed() string { return v.configFile } // AddConfigPath adds a path for Viper to search for the config file in. // Can be called multiple times to define multiple search paths. func AddConfigPath(in string) { v.AddConfigPath(in) } func (v *Viper) AddConfigPath(in string) { if in != "" { absin := absPathify(in) jww.INFO.Println("adding", absin, "to paths to search") if !stringInSlice(absin, v.configPaths) { v.configPaths = append(v.configPaths, absin) } } } // AddRemoteProvider adds a remote configuration source. // Remote Providers are searched in the order they are added. // provider is a string value, "etcd", "etcd3", "consul" or "zookeeper" are currently supported. // endpoint is the url. etcd requires http://ip:port consul requires ip:port // path is the path in the k/v store to retrieve configuration // To retrieve a config file called myapp.json from /configs/myapp.json // you should set path to /configs and set config name (SetConfigName()) to // "myapp" func AddRemoteProvider(provider, endpoint, path string) error { return v.AddRemoteProvider(provider, endpoint, path) } func (v *Viper) AddRemoteProvider(provider, endpoint, path string) error { if !stringInSlice(provider, SupportedRemoteProviders) { return UnsupportedRemoteProviderError(provider) } if provider != "" && endpoint != "" { jww.INFO.Printf("adding %s:%s to remote provider list", provider, endpoint) rp := &defaultRemoteProvider{ endpoint: endpoint, provider: provider, path: path, } if !v.providerPathExists(rp) { v.remoteProviders = append(v.remoteProviders, rp) } } return nil } // AddSecureRemoteProvider adds a remote configuration source. // Secure Remote Providers are searched in the order they are added. // provider is a string value, "etcd", "etcd3", "consul" or "zookeeper" are currently supported. // endpoint is the url. etcd requires http://ip:port consul requires ip:port // secretkeyring is the filepath to your openpgp secret keyring. e.g. /etc/secrets/myring.gpg // path is the path in the k/v store to retrieve configuration // To retrieve a config file called myapp.json from /configs/myapp.json // you should set path to /configs and set config name (SetConfigName()) to // "myapp" // Secure Remote Providers are implemented with github.com/bketelsen/crypt func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error { return v.AddSecureRemoteProvider(provider, endpoint, path, secretkeyring) } func (v *Viper) AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error { if !stringInSlice(provider, SupportedRemoteProviders) { return UnsupportedRemoteProviderError(provider) } if provider != "" && endpoint != "" { jww.INFO.Printf("adding %s:%s to remote provider list", provider, endpoint) rp := &defaultRemoteProvider{ endpoint: endpoint, provider: provider, path: path, secretKeyring: secretkeyring, } if !v.providerPathExists(rp) { v.remoteProviders = append(v.remoteProviders, rp) } } return nil } func (v *Viper) providerPathExists(p *defaultRemoteProvider) bool { for _, y := range v.remoteProviders { if reflect.DeepEqual(y, p) { return true } } return false } // searchMap recursively searches for a value for path in source map. // Returns nil if not found. // Note: This assumes that the path entries and map keys are lower cased. func (v *Viper) searchMap(source map[string]interface{}, path []string) interface{} { if len(path) == 0 { return source } next, ok := source[path[0]] if ok { // Fast path if len(path) == 1 { return next } // Nested case switch next.(type) { case map[interface{}]interface{}: return v.searchMap(cast.ToStringMap(next), path[1:]) case map[string]interface{}: // Type assertion is safe here since it is only reached // if the type of `next` is the same as the type being asserted return v.searchMap(next.(map[string]interface{}), path[1:]) default: // got a value but nested key expected, return "nil" for not found return nil } } return nil } // searchMapWithPathPrefixes recursively searches for a value for path in source map. // // While searchMap() considers each path element as a single map key, this // function searches for, and prioritizes, merged path elements. // e.g., if in the source, "foo" is defined with a sub-key "bar", and "foo.bar" // is also defined, this latter value is returned for path ["foo", "bar"]. // // This should be useful only at config level (other maps may not contain dots // in their keys). // // Note: This assumes that the path entries and map keys are lower cased. func (v *Viper) searchMapWithPathPrefixes(source map[string]interface{}, path []string) interface{} { if len(path) == 0 { return source } // search for path prefixes, starting from the longest one for i := len(path); i > 0; i-- { prefixKey := strings.ToLower(strings.Join(path[0:i], v.keyDelim)) next, ok := source[prefixKey] if ok { // Fast path if i == len(path) { return next } // Nested case var val interface{} switch next.(type) { case map[interface{}]interface{}: val = v.searchMapWithPathPrefixes(cast.ToStringMap(next), path[i:]) case map[string]interface{}: // Type assertion is safe here since it is only reached // if the type of `next` is the same as the type being asserted val = v.searchMapWithPathPrefixes(next.(map[string]interface{}), path[i:]) default: // got a value but nested key expected, do nothing and look for next prefix } if val != nil { return val } } } // not found return nil } // isPathShadowedInDeepMap makes sure the given path is not shadowed somewhere // on its path in the map. // e.g., if "foo.bar" has a value in the given map, it “shadows” // "foo.bar.baz" in a lower-priority map func (v *Viper) isPathShadowedInDeepMap(path []string, m map[string]interface{}) string { var parentVal interface{} for i := 1; i < len(path); i++ { parentVal = v.searchMap(m, path[0:i]) if parentVal == nil { // not found, no need to add more path elements return "" } switch parentVal.(type) { case map[interface{}]interface{}: continue case map[string]interface{}: continue default: // parentVal is a regular value which shadows "path" return strings.Join(path[0:i], v.keyDelim) } } return "" } // isPathShadowedInFlatMap makes sure the given path is not shadowed somewhere // in a sub-path of the map. // e.g., if "foo.bar" has a value in the given map, it “shadows” // "foo.bar.baz" in a lower-priority map func (v *Viper) isPathShadowedInFlatMap(path []string, mi interface{}) string { // unify input map var m map[string]interface{} switch mi.(type) { case map[string]string, map[string]FlagValue: m = cast.ToStringMap(mi) default: return "" } // scan paths var parentKey string for i := 1; i < len(path); i++ { parentKey = strings.Join(path[0:i], v.keyDelim) if _, ok := m[parentKey]; ok { return parentKey } } return "" } // isPathShadowedInAutoEnv makes sure the given path is not shadowed somewhere // in the environment, when automatic env is on. // e.g., if "foo.bar" has a value in the environment, it “shadows” // "foo.bar.baz" in a lower-priority map func (v *Viper) isPathShadowedInAutoEnv(path []string) string { var parentKey string for i := 1; i < len(path); i++ { parentKey = strings.Join(path[0:i], v.keyDelim) if _, ok := v.getEnv(v.mergeWithEnvPrefix(parentKey)); ok { return parentKey } } return "" } // SetTypeByDefaultValue enables or disables the inference of a key value's // type when the Get function is used based upon a key's default value as // opposed to the value returned based on the normal fetch logic. // // For example, if a key has a default value of []string{} and the same key // is set via an environment variable to "a b c", a call to the Get function // would return a string slice for the key if the key's type is inferred by // the default value and the Get function would return: // // []string {"a", "b", "c"} // // Otherwise the Get function would return: // // "a b c" func SetTypeByDefaultValue(enable bool) { v.SetTypeByDefaultValue(enable) } func (v *Viper) SetTypeByDefaultValue(enable bool) { v.typeByDefValue = enable } // GetViper gets the global Viper instance. func GetViper() *Viper { return v } // Get can retrieve any value given the key to use. // Get is case-insensitive for a key. // Get has the behavior of returning the value associated with the first // place from where it is set. Viper will check in the following order: // override, flag, env, config file, key/value store, default // // Get returns an interface. For a specific value use one of the Get____ methods. func Get(key string) interface{} { return v.Get(key) } func (v *Viper) Get(key string) interface{} { lcaseKey := strings.ToLower(key) val := v.find(lcaseKey, true) if val == nil { return nil } if v.typeByDefValue { // TODO(bep) this branch isn't covered by a single test. valType := val path := strings.Split(lcaseKey, v.keyDelim) defVal := v.searchMap(v.defaults, path) if defVal != nil { valType = defVal } switch valType.(type) { case bool: return cast.ToBool(val) case string: return cast.ToString(val) case int32, int16, int8, int: return cast.ToInt(val) case uint: return cast.ToUint(val) case uint32: return cast.ToUint32(val) case uint64: return cast.ToUint64(val) case int64: return cast.ToInt64(val) case float64, float32: return cast.ToFloat64(val) case time.Time: return cast.ToTime(val) case time.Duration: return cast.ToDuration(val) case []string: return cast.ToStringSlice(val) case []int: return cast.ToIntSlice(val) } } return val } // Sub returns new Viper instance representing a sub tree of this instance. // Sub is case-insensitive for a key. func Sub(key string) *Viper { return v.Sub(key) } func (v *Viper) Sub(key string) *Viper { subv := New() data := v.Get(key) if data == nil { return nil } if reflect.TypeOf(data).Kind() == reflect.Map { subv.config = cast.ToStringMap(data) return subv } return nil } // GetString returns the value associated with the key as a string. func GetString(key string) string { return v.GetString(key) } func (v *Viper) GetString(key string) string { return cast.ToString(v.Get(key)) } // GetBool returns the value associated with the key as a boolean. func GetBool(key string) bool { return v.GetBool(key) } func (v *Viper) GetBool(key string) bool { return cast.ToBool(v.Get(key)) } // GetInt returns the value associated with the key as an integer. func GetInt(key string) int { return v.GetInt(key) } func (v *Viper) GetInt(key string) int { return cast.ToInt(v.Get(key)) } // GetInt32 returns the value associated with the key as an integer. func GetInt32(key string) int32 { return v.GetInt32(key) } func (v *Viper) GetInt32(key string) int32 { return cast.ToInt32(v.Get(key)) } // GetInt64 returns the value associated with the key as an integer. func GetInt64(key string) int64 { return v.GetInt64(key) } func (v *Viper) GetInt64(key string) int64 { return cast.ToInt64(v.Get(key)) } // GetUint returns the value associated with the key as an unsigned integer. func GetUint(key string) uint { return v.GetUint(key) } func (v *Viper) GetUint(key string) uint { return cast.ToUint(v.Get(key)) } // GetUint32 returns the value associated with the key as an unsigned integer. func GetUint32(key string) uint32 { return v.GetUint32(key) } func (v *Viper) GetUint32(key string) uint32 { return cast.ToUint32(v.Get(key)) } // GetUint64 returns the value associated with the key as an unsigned integer. func GetUint64(key string) uint64 { return v.GetUint64(key) } func (v *Viper) GetUint64(key string) uint64 { return cast.ToUint64(v.Get(key)) } // GetFloat64 returns the value associated with the key as a float64. func GetFloat64(key string) float64 { return v.GetFloat64(key) } func (v *Viper) GetFloat64(key string) float64 { return cast.ToFloat64(v.Get(key)) } // GetTime returns the value associated with the key as time. func GetTime(key string) time.Time { return v.GetTime(key) } func (v *Viper) GetTime(key string) time.Time { return cast.ToTime(v.Get(key)) } // GetDuration returns the value associated with the key as a duration. func GetDuration(key string) time.Duration { return v.GetDuration(key) } func (v *Viper) GetDuration(key string) time.Duration { return cast.ToDuration(v.Get(key)) } // GetIntSlice returns the value associated with the key as a slice of int values. func GetIntSlice(key string) []int { return v.GetIntSlice(key) } func (v *Viper) GetIntSlice(key string) []int { return cast.ToIntSlice(v.Get(key)) } // GetStringSlice returns the value associated with the key as a slice of strings. func GetStringSlice(key string) []string { return v.GetStringSlice(key) } func (v *Viper) GetStringSlice(key string) []string { return cast.ToStringSlice(v.Get(key)) } // GetStringMap returns the value associated with the key as a map of interfaces. func GetStringMap(key string) map[string]interface{} { return v.GetStringMap(key) } func (v *Viper) GetStringMap(key string) map[string]interface{} { return cast.ToStringMap(v.Get(key)) } // GetStringMapString returns the value associated with the key as a map of strings. func GetStringMapString(key string) map[string]string { return v.GetStringMapString(key) } func (v *Viper) GetStringMapString(key string) map[string]string { return cast.ToStringMapString(v.Get(key)) } // GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings. func GetStringMapStringSlice(key string) map[string][]string { return v.GetStringMapStringSlice(key) } func (v *Viper) GetStringMapStringSlice(key string) map[string][]string { return cast.ToStringMapStringSlice(v.Get(key)) } // GetSizeInBytes returns the size of the value associated with the given key // in bytes. func GetSizeInBytes(key string) uint { return v.GetSizeInBytes(key) } func (v *Viper) GetSizeInBytes(key string) uint { sizeStr := cast.ToString(v.Get(key)) return parseSizeInBytes(sizeStr) } // UnmarshalKey takes a single key and unmarshals it into a Struct. func UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error { return v.UnmarshalKey(key, rawVal, opts...) } func (v *Viper) UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error { err := decode(v.Get(key), defaultDecoderConfig(rawVal, opts...)) if err != nil { return err } return nil } // Unmarshal unmarshals the config into a Struct. Make sure that the tags // on the fields of the structure are properly set. func Unmarshal(rawVal interface{}, opts ...DecoderConfigOption) error { return v.Unmarshal(rawVal, opts...) } func (v *Viper) Unmarshal(rawVal interface{}, opts ...DecoderConfigOption) error { err := decode(v.AllSettings(), defaultDecoderConfig(rawVal, opts...)) if err != nil { return err } return nil } // defaultDecoderConfig returns default mapsstructure.DecoderConfig with suppot // of time.Duration values & string slices func defaultDecoderConfig(output interface{}, opts ...DecoderConfigOption) *mapstructure.DecoderConfig { c := &mapstructure.DecoderConfig{ Metadata: nil, Result: output, WeaklyTypedInput: true, DecodeHook: mapstructure.ComposeDecodeHookFunc( mapstructure.StringToTimeDurationHookFunc(), mapstructure.StringToSliceHookFunc(","), ), } for _, opt := range opts { opt(c) } return c } // A wrapper around mapstructure.Decode that mimics the WeakDecode functionality func decode(input interface{}, config *mapstructure.DecoderConfig) error { decoder, err := mapstructure.NewDecoder(config) if err != nil { return err } return decoder.Decode(input) } // UnmarshalExact unmarshals the config into a Struct, erroring if a field is nonexistent // in the destination struct. func UnmarshalExact(rawVal interface{}, opts ...DecoderConfigOption) error { return v.UnmarshalExact(rawVal, opts...) } func (v *Viper) UnmarshalExact(rawVal interface{}, opts ...DecoderConfigOption) error { config := defaultDecoderConfig(rawVal, opts...) config.ErrorUnused = true err := decode(v.AllSettings(), config) if err != nil { return err } return nil } // BindPFlags binds a full flag set to the configuration, using each flag's long // name as the config key. func BindPFlags(flags *pflag.FlagSet) error { return v.BindPFlags(flags) } func (v *Viper) BindPFlags(flags *pflag.FlagSet) error { return v.BindFlagValues(pflagValueSet{flags}) } // BindPFlag binds a specific key to a pflag (as used by cobra). // Example (where serverCmd is a Cobra instance): // // serverCmd.Flags().Int("port", 1138, "Port to run Application server on") // Viper.BindPFlag("port", serverCmd.Flags().Lookup("port")) // func BindPFlag(key string, flag *pflag.Flag) error { return v.BindPFlag(key, flag) } func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error { return v.BindFlagValue(key, pflagValue{flag}) } // BindFlagValues binds a full FlagValue set to the configuration, using each flag's long // name as the config key. func BindFlagValues(flags FlagValueSet) error { return v.BindFlagValues(flags) } func (v *Viper) BindFlagValues(flags FlagValueSet) (err error) { flags.VisitAll(func(flag FlagValue) { if err = v.BindFlagValue(flag.Name(), flag); err != nil { return } }) return nil } // BindFlagValue binds a specific key to a FlagValue. func BindFlagValue(key string, flag FlagValue) error { return v.BindFlagValue(key, flag) } func (v *Viper) BindFlagValue(key string, flag FlagValue) error { if flag == nil { return fmt.Errorf("flag for %q is nil", key) } v.pflags[strings.ToLower(key)] = flag return nil } // BindEnv binds a Viper key to a ENV variable. // ENV variables are case sensitive. // If only a key is provided, it will use the env key matching the key, uppercased. // EnvPrefix will be used when set when env name is not provided. func BindEnv(input ...string) error { return v.BindEnv(input...) } func (v *Viper) BindEnv(input ...string) error { var key, envkey string if len(input) == 0 { return fmt.Errorf("missing key to bind to") } key = strings.ToLower(input[0]) if len(input) == 1 { envkey = v.mergeWithEnvPrefix(key) } else { envkey = input[1] } v.env[key] = envkey return nil } // Given a key, find the value. // // Viper will check to see if an alias exists first. // Viper will then check in the following order: // flag, env, config file, key/value store. // Lastly, if no value was found and flagDefault is true, and if the key // corresponds to a flag, the flag's default value is returned. // // Note: this assumes a lower-cased key given. func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} { var ( val interface{} exists bool path = strings.Split(lcaseKey, v.keyDelim) nested = len(path) > 1 ) // compute the path through the nested maps to the nested value if nested && v.isPathShadowedInDeepMap(path, castMapStringToMapInterface(v.aliases)) != "" { return nil } // if the requested key is an alias, then return the proper key lcaseKey = v.realKey(lcaseKey) path = strings.Split(lcaseKey, v.keyDelim) nested = len(path) > 1 // Set() override first val = v.searchMap(v.override, path) if val != nil { return val } if nested && v.isPathShadowedInDeepMap(path, v.override) != "" { return nil } // PFlag override next flag, exists := v.pflags[lcaseKey] if exists && flag.HasChanged() { switch flag.ValueType() { case "int", "int8", "int16", "int32", "int64": return cast.ToInt(flag.ValueString()) case "bool": return cast.ToBool(flag.ValueString()) case "stringSlice": s := strings.TrimPrefix(flag.ValueString(), "[") s = strings.TrimSuffix(s, "]") res, _ := readAsCSV(s) return res case "intSlice": s := strings.TrimPrefix(flag.ValueString(), "[") s = strings.TrimSuffix(s, "]") res, _ := readAsCSV(s) return cast.ToIntSlice(res) default: return flag.ValueString() } } if nested && v.isPathShadowedInFlatMap(path, v.pflags) != "" { return nil } // Env override next if v.automaticEnvApplied { // even if it hasn't been registered, if automaticEnv is used, // check any Get request if val, ok := v.getEnv(v.mergeWithEnvPrefix(lcaseKey)); ok { return val } if nested && v.isPathShadowedInAutoEnv(path) != "" { return nil } } envkey, exists := v.env[lcaseKey] if exists { if val, ok := v.getEnv(envkey); ok { return val } } if nested && v.isPathShadowedInFlatMap(path, v.env) != "" { return nil } // Config file next val = v.searchMapWithPathPrefixes(v.config, path) if val != nil { return val } if nested && v.isPathShadowedInDeepMap(path, v.config) != "" { return nil } // K/V store next val = v.searchMap(v.kvstore, path) if val != nil { return val } if nested && v.isPathShadowedInDeepMap(path, v.kvstore) != "" { return nil } // Default next val = v.searchMap(v.defaults, path) if val != nil { return val } if nested && v.isPathShadowedInDeepMap(path, v.defaults) != "" { return nil } if flagDefault { // last chance: if no value is found and a flag does exist for the key, // get the flag's default value even if the flag's value has not been set. if flag, exists := v.pflags[lcaseKey]; exists { switch flag.ValueType() { case "int", "int8", "int16", "int32", "int64": return cast.ToInt(flag.ValueString()) case "bool": return cast.ToBool(flag.ValueString()) case "stringSlice": s := strings.TrimPrefix(flag.ValueString(), "[") s = strings.TrimSuffix(s, "]") res, _ := readAsCSV(s) return res case "intSlice": s := strings.TrimPrefix(flag.ValueString(), "[") s = strings.TrimSuffix(s, "]") res, _ := readAsCSV(s) return cast.ToIntSlice(res) default: return flag.ValueString() } } // last item, no need to check shadowing } return nil } func readAsCSV(val string) ([]string, error) { if val == "" { return []string{}, nil } stringReader := strings.NewReader(val) csvReader := csv.NewReader(stringReader) return csvReader.Read() } // IsSet checks to see if the key has been set in any of the data locations. // IsSet is case-insensitive for a key. func IsSet(key string) bool { return v.IsSet(key) } func (v *Viper) IsSet(key string) bool { lcaseKey := strings.ToLower(key) val := v.find(lcaseKey, false) return val != nil } // AutomaticEnv has Viper check ENV variables for all. // keys set in config, default & flags func AutomaticEnv() { v.AutomaticEnv() } func (v *Viper) AutomaticEnv() { v.automaticEnvApplied = true } // SetEnvKeyReplacer sets the strings.Replacer on the viper object // Useful for mapping an environmental variable to a key that does // not match it. func SetEnvKeyReplacer(r *strings.Replacer) { v.SetEnvKeyReplacer(r) } func (v *Viper) SetEnvKeyReplacer(r *strings.Replacer) { v.envKeyReplacer = r } // RegisterAlias creates an alias that provides another accessor for the same key. // This enables one to change a name without breaking the application. func RegisterAlias(alias string, key string) { v.RegisterAlias(alias, key) } func (v *Viper) RegisterAlias(alias string, key string) { v.registerAlias(alias, strings.ToLower(key)) } func (v *Viper) registerAlias(alias string, key string) { alias = strings.ToLower(alias) if alias != key && alias != v.realKey(key) { _, exists := v.aliases[alias] if !exists { // if we alias something that exists in one of the maps to another // name, we'll never be able to get that value using the original // name, so move the config value to the new realkey. if val, ok := v.config[alias]; ok { delete(v.config, alias) v.config[key] = val } if val, ok := v.kvstore[alias]; ok { delete(v.kvstore, alias) v.kvstore[key] = val } if val, ok := v.defaults[alias]; ok { delete(v.defaults, alias) v.defaults[key] = val } if val, ok := v.override[alias]; ok { delete(v.override, alias) v.override[key] = val } v.aliases[alias] = key } } else { jww.WARN.Println("Creating circular reference alias", alias, key, v.realKey(key)) } } func (v *Viper) realKey(key string) string { newkey, exists := v.aliases[key] if exists { jww.DEBUG.Println("Alias", key, "to", newkey) return v.realKey(newkey) } return key } // InConfig checks to see if the given key (or an alias) is in the config file. func InConfig(key string) bool { return v.InConfig(key) } func (v *Viper) InConfig(key string) bool { // if the requested key is an alias, then return the proper key key = v.realKey(key) _, exists := v.config[key] return exists } // SetDefault sets the default value for this key. // SetDefault is case-insensitive for a key. // Default only used when no value is provided by the user via flag, config or ENV. func SetDefault(key string, value interface{}) { v.SetDefault(key, value) } func (v *Viper) SetDefault(key string, value interface{}) { // If alias passed in, then set the proper default key = v.realKey(strings.ToLower(key)) value = toCaseInsensitiveValue(value) path := strings.Split(key, v.keyDelim) lastKey := strings.ToLower(path[len(path)-1]) deepestMap := deepSearch(v.defaults, path[0:len(path)-1]) // set innermost value deepestMap[lastKey] = value } // Set sets the value for the key in the override register. // Set is case-insensitive for a key. // Will be used instead of values obtained via // flags, config file, ENV, default, or key/value store. func Set(key string, value interface{}) { v.Set(key, value) } func (v *Viper) Set(key string, value interface{}) { // If alias passed in, then set the proper override key = v.realKey(strings.ToLower(key)) value = toCaseInsensitiveValue(value) path := strings.Split(key, v.keyDelim) lastKey := strings.ToLower(path[len(path)-1]) deepestMap := deepSearch(v.override, path[0:len(path)-1]) // set innermost value deepestMap[lastKey] = value } // ReadInConfig will discover and load the configuration file from disk // and key/value stores, searching in one of the defined paths. func ReadInConfig() error { return v.ReadInConfig() } func (v *Viper) ReadInConfig() error { jww.INFO.Println("Attempting to read in config file") filename, err := v.getConfigFile() if err != nil { return err } if !stringInSlice(v.getConfigType(), SupportedExts) { return UnsupportedConfigError(v.getConfigType()) } jww.DEBUG.Println("Reading file: ", filename) file, err := afero.ReadFile(v.fs, filename) if err != nil { return err } config := make(map[string]interface{}) err = v.unmarshalReader(bytes.NewReader(file), config) if err != nil { return err } v.config = config return nil } // MergeInConfig merges a new configuration with an existing config. func MergeInConfig() error { return v.MergeInConfig() } func (v *Viper) MergeInConfig() error { jww.INFO.Println("Attempting to merge in config file") filename, err := v.getConfigFile() if err != nil { return err } if !stringInSlice(v.getConfigType(), SupportedExts) { return UnsupportedConfigError(v.getConfigType()) } file, err := afero.ReadFile(v.fs, filename) if err != nil { return err } return v.MergeConfig(bytes.NewReader(file)) } // ReadConfig will read a configuration file, setting existing keys to nil if the // key does not exist in the file. func ReadConfig(in io.Reader) error { return v.ReadConfig(in) } func (v *Viper) ReadConfig(in io.Reader) error { v.config = make(map[string]interface{}) return v.unmarshalReader(in, v.config) } // MergeConfig merges a new configuration with an existing config. func MergeConfig(in io.Reader) error { return v.MergeConfig(in) } func (v *Viper) MergeConfig(in io.Reader) error { cfg := make(map[string]interface{}) if err := v.unmarshalReader(in, cfg); err != nil { return err } return v.MergeConfigMap(cfg) } // MergeConfigMap merges the configuration from the map given with an existing config. // Note that the map given may be modified. func MergeConfigMap(cfg map[string]interface{}) error { return v.MergeConfigMap(cfg) } func (v *Viper) MergeConfigMap(cfg map[string]interface{}) error { if v.config == nil { v.config = make(map[string]interface{}) } insensitiviseMap(cfg) mergeMaps(cfg, v.config, nil) return nil } // WriteConfig writes the current configuration to a file. func WriteConfig() error { return v.WriteConfig() } func (v *Viper) WriteConfig() error { filename, err := v.getConfigFile() if err != nil { return err } return v.writeConfig(filename, true) } // SafeWriteConfig writes current configuration to file only if the file does not exist. func SafeWriteConfig() error { return v.SafeWriteConfig() } func (v *Viper) SafeWriteConfig() error { if len(v.configPaths) < 1 { return errors.New("missing configuration for 'configPath'") } return v.SafeWriteConfigAs(filepath.Join(v.configPaths[0], v.configName+"."+v.configType)) } // WriteConfigAs writes current configuration to a given filename. func WriteConfigAs(filename string) error { return v.WriteConfigAs(filename) } func (v *Viper) WriteConfigAs(filename string) error { return v.writeConfig(filename, true) } // SafeWriteConfigAs writes current configuration to a given filename if it does not exist. func SafeWriteConfigAs(filename string) error { return v.SafeWriteConfigAs(filename) } func (v *Viper) SafeWriteConfigAs(filename string) error { alreadyExists, err := afero.Exists(v.fs, filename) if alreadyExists && err == nil { return ConfigFileAlreadyExistsError(filename) } return v.writeConfig(filename, false) } func (v *Viper) writeConfig(filename string, force bool) error { jww.INFO.Println("Attempting to write configuration to file.") var configType string ext := filepath.Ext(filename) if ext != "" { configType = ext[1:] } else { configType = v.configType } if configType == "" { return fmt.Errorf("config type could not be determined for %s", filename) } if !stringInSlice(configType, SupportedExts) { return UnsupportedConfigError(configType) } if v.config == nil { v.config = make(map[string]interface{}) } flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY if !force { flags |= os.O_EXCL } f, err := v.fs.OpenFile(filename, flags, v.configPermissions) if err != nil { return err } defer f.Close() if err := v.marshalWriter(f, configType); err != nil { return err } return f.Sync() } // Unmarshal a Reader into a map. // Should probably be an unexported function. func unmarshalReader(in io.Reader, c map[string]interface{}) error { return v.unmarshalReader(in, c) } func (v *Viper) unmarshalReader(in io.Reader, c map[string]interface{}) error { buf := new(bytes.Buffer) buf.ReadFrom(in) switch strings.ToLower(v.getConfigType()) { case "yaml", "yml": if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil { return ConfigParseError{err} } case "json": if err := json.Unmarshal(buf.Bytes(), &c); err != nil { return ConfigParseError{err} } case "hcl": obj, err := hcl.Parse(buf.String()) if err != nil { return ConfigParseError{err} } if err = hcl.DecodeObject(&c, obj); err != nil { return ConfigParseError{err} } case "toml": tree, err := toml.LoadReader(buf) if err != nil { return ConfigParseError{err} } tmap := tree.ToMap() for k, v := range tmap { c[k] = v } case "dotenv", "env": env, err := gotenv.StrictParse(buf) if err != nil { return ConfigParseError{err} } for k, v := range env { c[k] = v } case "properties", "props", "prop": v.properties = properties.NewProperties() var err error if v.properties, err = properties.Load(buf.Bytes(), properties.UTF8); err != nil { return ConfigParseError{err} } for _, key := range v.properties.Keys() { value, _ := v.properties.Get(key) // recursively build nested maps path := strings.Split(key, ".") lastKey := strings.ToLower(path[len(path)-1]) deepestMap := deepSearch(c, path[0:len(path)-1]) // set innermost value deepestMap[lastKey] = value } case "ini": cfg := ini.Empty() err := cfg.Append(buf.Bytes()) if err != nil { return ConfigParseError{err} } sections := cfg.Sections() for i := 0; i < len(sections); i++ { section := sections[i] keys := section.Keys() for j := 0; j < len(keys); j++ { key := keys[j] value := cfg.Section(section.Name()).Key(key.Name()).String() c[section.Name()+"."+key.Name()] = value } } } insensitiviseMap(c) return nil } // Marshal a map into Writer. func (v *Viper) marshalWriter(f afero.File, configType string) error { c := v.AllSettings() switch configType { case "json": b, err := json.MarshalIndent(c, "", " ") if err != nil { return ConfigMarshalError{err} } _, err = f.WriteString(string(b)) if err != nil { return ConfigMarshalError{err} } case "hcl": b, err := json.Marshal(c) if err != nil { return ConfigMarshalError{err} } ast, err := hcl.Parse(string(b)) if err != nil { return ConfigMarshalError{err} } err = printer.Fprint(f, ast.Node) if err != nil { return ConfigMarshalError{err} } case "prop", "props", "properties": if v.properties == nil { v.properties = properties.NewProperties() } p := v.properties for _, key := range v.AllKeys() { _, _, err := p.Set(key, v.GetString(key)) if err != nil { return ConfigMarshalError{err} } } _, err := p.WriteComment(f, "#", properties.UTF8) if err != nil { return ConfigMarshalError{err} } case "dotenv", "env": lines := []string{} for _, key := range v.AllKeys() { envName := strings.ToUpper(strings.Replace(key, ".", "_", -1)) val := v.Get(key) lines = append(lines, fmt.Sprintf("%v=%v", envName, val)) } s := strings.Join(lines, "\n") if _, err := f.WriteString(s); err != nil { return ConfigMarshalError{err} } case "toml": t, err := toml.TreeFromMap(c) if err != nil { return ConfigMarshalError{err} } s := t.String() if _, err := f.WriteString(s); err != nil { return ConfigMarshalError{err} } case "yaml", "yml": b, err := yaml.Marshal(c) if err != nil { return ConfigMarshalError{err} } if _, err = f.WriteString(string(b)); err != nil { return ConfigMarshalError{err} } case "ini": keys := v.AllKeys() cfg := ini.Empty() ini.PrettyFormat = false for i := 0; i < len(keys); i++ { key := keys[i] lastSep := strings.LastIndex(key, ".") sectionName := key[:(lastSep)] keyName := key[(lastSep + 1):] if sectionName == "default" { sectionName = "" } cfg.Section(sectionName).Key(keyName).SetValue(Get(key).(string)) } cfg.WriteTo(f) } return nil } func keyExists(k string, m map[string]interface{}) string { lk := strings.ToLower(k) for mk := range m { lmk := strings.ToLower(mk) if lmk == lk { return mk } } return "" } func castToMapStringInterface( src map[interface{}]interface{}) map[string]interface{} { tgt := map[string]interface{}{} for k, v := range src { tgt[fmt.Sprintf("%v", k)] = v } return tgt } func castMapStringToMapInterface(src map[string]string) map[string]interface{} { tgt := map[string]interface{}{} for k, v := range src { tgt[k] = v } return tgt } func castMapFlagToMapInterface(src map[string]FlagValue) map[string]interface{} { tgt := map[string]interface{}{} for k, v := range src { tgt[k] = v } return tgt } // mergeMaps merges two maps. The `itgt` parameter is for handling go-yaml's // insistence on parsing nested structures as `map[interface{}]interface{}` // instead of using a `string` as the key for nest structures beyond one level // deep. Both map types are supported as there is a go-yaml fork that uses // `map[string]interface{}` instead. func mergeMaps( src, tgt map[string]interface{}, itgt map[interface{}]interface{}) { for sk, sv := range src { tk := keyExists(sk, tgt) if tk == "" { jww.TRACE.Printf("tk=\"\", tgt[%s]=%v", sk, sv) tgt[sk] = sv if itgt != nil { itgt[sk] = sv } continue } tv, ok := tgt[tk] if !ok { jww.TRACE.Printf("tgt[%s] != ok, tgt[%s]=%v", tk, sk, sv) tgt[sk] = sv if itgt != nil { itgt[sk] = sv } continue } svType := reflect.TypeOf(sv) tvType := reflect.TypeOf(tv) if svType != tvType { jww.ERROR.Printf( "svType != tvType; key=%s, st=%v, tt=%v, sv=%v, tv=%v", sk, svType, tvType, sv, tv) continue } jww.TRACE.Printf("processing key=%s, st=%v, tt=%v, sv=%v, tv=%v", sk, svType, tvType, sv, tv) switch ttv := tv.(type) { case map[interface{}]interface{}: jww.TRACE.Printf("merging maps (must convert)") tsv := sv.(map[interface{}]interface{}) ssv := castToMapStringInterface(tsv) stv := castToMapStringInterface(ttv) mergeMaps(ssv, stv, ttv) case map[string]interface{}: jww.TRACE.Printf("merging maps") mergeMaps(sv.(map[string]interface{}), ttv, nil) default: jww.TRACE.Printf("setting value") tgt[tk] = sv if itgt != nil { itgt[tk] = sv } } } } // ReadRemoteConfig attempts to get configuration from a remote source // and read it in the remote configuration registry. func ReadRemoteConfig() error { return v.ReadRemoteConfig() } func (v *Viper) ReadRemoteConfig() error { return v.getKeyValueConfig() } func WatchRemoteConfig() error { return v.WatchRemoteConfig() } func (v *Viper) WatchRemoteConfig() error { return v.watchKeyValueConfig() } func WatchRemoteConfigOnChannel() error { return v.WatchRemoteConfigOnChannel() } func (v *Viper) WatchRemoteConfigOnChannel() error { return v.watchKeyValueConfigOnChannel() } // Retrieve the first found remote configuration. func (v *Viper) getKeyValueConfig() error { if RemoteConfig == nil { return RemoteConfigError("Enable the remote features by doing a blank import of the viper/remote package: '_ github.com/kklinan/viper/remote'") } for _, rp := range v.remoteProviders { val, err := v.getRemoteConfig(rp) if err != nil { continue } v.kvstore = val return nil } return RemoteConfigError("No Files Found") } func (v *Viper) getRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) { reader, err := RemoteConfig.Get(provider) if err != nil { return nil, err } err = v.unmarshalReader(reader, v.kvstore) return v.kvstore, err } // Retrieve the first found remote configuration. func (v *Viper) watchKeyValueConfigOnChannel() error { for _, rp := range v.remoteProviders { respc, _ := RemoteConfig.WatchChannel(rp) // Todo: Add quit channel go func(rc <-chan *RemoteResponse) { for { b := <-rc reader := bytes.NewReader(b.Value) v.unmarshalReader(reader, v.kvstore) } }(respc) return nil } return RemoteConfigError("No Files Found") } // Retrieve the first found remote configuration. func (v *Viper) watchKeyValueConfig() error { for _, rp := range v.remoteProviders { val, err := v.watchRemoteConfig(rp) if err != nil { continue } v.kvstore = val return nil } return RemoteConfigError("No Files Found") } func (v *Viper) watchRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) { reader, err := RemoteConfig.Watch(provider) if err != nil { return nil, err } err = v.unmarshalReader(reader, v.kvstore) return v.kvstore, err } // AllKeys returns all keys holding a value, regardless of where they are set. // Nested keys are returned with a v.keyDelim separator func AllKeys() []string { return v.AllKeys() } func (v *Viper) AllKeys() []string { m := map[string]bool{} // add all paths, by order of descending priority to ensure correct shadowing m = v.flattenAndMergeMap(m, castMapStringToMapInterface(v.aliases), "") m = v.flattenAndMergeMap(m, v.override, "") m = v.mergeFlatMap(m, castMapFlagToMapInterface(v.pflags)) m = v.mergeFlatMap(m, castMapStringToMapInterface(v.env)) m = v.flattenAndMergeMap(m, v.config, "") m = v.flattenAndMergeMap(m, v.kvstore, "") m = v.flattenAndMergeMap(m, v.defaults, "") // convert set of paths to list a := make([]string, 0, len(m)) for x := range m { a = append(a, x) } return a } // flattenAndMergeMap recursively flattens the given map into a map[string]bool // of key paths (used as a set, easier to manipulate than a []string): // - each path is merged into a single key string, delimited with v.keyDelim // - if a path is shadowed by an earlier value in the initial shadow map, // it is skipped. // The resulting set of paths is merged to the given shadow set at the same time. func (v *Viper) flattenAndMergeMap(shadow map[string]bool, m map[string]interface{}, prefix string) map[string]bool { if shadow != nil && prefix != "" && shadow[prefix] { // prefix is shadowed => nothing more to flatten return shadow } if shadow == nil { shadow = make(map[string]bool) } var m2 map[string]interface{} if prefix != "" { prefix += v.keyDelim } for k, val := range m { fullKey := prefix + k switch val.(type) { case map[string]interface{}: m2 = val.(map[string]interface{}) case map[interface{}]interface{}: m2 = cast.ToStringMap(val) default: // immediate value shadow[strings.ToLower(fullKey)] = true continue } // recursively merge to shadow map shadow = v.flattenAndMergeMap(shadow, m2, fullKey) } return shadow } // mergeFlatMap merges the given maps, excluding values of the second map // shadowed by values from the first map. func (v *Viper) mergeFlatMap(shadow map[string]bool, m map[string]interface{}) map[string]bool { // scan keys outer: for k := range m { path := strings.Split(k, v.keyDelim) // scan intermediate paths var parentKey string for i := 1; i < len(path); i++ { parentKey = strings.Join(path[0:i], v.keyDelim) if shadow[parentKey] { // path is shadowed, continue continue outer } } // add key shadow[strings.ToLower(k)] = true } return shadow } // AllSettings merges all settings and returns them as a map[string]interface{}. func AllSettings() map[string]interface{} { return v.AllSettings() } func (v *Viper) AllSettings() map[string]interface{} { m := map[string]interface{}{} // start from the list of keys, and construct the map one value at a time for _, k := range v.AllKeys() { value := v.Get(k) if value == nil { // should not happen, since AllKeys() returns only keys holding a value, // check just in case anything changes continue } path := strings.Split(k, v.keyDelim) lastKey := strings.ToLower(path[len(path)-1]) deepestMap := deepSearch(m, path[0:len(path)-1]) // set innermost value deepestMap[lastKey] = value } return m } // SetFs sets the filesystem to use to read configuration. func SetFs(fs afero.Fs) { v.SetFs(fs) } func (v *Viper) SetFs(fs afero.Fs) { v.fs = fs } // SetConfigName sets name for the config file. // Does not include extension. func SetConfigName(in string) { v.SetConfigName(in) } func (v *Viper) SetConfigName(in string) { if in != "" { v.configName = in v.configFile = "" } } // SetConfigType sets the type of the configuration returned by the // remote source, e.g. "json". func SetConfigType(in string) { v.SetConfigType(in) } func (v *Viper) SetConfigType(in string) { if in != "" { v.configType = in } } // SetConfigPermissions sets the permissions for the config file. func SetConfigPermissions(perm os.FileMode) { v.SetConfigPermissions(perm) } func (v *Viper) SetConfigPermissions(perm os.FileMode) { v.configPermissions = perm.Perm() } func (v *Viper) getConfigType() string { if v.configType != "" { return v.configType } cf, err := v.getConfigFile() if err != nil { return "" } ext := filepath.Ext(cf) if len(ext) > 1 { return ext[1:] } return "" } func (v *Viper) getConfigFile() (string, error) { if v.configFile == "" { cf, err := v.findConfigFile() if err != nil { return "", err } v.configFile = cf } return v.configFile, nil } func (v *Viper) searchInPath(in string) (filename string) { jww.DEBUG.Println("Searching for config in ", in) for _, ext := range SupportedExts { jww.DEBUG.Println("Checking for", filepath.Join(in, v.configName+"."+ext)) if b, _ := exists(v.fs, filepath.Join(in, v.configName+"."+ext)); b { jww.DEBUG.Println("Found: ", filepath.Join(in, v.configName+"."+ext)) return filepath.Join(in, v.configName+"."+ext) } } if v.configType != "" { if b, _ := exists(v.fs, filepath.Join(in, v.configName)); b { return filepath.Join(in, v.configName) } } return "" } // Search all configPaths for any config file. // Returns the first path that exists (and is a config file). func (v *Viper) findConfigFile() (string, error) { jww.INFO.Println("Searching for config in ", v.configPaths) for _, cp := range v.configPaths { file := v.searchInPath(cp) if file != "" { return file, nil } } return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)} } // Debug prints all configuration registries for debugging // purposes. func Debug() { v.Debug() } func (v *Viper) Debug() { fmt.Printf("Aliases:\n%#v\n", v.aliases) fmt.Printf("Override:\n%#v\n", v.override) fmt.Printf("PFlags:\n%#v\n", v.pflags) fmt.Printf("Env:\n%#v\n", v.env) fmt.Printf("Key/Value Store:\n%#v\n", v.kvstore) fmt.Printf("Config:\n%#v\n", v.config) fmt.Printf("Defaults:\n%#v\n", v.defaults) }
[]
[]
[]
[]
[]
go
0
0
manage.py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ida_images.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: 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?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
[]
[]
[]
[]
[]
python
0
0
service/jwt-svc.go
package service import ( "fmt" "os" "time" "github.com/dgrijalva/jwt-go" ) type JWTService interface { GenerateToken(name string, user bool) string ValidateToken(token string) (*jwt.Token, error) } type jwtClaim struct { Name string `json:"name"` Admin bool `json:"admin"` jwt.StandardClaims } type jwtService struct { secretKey string issuer string } func NewJWTService() JWTService { return &jwtService{ secretKey: getSecretKey(), issuer: "robert", } } func getSecretKey() string { secret := os.Getenv("JWT_SECRET") if len(secret) == 0 { secret = "diptochuck" } return secret } func (jwtsvc *jwtService) GenerateToken(username string, user bool) string { claims := &jwtClaim{ username, user, jwt.StandardClaims{ ExpiresAt: time.Now().Add(time.Hour * 72).Unix(), Issuer: jwtsvc.issuer, IssuedAt: time.Now().Unix(), }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) tokenSign, err := token.SignedString([]byte(jwtsvc.secretKey)) if err != nil { panic(err) } return tokenSign } func (jwtsvc *jwtService) ValidateToken(token string) (*jwt.Token, error) { return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) { if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("incorrect SignIn Method: %v", t.Header["alg"]) } return []byte(jwtsvc.secretKey), nil }) }
[ "\"JWT_SECRET\"" ]
[]
[ "JWT_SECRET" ]
[]
["JWT_SECRET"]
go
1
0
manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_uuid_primary_key.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: 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?" ) from exc execute_from_command_line(sys.argv)
[]
[]
[]
[]
[]
python
0
0
examples/client/main.go
package main import ( "context" "io/ioutil" "log" "net/http" "os" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.7.0" "go.opentelemetry.io/otel/trace" ) // Initializes an OTLP exporter, and configures the corresponding trace and // metric providers. func initProvider() func() { ctx := context.Background() res, err := resource.New(ctx, resource.WithAttributes( // the service name used to display traces in backends semconv.ServiceNameKey.String("test-client"), ), ) handleErr(err, "failed to create resource") // If the OpenTelemetry Collector is running on a local cluster (minikube or // microk8s), it should be accessible through the NodePort service at the // `localhost:30080` endpoint. Otherwise, replace `localhost` with the // endpoint of your cluster. If you run the app inside k8s, then you can // probably connect directly to the service through dns // Set up a trace exporter traceExporter, err := otlptracehttp.New(ctx, otlptracehttp.WithEndpoint("otel-collector:4317"), otlptracehttp.WithInsecure(), otlptracehttp.WithHeaders(map[string]string{ "Content-Type": "application/json", })) handleErr(err, "failed to create trace exporter") // Register the trace exporter with a TracerProvider, using a batch // span processor to aggregate spans before export. bsp := sdktrace.NewBatchSpanProcessor(traceExporter) tracerProvider := sdktrace.NewTracerProvider( sdktrace.WithSampler(sdktrace.AlwaysSample()), sdktrace.WithResource(res), sdktrace.WithSpanProcessor(bsp), ) otel.SetTracerProvider(tracerProvider) // set global propagator to tracecontext (the default is no-op). otel.SetTextMapPropagator(propagation.TraceContext{}) return func() { // Shutdown will flush any remaining spans and shut down the exporter. handleErr(tracerProvider.Shutdown(ctx), "failed to shutdown TracerProvider") } } func main() { shutdown := initProvider() defer shutdown() tracer := otel.Tracer("test-client-tracer") ctx, span := tracer.Start(context.Background(), "test-client-span", trace.WithSpanKind(trace.SpanKindClient)) defer span.End() span.SetStatus(codes.Error, "client side failed") req, err := http.NewRequest("GET", os.Getenv("PROXY_ENDPOINT"), nil) handleErr(err, "new request fail") propagation.TraceContext{}.Inject(ctx, propagation.HeaderCarrier(req.Header)) rsp, err := http.DefaultClient.Do(req) handleErr(err, "request fail") body, err := ioutil.ReadAll(rsp.Body) handleErr(err, "read body fail") log.Println(string(body)) _ = rsp.Body.Close() } func handleErr(err error, message string) { if err != nil { log.Fatalf("%s: %v", message, err) } }
[ "\"PROXY_ENDPOINT\"" ]
[]
[ "PROXY_ENDPOINT" ]
[]
["PROXY_ENDPOINT"]
go
1
0
python/paddle/fluid/contrib/sparsity/asp.py
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2021 NVIDIA Corporation. 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. """ Functions for Auto SParsity (ASP) training and inference. """ import os import copy import numpy as np import paddle from paddle.fluid import global_scope, program_guard, layers from paddle.fluid.initializer import ConstantInitializer from paddle.fluid.contrib import sparsity from paddle.fluid import core OpRole = core.op_proto_and_checker_maker.OpRole OP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName() __all__ = [ 'decorate', 'prune_model', 'set_excluded_layers', 'reset_excluded_layers' ] def set_excluded_layers(main_program, param_names): r""" Set parameter name of layers which would not be pruned as sparse weights. Args: main_program (Program, optional): Program with model definition and its parameters. param_names (list): A list contains names of parameters. Examples: .. code-block:: python import paddle from paddle.static import sparsity paddle.enable_static() main_program = paddle.static.Program() startup_program = paddle.static.Program() with paddle.static.program_guard(main_program, startup_program): input_data = paddle.static.data(name='data', shape=[None, 128]) label = paddle.static.data(name='label', shape=[None, 10]) hidden = paddle.static.nn.fc(x=input_data, num_flatten_dims=-1, size=32, activation=None, name="need_sparse_fc") hidden = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=32, activation=None, name="need_dense_fc") prob = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=10, activation=None) loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label)) # Setup exluded layers out from ASP workflow. # Please note, excluded_layers must be set before calling `optimizer.minimize()`. sparsity.set_excluded_layers(main_program, ["need_dense_fc"]) optimizer = paddle.optimizer.SGD(learning_rate=0.1) optimizer = paddle.static.amp.decorate(optimizer ) # Calling sparsity.decorate() to wrap minimize() in optimizer, which # will insert necessary masking operations for ASP workflow. optimizer = sparsity.decorate(optimizer) optimizer.minimize(loss, startup_program) """ ASPHelper.set_excluded_layers( main_program=main_program, param_names=param_names) def reset_excluded_layers(main_program=None): r""" Reset exculded layers setting corresponding to :attr:`main_program`. If :attr:`main_program` is None, then all configurations of excluded_layers would be cleaned. Args: main_program (Program, optional): Program with model definition and its parameters. Examples: .. code-block:: python import paddle from paddle.static import sparsity paddle.enable_static() main_program = paddle.static.Program() startup_program = paddle.static.Program() with paddle.static.program_guard(main_program, startup_program): input_data = paddle.static.data(name='data', shape=[None, 128]) label = paddle.static.data(name='label', shape=[None, 10]) hidden = paddle.static.nn.fc(x=input_data, num_flatten_dims=-1, size=32, activation=None, name="my_first_fc") hidden = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=32, activation=None, name="my_second_fc") prob = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=10, activation=None) loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label)) # Setup exluded layers out from ASP workflow. # Please note, excluded_layers must be set before calling `optimizer.minimize()`. sparsity.set_excluded_layers(main_program, ["my_second_fc"]) # Now the weights of "my_second_fc" would not be included in Automatic SParsity's workflow. # Reset excluded_layers, all FC layers would be included into Automatic SParsity's workflow. # Please note, reset_excluded_layers also must be called before calling `optimizer.minimize()`. sparsity.reset_excluded_layers(main_program) """ ASPHelper.reset_excluded_layers(main_program=main_program) def decorate(optimizer): r""" Wrap the given optimizer as a OptimizerWithSparsityGuarantee, which would insert necessary ops for ASP workflows when calling minimize() Args: optimizer (Optimizer): A Optimizer used for training. Returns: OptimizerWithSparsityGuarantee: A wrapper for ASP to decorate `minimize` function of the given optimizer. Examples: .. code-block:: python import paddle from paddle.static import sparsity main_program = paddle.static.Program() startup_program = paddle.static.Program() paddle.enable_static() with paddle.static.program_guard(main_program, startup_program): input_data = paddle.static.data(name='data', shape=[None, 128]) label = paddle.static.data(name='label', shape=[None, 10]) hidden = paddle.static.nn.fc(x=input_data, num_flatten_dims=-1, size=32, activation=None) prob = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=10, activation=None) loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label)) optimizer = paddle.optimizer.SGD(learning_rate=0.1) optimizer = sparsity.decorate(optimizer) # if do sparse training with Fleet, please replace above decorate with: # strategy = paddle.distributed.fleet.DistributedStrategy() # strategy.asp = True # optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy) optimizer.minimize(loss, startup_program) """ return ASPHelper.decorate(optimizer) def prune_model(main_program=None, n=2, m=4, mask_algo='mask_1d', with_mask=True): r""" Pruning parameters of supported layers in :attr:`main_program` via specified mask generation function given by :attr:`mask_algo`. This function supports both training and inference controlled by :attr:`with_mask`. If :attr:`with_mask` is True, it would also prune parameter related ASP mask Variables, else only prunes parameters. *Note*: If parameters are supported and in FP16, please set :attr:`n`=2, :attr:`m`=4, if they in FP32, then :attr:`n`=1, :attr:`m`=2` to further enable Sparse Tensor Core acceleration. *Note*: If calling this function with :attr:`with_mask`, it should call `OptimizerWithSparsityGuarantee.minimize` and initialization (`exe.run(startup_program`)) before (For successfully obtain mask Variable). Typically set `with_mask` as true for training (have called `OptimizerWithSparsityGuarantee.minimize`) and false for inference only. To obtain OptimizerWithSparsityGuarantee, please see `sparsity.decoreate()`. Args: main_program (Program, optional): Program with model definition and its parameters. Default is `paddle.static.default_main_program() n (int): n of `n:m` sparse pattern. m (int): m of `n:m` sparse pattern. mask_algo (string, optional): The function name to generate spase mask. Default is `mask_1d`. The vaild inputs should be one of 'mask_1d', 'mask_2d_greedy' and 'mask_2d_best'. with_mask (bool, optional): To prune mask Variables related to parameters or not. Ture is purning also, False is not. Defalut is True. Returns: dictionary: A dictionary with key: `parameter name` (string) and value: its corresponding mask Variable. Examples: .. code-block:: python import paddle from paddle.static import sparsity paddle.enable_static() main_program = paddle.static.Program() startup_program = paddle.static.Program() with paddle.static.program_guard(main_program, startup_program): input_data = paddle.static.data(name='data', shape=[None, 128]) label = paddle.static.data(name='label', shape=[None, 10]) hidden = paddle.static.nn.fc(x=input_data, num_flatten_dims=-1, size=32, activation=None, name="need_sparse_fc") hidden = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=32, activation=None, name="need_dense_fc") prob = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=10, activation=None) loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label)) # Setup exluded layers out from ASP workflow. # Please note, excluded_layers must be set before calling `optimizer.minimize()`. sparsity.set_excluded_layers(main_program, ["need_dense_fc"]) optimizer = paddle.optimizer.SGD(learning_rate=0.1) optimizer = paddle.static.amp.decorate(optimizer ) # Calling sparsity.decorate() to wrap minimize() in optimizer, which # will insert necessary masking operations for ASP workflow. optimizer = sparsity.decorate(optimizer) optimizer.minimize(loss, startup_program) device = paddle.device.get_device() place = paddle.set_device(device) exe = paddle.static.Executor(place) exe.run(startup_program) # Must call `exe.run(startup_program)` first before calling `sparsity.prune_model` sparsity.prune_model(main_program, mask_algo='mask_2d_best') """ if main_program is not None and hasattr( main_program, "distributed_info_") and main_program.distributed_info_[ "sharding_degree"] > 1 and paddle.fluid.is_compiled_with_cuda(): gpu_id = int(os.environ.get('FLAGS_selected_gpus', 0)) place = paddle.CUDAPlace(gpu_id) else: device = paddle.device.get_device() place = paddle.set_device(device) MaskAlgo_mapping = { 'mask_1d': sparsity.MaskAlgo.MASK_1D, 'mask_2d_greedy': sparsity.MaskAlgo.MASK_2D_GREEDY, 'mask_2d_best': sparsity.MaskAlgo.MASK_2D_BEST } assert (mask_algo in MaskAlgo_mapping), \ 'The "mask_algo" should be one of ["mask_1d", "mask_2d_greedy", "mask_2d_best"]' return ASPHelper.prune_model( place=place, main_program=main_program, n=n, m=m, mask_algo=MaskAlgo_mapping[mask_algo], with_mask=with_mask) class ProgramASPInfo(object): r""" ProgramASPInfo is a container to keep ASP relevant information of Pragrom. It contains three inner-variables: 1. __mask_vars (Dictionary): Key is parameter's name and vaule is its corresponding sparse mask Variable object, which is created by `ASPHelper.create_mask_variables`. 2. __masks (Dictionary): Key is parameter's name and vaule is its corressponding sparse mask Numpy array, which is created by `ASPHelper.prune_model`. 3. __excluded_layers (List): It stores name of layers which should not involve into ASP workflow. """ def __init__(self): self.__mask_vars = {} self.__masks = {} self.__excluded_layers = [] def update_mask_vars(self, param_name, var): self.__mask_vars[param_name] = var def update_masks(self, param_name, var): self.__masks[param_name] = var def update_excluded_layers(self, param_names): self.__excluded_layers.extend(copy.deepcopy(param_names)) def reset_excluded_layers(self): self.__excluded_layers = [] @property def mask_vars(self): return self.__mask_vars @property def masks(self): return self.__masks @property def excluded_layers(self): return self.__excluded_layers class ASPHelper(object): r""" ASPHelper is a collection of Auto SParsity (ASP) functions to enable 1. training models with weights in 2:4 sparse pattern on FP16 or 1:2 sparse pattern on FP32 from scratch. 2. pruning well-trained models into 2:4 sparse pattern on FP16 or 1:2 sparse pattern on FP32 for fine-tuning. """ MASK_APPENDDED_NAME = '_asp_mask' SUPPORTED_LAYERS = {'fc': 'w_0', 'linear': 'w_0', 'conv2d': 'w_0'} __asp_info = {} @classmethod def set_excluded_layers(cls, main_program, param_names): r""" This is the implementation of `sparsity.set_excluded_layers`, for details please see explanation in `sparsity.set_excluded_layers`. """ asp_info = cls._get_program_asp_info(main_program) asp_info.update_excluded_layers(param_names) @classmethod def reset_excluded_layers(cls, main_program=None): r""" This is the implementation of `sparsity.reset_excluded_layers`, for details please see explanation in `sparsity.reset_excluded_layers`. """ if main_program is None: for asp_info in cls.__asp_info: asp_info.reset_excluded_layers() else: cls._get_program_asp_info(main_program).reset_excluded_layers() @staticmethod def decorate(optimizer): r""" This is the implementation of `sparsity.decorate`, for details please see explanation in `sparsity.decorate`. """ return OptimizerWithSparsityGuarantee(optimizer) @classmethod def prune_model(cls, place, main_program=None, n=2, m=4, mask_algo=sparsity.MaskAlgo.MASK_1D, with_mask=True): r""" This is the implementation of `sparsity.prune_model`, for details please see explanation in `sparsity.prune_model`. """ checked_func_name = sparsity.CheckMethod.get_checking_method(mask_algo) if main_program is None: main_program = paddle.static.default_main_program() asp_info = cls._get_program_asp_info(main_program) for param in main_program.global_block().all_parameters(): if ASPHelper._is_supported_layer(main_program, param.name): weight_tensor = global_scope().find_var(param.name).get_tensor() weight_nparray = np.array(weight_tensor) # The double transpose ops here make sure pruning direction consistent with cuSparseLt. # SPMMA in cuSparseLt: D = (AxB) + C, where matrix A (mxk) is sparse matrix. # cuSparseLt would prune matrix A along k dimension. # In sparse training, layer weight matriices is viewed sparse matrix A, so # the math fomula should be 'Act(WX + b)'. However, default fomula in PaddlePaddle # is 'Act(XW + b)'. For enabling SPMMA, weights and inputs should be transposed # for computing, Act( (W^T X^T)^T + b). Therefore, we have to prune alog k dimension # of W^T, which is m dimension of W. Moreove, all mask generating functions in # sparsity/utils is row-major pruning. That is the reason we have to transpose weight # matrices beforce invoking create_mask. Then we transpose the result maks to make # sure its shape to be the same as the input weight. weight_sparse_mask = sparsity.create_mask( weight_nparray.T, func_name=mask_algo, n=n, m=m).T weight_pruned_nparray = np.multiply(weight_nparray, weight_sparse_mask) weight_tensor.set(weight_pruned_nparray, place) assert sparsity.check_sparsity(weight_pruned_nparray.T, n=n, m=m, func_name=checked_func_name), \ 'Pruning {} weight matrix failure!!!'.format(param.name) if with_mask: weight_mask_param = global_scope().find_var( ASPHelper._get_mask_name(param.name)) assert weight_mask_param is not None, \ 'Cannot find {} variable, please call ASPHelper.minimize' \ ' and initialization (exe.run(startup_program)) first!'.format(ASPHelper._get_mask_name(param.name)) weight_mask_tensor = weight_mask_param.get_tensor() weight_mask_tensor.set(weight_sparse_mask, place) asp_info.update_masks(param.name, weight_sparse_mask) return asp_info.masks.copy() @staticmethod def _get_mask_name(param_name): r""" Return mask name by given parameter name :attr:`param_name`. Args: param_name (string): The name of parameter. Returns: string: The mask name of :attr:`param_name`. """ return param_name + ASPHelper.MASK_APPENDDED_NAME @staticmethod def _get_not_ASP_relevant_vars(main_program): r""" Get all parameters's Variables in :attr:`main_program` but excluded ASP mask Variables. Args: main_program (Program): Program with model definition and its parameters. Returns: list: A list of parameter Variables in :attr:`main_program` (excluded ASP mask Variables). """ var_list = [] for param in main_program.global_block().all_parameters(): if ASPHelper.MASK_APPENDDED_NAME not in param.name: var_list.append(param) return var_list @classmethod def _get_program_asp_info(cls, main_program): if not main_program in cls.__asp_info: cls.__asp_info[main_program] = ProgramASPInfo() return cls.__asp_info[main_program] @classmethod def _is_supported_layer(cls, main_program, param_name): r""" Verify if given :attr:`param_name` is supported by ASP. Args: param_name (string): The name of parameter. Returns: bool: True if it is supported, else False. Examples: .. code-block:: python from paddle.static.sparsity.asp import ASPHelper main_program = paddle.static.Program() startup_program = paddle.static.Program() with paddle.static.program_guard(main_program, startup_program): input_data = paddle.static.data(name='data', shape=[None, 128]) fc = paddle.static.nn.fc(x=input_data, num_flatten_dims=-1, size=32, activation=None) for param in main_program.global_block().all_parameters(): ASPHelper._is_supported_layer(main_program, param.name) # fc_0.w_0 -> True # fc_0.b_0 -> False """ if ASPHelper.MASK_APPENDDED_NAME in param_name: return False for layer in cls._get_program_asp_info(main_program).excluded_layers: if layer in param_name: return False for name in ASPHelper.SUPPORTED_LAYERS: if name in param_name and \ ASPHelper.SUPPORTED_LAYERS[name] in param_name: return True return False @classmethod def _minimize(cls, optimizer, loss, main_program=None, startup_program=None, parameter_list=None, no_grad_set=None): r""" This function is a decorator of `minimize` function in `Optimizer`. There are three steps: 1. Call :attr:`optimizer`.minimize(:attr:`loss`) 2. Create sparse mask Tensors according to supported layers in :attr:`main_program`. 3. Insert masking ops in the end of parameters update. *Note*: Please use `ASP.decorate` instead when applying distributed training with `Fleet`. (Due to there is a invisiable graphs optimization in `Fleet.minimize()` which make training graph cannot be modified anymore.) Args: optimizer (Optimizer): A Optimizer used for training. loss (Variable): A Variable containing the value to minimize. main_program (Program, optional): Program with model definition and its parameters. Default is `loss.block.program`. startup_program (Program, optional): Program for initializing parameters in `parameter_list`. Default is `paddle.static.default_startup_program()`. parameter_list (Iterable, optional): Iterable of `Variable` or `Variable.name` to update to minimize `loss`. The default value is None, at this time all parameters will be updated. no_grad_set (set, optional): Set of `Variable or `Variable.name` that don't need to be updated. The default value is None. Returns: list: operators from :attr:`optimizer`.minimize(:attr:`loss`). list: pairs of parameters and their gradients. """ if main_program is None: main_program = loss.block.program if startup_program is None: startup_program = paddle.static.default_startup_program() optimizer_ops, params_and_grads = optimizer.minimize( loss, startup_program, parameter_list, no_grad_set=no_grad_set) cls._create_mask_variables(main_program, startup_program, params_and_grads) cls._insert_sparse_mask_ops(main_program, params_and_grads) return optimizer_ops, params_and_grads @classmethod def _create_mask_variables(cls, main_program, startup_program, params_and_grads): r""" Create sparse mask Tensors according to supported layers in :attr:`main_program`. This function is called in second step of `ASPHelper._minimize` Args: main_program (Program): Program with model definition and its parameters. startup_program (Program): Program for initializing parameters. params_and_grads (list): Variable pairs of parameters and their gradients. """ asp_info = cls._get_program_asp_info(main_program) with program_guard(main_program, startup_program): for param_and_grad in params_and_grads: if ASPHelper._is_supported_layer(main_program, param_and_grad[0].name): mask_param = layers.create_parameter( name=param_and_grad[0].name + ASPHelper.MASK_APPENDDED_NAME, shape=param_and_grad[0].shape, dtype=param_and_grad[0].dtype, default_initializer=ConstantInitializer(value=1.0)) mask_param.stop_gradient = True mask_param.trainable = False asp_info.update_mask_vars(param_and_grad[0].name, mask_param) @classmethod def _insert_sparse_mask_ops(cls, main_program, param_grads): r""" Insert masking ops in the end of parameters update. This function is called in third step of `ASPHelper._minimize` Args: main_program (Program): Program with model definition and its parameters. params_and_grads (list): Variable pairs of parameters and their gradients. """ block = main_program.global_block() asp_info = cls._get_program_asp_info(main_program) for param_grad in param_grads: if param_grad[0].name in asp_info.mask_vars: block.append_op( type='elementwise_mul', inputs={ "X": param_grad[0], 'Y': asp_info.mask_vars[param_grad[0].name] }, outputs={'Out': param_grad[0]}, attrs={ 'axis': -1, 'use_mkldnn': False, OP_ROLE_KEY: OpRole.Optimize }) class OptimizerWithSparsityGuarantee(object): r""" OptimizerWithSparsityGuarantee is a wrapper to decorate `minimize` function of given optimizer by `_minimize` of ASPHelper. The decorated `minimize` function would do three things (exactly same as `ASPHelper._minimize`): 1. Call `minimize` function of given optimizer. 2. Call `ASPHelper._create_mask_variables` to create mask Variables. 3. Call `ASPHelper._insert_sparse_mask_ops` to insert weight masking ops in the end of `loss`'s Program. """ def __init__(self, optimizer): self._optimizer = optimizer self._learning_rate = optimizer._learning_rate self._learning_rate_map = optimizer._learning_rate_map def minimize(self, loss, startup_program=None, parameter_list=None, no_grad_set=None): r""" This function is to call `ASPHelper.minimize()` and return its return Args: loss (Variable): A Variable containing the value to minimize. startup_program (Program, optional): Program for initializing parameters in `parameter_list`. Default is `paddle.static.default_startup_program()`. parameter_list (Iterable, optional): Iterable of `Variable` or `Variable.name` to update to minimize `loss`. The default value is None, at this time all parameters will be updated. no_grad_set (set, optional): Set of `Variable or `Variable.name` that don't need to be updated. The default value is None. Returns: list: operators from :attr:`optimizer`.minimize(:attr:`loss`). list: pairs of parameters and their gradients. """ return ASPHelper._minimize( self._optimizer, loss, startup_program=startup_program, parameter_list=parameter_list, no_grad_set=no_grad_set)
[]
[]
[ "FLAGS_selected_gpus" ]
[]
["FLAGS_selected_gpus"]
python
1
0
vertical-pod-autoscaler/e2e/vendor/k8s.io/kubernetes/pkg/security/apparmor/validate.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 apparmor import ( "bufio" "errors" "fmt" "io/ioutil" "os" "path" "strings" v1 "k8s.io/api/core/v1" utilfeature "k8s.io/apiserver/pkg/util/feature" podutil "k8s.io/kubernetes/pkg/api/v1/pod" "k8s.io/kubernetes/pkg/features" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" utilpath "k8s.io/utils/path" ) // Whether AppArmor should be disabled by default. // Set to true if the wrong build tags are set (see validate_disabled.go). var isDisabledBuild bool // Validator is a interface for validating that a pod with an AppArmor profile can be run by a Node. type Validator interface { Validate(pod *v1.Pod) error ValidateHost() error } // NewValidator is in order to find AppArmor FS func NewValidator(runtime string) Validator { if err := validateHost(runtime); err != nil { return &validator{validateHostErr: err} } appArmorFS, err := getAppArmorFS() if err != nil { return &validator{ validateHostErr: fmt.Errorf("error finding AppArmor FS: %v", err), } } return &validator{ appArmorFS: appArmorFS, } } type validator struct { validateHostErr error appArmorFS string } func (v *validator) Validate(pod *v1.Pod) error { if !isRequired(pod) { return nil } if v.ValidateHost() != nil { return v.validateHostErr } loadedProfiles, err := v.getLoadedProfiles() if err != nil { return fmt.Errorf("could not read loaded profiles: %v", err) } var retErr error podutil.VisitContainers(&pod.Spec, podutil.AllContainers, func(container *v1.Container, containerType podutil.ContainerType) bool { retErr = validateProfile(GetProfileName(pod, container.Name), loadedProfiles) if retErr != nil { return false } return true }) return retErr } func (v *validator) ValidateHost() error { return v.validateHostErr } // Verify that the host and runtime is capable of enforcing AppArmor profiles. func validateHost(runtime string) error { // Check feature-gates if !utilfeature.DefaultFeatureGate.Enabled(features.AppArmor) { return errors.New("AppArmor disabled by feature-gate") } // Check build support. if isDisabledBuild { return errors.New("binary not compiled for linux") } // Check kernel support. if !IsAppArmorEnabled() { return errors.New("AppArmor is not enabled on the host") } // Check runtime support. Currently only Docker is supported. if runtime != kubetypes.DockerContainerRuntime && runtime != kubetypes.RemoteContainerRuntime { return fmt.Errorf("AppArmor is only enabled for 'docker' and 'remote' runtimes. Found: %q", runtime) } return nil } // Verify that the profile is valid and loaded. func validateProfile(profile string, loadedProfiles map[string]bool) error { if err := ValidateProfileFormat(profile); err != nil { return err } if strings.HasPrefix(profile, v1.AppArmorBetaProfileNamePrefix) { profileName := strings.TrimPrefix(profile, v1.AppArmorBetaProfileNamePrefix) if !loadedProfiles[profileName] { return fmt.Errorf("profile %q is not loaded", profileName) } } return nil } // ValidateProfileFormat checks the format of the profile. func ValidateProfileFormat(profile string) error { if profile == "" || profile == v1.AppArmorBetaProfileRuntimeDefault || profile == v1.AppArmorBetaProfileNameUnconfined { return nil } if !strings.HasPrefix(profile, v1.AppArmorBetaProfileNamePrefix) { return fmt.Errorf("invalid AppArmor profile name: %q", profile) } return nil } func (v *validator) getLoadedProfiles() (map[string]bool, error) { profilesPath := path.Join(v.appArmorFS, "profiles") profilesFile, err := os.Open(profilesPath) if err != nil { return nil, fmt.Errorf("failed to open %s: %v", profilesPath, err) } defer profilesFile.Close() profiles := map[string]bool{} scanner := bufio.NewScanner(profilesFile) for scanner.Scan() { profileName := parseProfileName(scanner.Text()) if profileName == "" { // Unknown line format; skip it. continue } profiles[profileName] = true } return profiles, nil } // The profiles file is formatted with one profile per line, matching a form: // namespace://profile-name (mode) // profile-name (mode) // Where mode is {enforce, complain, kill}. The "namespace://" is only included for namespaced // profiles. For the purposes of Kubernetes, we consider the namespace part of the profile name. func parseProfileName(profileLine string) string { modeIndex := strings.IndexRune(profileLine, '(') if modeIndex < 0 { return "" } return strings.TrimSpace(profileLine[:modeIndex]) } func getAppArmorFS() (string, error) { mountsFile, err := os.Open("/proc/mounts") if err != nil { return "", fmt.Errorf("could not open /proc/mounts: %v", err) } defer mountsFile.Close() scanner := bufio.NewScanner(mountsFile) for scanner.Scan() { fields := strings.Fields(scanner.Text()) if len(fields) < 3 { // Unknown line format; skip it. continue } if fields[2] == "securityfs" { appArmorFS := path.Join(fields[1], "apparmor") if ok, err := utilpath.Exists(utilpath.CheckFollowSymlink, appArmorFS); !ok { msg := fmt.Sprintf("path %s does not exist", appArmorFS) if err != nil { return "", fmt.Errorf("%s: %v", msg, err) } return "", errors.New(msg) } return appArmorFS, nil } } if err := scanner.Err(); err != nil { return "", fmt.Errorf("error scanning mounts: %v", err) } return "", errors.New("securityfs not found") } // IsAppArmorEnabled returns true if apparmor is enabled for the host. // This function is forked from // https://github.com/opencontainers/runc/blob/1a81e9ab1f138c091fe5c86d0883f87716088527/libcontainer/apparmor/apparmor.go // to avoid the libapparmor dependency. func IsAppArmorEnabled() bool { if _, err := os.Stat("/sys/kernel/security/apparmor"); err == nil && os.Getenv("container") == "" { if _, err = os.Stat("/sbin/apparmor_parser"); err == nil { buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled") return err == nil && len(buf) > 1 && buf[0] == 'Y' } } return false }
[ "\"container\"" ]
[]
[ "container" ]
[]
["container"]
go
1
0
manage.py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'goalspatial.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: 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?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
[]
[]
[]
[]
[]
python
0
0
cmd/all.go
/* Copyright © 2021 NAME HERE <EMAIL ADDRESS> 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 cmd import ( "os" "github.com/spf13/cobra" "github.com/vmlellis/imersao/codepix-go/infrastructure/db" ) // allCmd represents the all command var allCmd = &cobra.Command{ Use: "all", Short: "Run gRPC and Kafka Consumer", Run: func(cmd *cobra.Command, args []string) { database := db.ConnectDB(os.Getenv("env")) go runGrpc(database) runKafka(database) }, } func init() { rootCmd.AddCommand(allCmd) allCmd.Flags().IntVarP(&gRPCPortNumber, "grpc-port", "p", 50051, "gRPC Server Port") // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // allCmd.PersistentFlags().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: // allCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }
[ "\"env\"" ]
[]
[ "env" ]
[]
["env"]
go
1
0
manage.py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smartcity.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: 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?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
[]
[]
[]
[]
[]
python
0
0
trailing_planner/wsgi.py
""" WSGI config for trailing_planner 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.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'trailing_planner.settings') application = get_wsgi_application()
[]
[]
[]
[]
[]
python
0
0
tiny/util.go
// Copyright 2019 tree xie // // 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 tiny import ( "bytes" "context" "io/ioutil" "math/rand" "os" "os/exec" ) // Commander commander type Commander func(string, string) []string // https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const ( letterIdxBits = 6 // 6 bits to represent a letter index letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits ) // randomString create a random string func randomString(baseLetters string, n int) string { b := make([]byte, n) // A rand.Int63() generates 63 random bits, enough for letterIdxMax letters! for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; { if remain == 0 { cache, remain = rand.Int63(), letterIdxMax } if idx := int(cache & letterIdxMask); idx < len(baseLetters) { b[i] = baseLetters[idx] i-- } cache >>= letterIdxBits remain-- } return string(b) } var tmpDir = os.Getenv("TINY_TMP_DIR") func doCommandConvert(ctx context.Context, data []byte, fn Commander, writer *bytes.Buffer) (err error) { filename := randomString(letterBytes, 10) tmpfile, err := ioutil.TempFile(tmpDir, filename) if err != nil { return } originalFile := tmpfile.Name() defer tmpfile.Close() defer os.Remove(originalFile) _, err = tmpfile.Write(data) if err != nil { return } targetFile := originalFile + "-new" args := fn(originalFile, targetFile) cmd := exec.CommandContext(ctx, args[0], args[1:]...) err = cmd.Run() if err != nil { return } // 删除临时文件 defer os.Remove(targetFile) target, err := ioutil.ReadFile(targetFile) if err != nil { return } writer.Write(target) return }
[ "\"TINY_TMP_DIR\"" ]
[]
[ "TINY_TMP_DIR" ]
[]
["TINY_TMP_DIR"]
go
1
0
service/api/tests/acceptance/api_acceptance_test.go
package acceptance import ( "fmt" "os" "time" "github.com/google/uuid" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/RJPearson94/twilio-sdk-go" v2010 "github.com/RJPearson94/twilio-sdk-go/service/api/v2010" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/address" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/addresses" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/application" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/applications" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/available_phone_number/local" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/available_phone_number/mobile" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/available_phone_number/toll_free" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/call" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/call/feedback" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/call/feedbacks" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/calls" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/calls/feedback_summaries" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/key" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/keys" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/message" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/messages" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/queue" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/queues" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/credential_list" sipCredential "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/credential_list/credential" sipCredentials "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/credential_list/credentials" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/credential_lists" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/domain" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/domain/auth/calls/credential_list_mappings" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/domain/auth/calls/ip_access_control_list_mappings" registrationCredentialListMappings "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/domain/auth/registrations/credential_list_mappings" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/domains" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/ip_access_control_list" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/ip_access_control_list/ip_address" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/ip_access_control_list/ip_addresses" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/sip/ip_access_control_lists" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/account/tokens" "github.com/RJPearson94/twilio-sdk-go/service/api/v2010/accounts" "github.com/RJPearson94/twilio-sdk-go/session/credentials" "github.com/RJPearson94/twilio-sdk-go/twiml/voice" "github.com/RJPearson94/twilio-sdk-go/utils" ) var accountSid = os.Getenv("TWILIO_ACCOUNT_SID") var _ = Describe("API Acceptance Tests", func() { creds, err := credentials.New(credentials.Account{ Sid: accountSid, AuthToken: os.Getenv("TWILIO_AUTH_TOKEN"), }) if err != nil { Fail(fmt.Sprintf("Failed to create credentials. Error %s", err.Error())) } apiClient := twilio.NewWithCredentials(creds).API.V2010 Describe("Given the account clients", func() { It("Then the account is created, fetched and updated", func() { accountsClient := apiClient.Accounts createResp, createErr := accountsClient.Create(&accounts.CreateAccountInput{}) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := accountsClient.Page(&accounts.AccountsPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.Accounts)).Should(BeNumerically(">=", 1)) paginator := accountsClient.NewAccountsPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.Accounts)).Should(BeNumerically(">=", 1)) accountClient := apiClient.Account(createResp.Sid) fetchResp, fetchErr := accountClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := accountClient.Update(&account.UpdateAccountInput{ Status: utils.String("closed"), }) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) }) }) Describe("Given the balance client", func() { It("Then the balance is fetched", func() { balanceClient := apiClient.Account(accountSid).Balance() fetchResp, fetchErr := balanceClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) }) }) Describe("Given the keys clients", func() { var accountSid string BeforeEach(func() { // Create sub account so if the key is leaked the parent account isn't compromised resp, err := apiClient.Accounts.Create(&accounts.CreateAccountInput{}) if err != nil { Fail(fmt.Sprintf("Failed to create account. Error %s", err.Error())) } accountSid = resp.Sid }) AfterEach(func() { if _, err := apiClient.Account(accountSid).Update(&account.UpdateAccountInput{ Status: utils.String("closed"), }); err != nil { Fail(fmt.Sprintf("Failed to delete account. Error %s", err.Error())) } }) It("Then the key is created, fetched, updated and deleted", func() { keysClient := apiClient.Account(accountSid).Keys createResp, createErr := keysClient.Create(&keys.CreateKeyInput{}) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := keysClient.Page(&keys.KeysPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.Keys)).Should(BeNumerically(">=", 1)) paginator := keysClient.NewKeysPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.Keys)).Should(BeNumerically(">=", 1)) keyClient := apiClient.Account(accountSid).Key(createResp.Sid) fetchResp, fetchErr := keyClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := keyClient.Update(&key.UpdateKeyInput{}) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) deleteErr := keyClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the message clients", func() { It("Then the message is created, fetched, updated and deleted", func() { messagesClient := apiClient.Account(accountSid).Messages createResp, createErr := messagesClient.Create(&messages.CreateMessageInput{ To: os.Getenv("DESTINATION_PHONE_NUMBER"), From: utils.String(os.Getenv("TWILIO_PHONE_NUMBER")), Body: utils.String("Hello World"), }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) poll(30, 1000, apiClient, accountSid, createResp.Sid) pageResp, pageErr := messagesClient.Page(&messages.MessagesPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.Messages)).Should(BeNumerically(">=", 1)) paginator := messagesClient.NewMessagesPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.Messages)).Should(BeNumerically(">=", 1)) messageClient := apiClient.Account(accountSid).Message(createResp.Sid) fetchResp, fetchErr := messageClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := messageClient.Update(&message.UpdateMessageInput{ Body: "", }) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) poll(30, 1000, apiClient, accountSid, createResp.Sid) deleteErr := messageClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the token client", func() { It("Then the token is created", func() { tokensClient := apiClient.Account(accountSid).Tokens createResp, createErr := tokensClient.Create(&tokens.CreateTokenInput{ Ttl: utils.Int(1), }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) }) }) Describe("Given the queue clients", func() { It("Then the queue is created, fetched, updated and deleted", func() { queuesClient := apiClient.Account(accountSid).Queues createResp, createErr := queuesClient.Create(&queues.CreateQueueInput{ FriendlyName: uuid.New().String(), }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := queuesClient.Page(&queues.QueuesPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.Queues)).Should(BeNumerically(">=", 1)) paginator := queuesClient.NewQueuesPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.Queues)).Should(BeNumerically(">=", 1)) queueClient := apiClient.Account(accountSid).Queue(createResp.Sid) fetchResp, fetchErr := queueClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := queueClient.Update(&queue.UpdateQueueInput{}) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) deleteErr := queueClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the call clients", func() { It("Then the call is created, fetched, updated and deleted", func() { callsClient := apiClient.Account(accountSid).Calls twiMLResponse := voice.New() twiMLResponse.Say("Hello World") twiML, _ := twiMLResponse.ToTwiML() createResp, createErr := callsClient.Create(&calls.CreateCallInput{ To: os.Getenv("DESTINATION_PHONE_NUMBER"), From: os.Getenv("TWILIO_PHONE_NUMBER"), TwiML: twiML, }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := callsClient.Page(&calls.CallsPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.Calls)).Should(BeNumerically(">=", 1)) paginator := callsClient.NewCallsPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.Calls)).Should(BeNumerically(">=", 1)) callClient := apiClient.Account(accountSid).Call(createResp.Sid) fetchResp, fetchErr := callClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := callClient.Update(&call.UpdateCallInput{ Status: utils.String("completed"), }) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) deleteErr := callClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the address clients", func() { It("Then the address is created, fetched, updated and deleted", func() { addressesClient := apiClient.Account(accountSid).Addresses createResp, createErr := addressesClient.Create(&addresses.CreateAddressInput{ CustomerName: os.Getenv("TWILIO_CUSTOMER_NAME"), Street: os.Getenv("TWILIO_ADDRESS_STREET"), City: os.Getenv("TWILIO_ADDRESS_CITY"), Region: os.Getenv("TWILIO_ADDRESS_REGION"), PostalCode: os.Getenv("TWILIO_ADDRESS_POSTAL_CODE"), IsoCountry: os.Getenv("TWILIO_ADDRESS_ISO_COUNTRY"), AutoCorrectAddress: utils.Bool(true), }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := addressesClient.Page(&addresses.AddressesPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.Addresses)).Should(BeNumerically(">=", 1)) paginator := addressesClient.NewAddressesPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.Addresses)).Should(BeNumerically(">=", 1)) addressClient := apiClient.Account(accountSid).Address(createResp.Sid) fetchResp, fetchErr := addressClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := addressClient.Update(&address.UpdateAddressInput{}) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) deleteErr := addressClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the feedback summary clients", func() { It("Then the feedback summary is created, fetched and deleted", func() { feedbackSummariesClient := apiClient.Account(accountSid).Calls.FeedbackSummaries createResp, createErr := feedbackSummariesClient.Create(&feedback_summaries.CreateFeedbackSummaryInput{ StartDate: "2019-10-03", EndDate: "2020-10-03", }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) feedbackSummaryClient := apiClient.Account(accountSid).Calls.FeedbackSummary(createResp.Sid) fetchResp, fetchErr := feedbackSummaryClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) deleteErr := feedbackSummaryClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the call feedback clients", func() { var callSid string BeforeEach(func() { twiMLResponse := voice.New() twiMLResponse.Say("Hello World") twiML, _ := twiMLResponse.ToTwiML() resp, err := apiClient.Account(accountSid).Calls.Create(&calls.CreateCallInput{ To: os.Getenv("DESTINATION_PHONE_NUMBER"), From: os.Getenv("TWILIO_PHONE_NUMBER"), TwiML: twiML, }) if err != nil { Fail(fmt.Sprintf("Failed to create call. Error %s", err.Error())) } callSid = resp.Sid _, endCallErr := apiClient.Account(accountSid).Call(callSid).Update(&call.UpdateCallInput{ Status: utils.String("completed"), }) if endCallErr != nil { Fail(fmt.Sprintf("Failed to update call. Error %s", endCallErr.Error())) } }) AfterEach(func() { if err := apiClient.Account(accountSid).Call(callSid).Delete(); err != nil { Fail(fmt.Sprintf("Failed to delete call. Error %s", err.Error())) } }) It("Then the feedback is created, fetched and updated", func() { feedbacksClient := apiClient.Account(accountSid).Call(callSid).Feedbacks createResp, createErr := feedbacksClient.Create(&feedbacks.CreateFeedbackInput{ QualityScore: 5, }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) feedbackClient := apiClient.Account(accountSid).Call(callSid).Feedback() fetchResp, fetchErr := feedbackClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := feedbackClient.Update(&feedback.UpdateFeedbackInput{ QualityScore: 4, Issues: &[]string{"audio-latency"}, }) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) }) }) Describe("Given the application clients", func() { It("Then the application is created, fetched, updated and deleted", func() { applicationsClient := apiClient.Account(accountSid).Applications createResp, createErr := applicationsClient.Create(&applications.CreateApplicationInput{}) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := applicationsClient.Page(&applications.ApplicationsPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.Applications)).Should(BeNumerically(">=", 1)) paginator := applicationsClient.NewApplicationsPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.Applications)).Should(BeNumerically(">=", 1)) applicationClient := apiClient.Account(accountSid).Application(createResp.Sid) fetchResp, fetchErr := applicationClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := applicationClient.Update(&application.UpdateApplicationInput{ FriendlyName: utils.String("Test"), }) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) deleteErr := applicationClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the available phone number countries clients", func() { It("Then the countries are fetched", func() { countriesClient := apiClient.Account(accountSid).AvailablePhoneNumbers pageResp, pageErr := countriesClient.Page() Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.Countries)).Should(BeNumerically(">=", 1)) countryClient := apiClient.Account(accountSid).AvailablePhoneNumber("GB") fetchResp, fetchErr := countryClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) }) }) Describe("Given the available toll free phone numbers clients", func() { It("Then the available phone numbers are fetched", func() { availablePhoneNumbersClient := apiClient.Account(accountSid).AvailablePhoneNumber("GB").TollFree pageResp, pageErr := availablePhoneNumbersClient.Page(&toll_free.AvailablePhoneNumbersPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.AvailablePhoneNumbers)).Should(BeNumerically(">=", 1)) }) }) Describe("Given the available local phone numbers clients", func() { It("Then the available phone numbers are fetched", func() { availablePhoneNumbersClient := apiClient.Account(accountSid).AvailablePhoneNumber("GB").Local pageResp, pageErr := availablePhoneNumbersClient.Page(&local.AvailablePhoneNumbersPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.AvailablePhoneNumbers)).Should(BeNumerically(">=", 1)) }) }) Describe("Given the available mobile phone numbers clients", func() { It("Then the available phone numbers are fetched", func() { availablePhoneNumbersClient := apiClient.Account(accountSid).AvailablePhoneNumber("GB").Mobile pageResp, pageErr := availablePhoneNumbersClient.Page(&mobile.AvailablePhoneNumbersPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.AvailablePhoneNumbers)).Should(BeNumerically(">=", 1)) }) }) Describe("Given the SIP credential list clients", func() { It("Then the credential list is created, fetched, updated and deleted", func() { credentialListsClient := apiClient.Account(accountSid).Sip.CredentialLists createResp, createErr := credentialListsClient.Create(&credential_lists.CreateCredentialListInput{ FriendlyName: uuid.New().String(), }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := credentialListsClient.Page(&credential_lists.CredentialListsPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.CredentialLists)).Should(BeNumerically(">=", 1)) paginator := credentialListsClient.NewCredentialListsPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.CredentialLists)).Should(BeNumerically(">=", 1)) credentialListClient := apiClient.Account(accountSid).Sip.CredentialList(createResp.Sid) fetchResp, fetchErr := credentialListClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := credentialListClient.Update(&credential_list.UpdateCredentialListInput{ FriendlyName: uuid.New().String(), }) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) deleteErr := credentialListClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the SIP credential clients", func() { var credentialListSid string BeforeEach(func() { resp, err := apiClient.Account(accountSid).Sip.CredentialLists.Create(&credential_lists.CreateCredentialListInput{ FriendlyName: uuid.New().String(), }) if err != nil { Fail(fmt.Sprintf("Failed to create credential list. Error %s", err.Error())) } credentialListSid = resp.Sid }) AfterEach(func() { if err := apiClient.Account(accountSid).Sip.CredentialList(credentialListSid).Delete(); err != nil { Fail(fmt.Sprintf("Failed to delete credential list. Error %s", err.Error())) } }) It("Then the credential is created, fetched, updated and deleted", func() { credentialsClient := apiClient.Account(accountSid).Sip.CredentialList(credentialListSid).Credentials createResp, createErr := credentialsClient.Create(&sipCredentials.CreateCredentialInput{ Username: uuid.New().String()[0:32], Password: "A" + uuid.New().String(), }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := credentialsClient.Page(&sipCredentials.CredentialsPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.Credentials)).Should(BeNumerically(">=", 1)) paginator := credentialsClient.NewCredentialsPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.Credentials)).Should(BeNumerically(">=", 1)) credentialClient := apiClient.Account(accountSid).Sip.CredentialList(credentialListSid).Credential(createResp.Sid) fetchResp, fetchErr := credentialClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := credentialClient.Update(&sipCredential.UpdateCredentialInput{ Password: "B" + uuid.New().String(), }) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) deleteErr := credentialClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the IP Access Control list clients", func() { It("Then the IP Access Control list is created, fetched, updated and deleted", func() { ipAccessControlListsClient := apiClient.Account(accountSid).Sip.IpAccessControlLists createResp, createErr := ipAccessControlListsClient.Create(&ip_access_control_lists.CreateIpAccessControlListInput{ FriendlyName: uuid.New().String(), }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := ipAccessControlListsClient.Page(&ip_access_control_lists.IpAccessControlListsPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.IpAccessControlLists)).Should(BeNumerically(">=", 1)) paginator := ipAccessControlListsClient.NewIpAccessControlListsPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.IpAccessControlLists)).Should(BeNumerically(">=", 1)) ipAccessControlListClient := apiClient.Account(accountSid).Sip.IpAccessControlList(createResp.Sid) fetchResp, fetchErr := ipAccessControlListClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := ipAccessControlListClient.Update(&ip_access_control_list.UpdateIpAccessControlListInput{ FriendlyName: uuid.New().String(), }) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) deleteErr := ipAccessControlListClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the IP address clients", func() { var ipAccessControlListSid string BeforeEach(func() { resp, err := apiClient.Account(accountSid).Sip.IpAccessControlLists.Create(&ip_access_control_lists.CreateIpAccessControlListInput{ FriendlyName: uuid.New().String(), }) if err != nil { Fail(fmt.Sprintf("Failed to create IP access control list. Error %s", err.Error())) } ipAccessControlListSid = resp.Sid }) AfterEach(func() { if err := apiClient.Account(accountSid).Sip.IpAccessControlList(ipAccessControlListSid).Delete(); err != nil { Fail(fmt.Sprintf("Failed to delete IP access control list. Error %s", err.Error())) } }) It("Then the IP address is created, fetched, updated and deleted", func() { ipAddressesClient := apiClient.Account(accountSid).Sip.IpAccessControlList(ipAccessControlListSid).IpAddresses createResp, createErr := ipAddressesClient.Create(&ip_addresses.CreateIpAddressInput{ FriendlyName: uuid.New().String(), IpAddress: "127.0.0.1", }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := ipAddressesClient.Page(&ip_addresses.IpAddressesPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.IpAddresses)).Should(BeNumerically(">=", 1)) paginator := ipAddressesClient.NewIpAddressesPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.IpAddresses)).Should(BeNumerically(">=", 1)) ipAddressClient := apiClient.Account(accountSid).Sip.IpAccessControlList(ipAccessControlListSid).IpAddress(createResp.Sid) fetchResp, fetchErr := ipAddressClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := ipAddressClient.Update(&ip_address.UpdateIpAddressInput{}) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) deleteErr := ipAddressClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the SIP domain clients", func() { It("Then the domain is created, fetched, updated and deleted", func() { domainsClient := apiClient.Account(accountSid).Sip.Domains createResp, createErr := domainsClient.Create(&domains.CreateDomainInput{ DomainName: uuid.New().String() + ".sip.twilio.com", }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := domainsClient.Page(&domains.DomainsPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.Domains)).Should(BeNumerically(">=", 1)) paginator := domainsClient.NewDomainsPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.Domains)).Should(BeNumerically(">=", 1)) domainClient := apiClient.Account(accountSid).Sip.Domain(createResp.Sid) fetchResp, fetchErr := domainClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) updateResp, updateErr := domainClient.Update(&domain.UpdateDomainInput{}) Expect(updateErr).To(BeNil()) Expect(updateResp).ToNot(BeNil()) deleteErr := domainClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the IP access control list mapping clients", func() { var domainSid string var ipAccessControlListSid string BeforeEach(func() { resp, err := apiClient.Account(accountSid).Sip.Domains.Create(&domains.CreateDomainInput{ DomainName: uuid.New().String() + ".sip.twilio.com", }) if err != nil { Fail(fmt.Sprintf("Failed to create SIP domain. Error %s", err.Error())) } domainSid = resp.Sid ipAccessControlListsResp, ipAccessControlListsErr := apiClient.Account(accountSid).Sip.IpAccessControlLists.Create(&ip_access_control_lists.CreateIpAccessControlListInput{ FriendlyName: uuid.New().String(), }) if ipAccessControlListsErr != nil { Fail(fmt.Sprintf("Failed to create IP access control list. Error %s", ipAccessControlListsErr.Error())) } ipAccessControlListSid = ipAccessControlListsResp.Sid }) AfterEach(func() { if err := apiClient.Account(accountSid).Sip.Domain(domainSid).Delete(); err != nil { Fail(fmt.Sprintf("Failed to delete SIP domain. Error %s", err.Error())) } if err := apiClient.Account(accountSid).Sip.IpAccessControlList(ipAccessControlListSid).Delete(); err != nil { Fail(fmt.Sprintf("Failed to delete IP access control list. Error %s", err.Error())) } }) It("Then the IP access control list mapping is created, fetched and deleted", func() { ipAccessControlListMappingsClient := apiClient.Account(accountSid).Sip.Domain(domainSid).Auth.Calls.IpAccessControlListMappings createResp, createErr := ipAccessControlListMappingsClient.Create(&ip_access_control_list_mappings.CreateIpAccessControlListMappingInput{ IpAccessControlListSid: ipAccessControlListSid, }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := ipAccessControlListMappingsClient.Page(&ip_access_control_list_mappings.IpAccessControlListMappingsPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.IpAccessControlListMappings)).Should(BeNumerically(">=", 1)) paginator := ipAccessControlListMappingsClient.NewIpAccessControlListMappingsPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.IpAccessControlListMappings)).Should(BeNumerically(">=", 1)) ipAccessControlListMappingClient := apiClient.Account(accountSid).Sip.Domain(domainSid).Auth.Calls.IpAccessControlListMapping(createResp.Sid) fetchResp, fetchErr := ipAccessControlListMappingClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) deleteErr := ipAccessControlListMappingClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the credential list mapping clients", func() { var domainSid string var credentialListSid string BeforeEach(func() { resp, err := apiClient.Account(accountSid).Sip.Domains.Create(&domains.CreateDomainInput{ DomainName: uuid.New().String() + ".sip.twilio.com", }) if err != nil { Fail(fmt.Sprintf("Failed to create SIP domain. Error %s", err.Error())) } domainSid = resp.Sid credentialListResp, credentialListErr := apiClient.Account(accountSid).Sip.CredentialLists.Create(&credential_lists.CreateCredentialListInput{ FriendlyName: uuid.New().String(), }) if credentialListErr != nil { Fail(fmt.Sprintf("Failed to create credential list. Error %s", credentialListErr.Error())) } credentialListSid = credentialListResp.Sid }) AfterEach(func() { if err := apiClient.Account(accountSid).Sip.Domain(domainSid).Delete(); err != nil { Fail(fmt.Sprintf("Failed to delete SIP domain. Error %s", err.Error())) } if err := apiClient.Account(accountSid).Sip.CredentialList(credentialListSid).Delete(); err != nil { Fail(fmt.Sprintf("Failed to delete credential list. Error %s", err.Error())) } }) It("Then the credential list mapping is created, fetched and deleted", func() { credentialListMappingsClient := apiClient.Account(accountSid).Sip.Domain(domainSid).Auth.Calls.CredentialListMappings createResp, createErr := credentialListMappingsClient.Create(&credential_list_mappings.CreateCredentialListMappingInput{ CredentialListSid: credentialListSid, }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := credentialListMappingsClient.Page(&credential_list_mappings.CredentialListMappingsPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.CredentialListMappings)).Should(BeNumerically(">=", 1)) paginator := credentialListMappingsClient.NewCredentialListMappingsPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.CredentialListMappings)).Should(BeNumerically(">=", 1)) credentialListMappingClient := apiClient.Account(accountSid).Sip.Domain(domainSid).Auth.Calls.CredentialListMapping(createResp.Sid) fetchResp, fetchErr := credentialListMappingClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) deleteErr := credentialListMappingClient.Delete() Expect(deleteErr).To(BeNil()) }) }) Describe("Given the SIP registration credential list mapping clients", func() { var domainSid string var credentialListSid string BeforeEach(func() { resp, err := apiClient.Account(accountSid).Sip.Domains.Create(&domains.CreateDomainInput{ DomainName: uuid.New().String() + ".sip.twilio.com", }) if err != nil { Fail(fmt.Sprintf("Failed to create SIP domain. Error %s", err.Error())) } domainSid = resp.Sid credentialListResp, credentialListErr := apiClient.Account(accountSid).Sip.CredentialLists.Create(&credential_lists.CreateCredentialListInput{ FriendlyName: uuid.New().String(), }) if credentialListErr != nil { Fail(fmt.Sprintf("Failed to create credential list. Error %s", credentialListErr.Error())) } credentialListSid = credentialListResp.Sid }) AfterEach(func() { if err := apiClient.Account(accountSid).Sip.Domain(domainSid).Delete(); err != nil { Fail(fmt.Sprintf("Failed to delete SIP domain. Error %s", err.Error())) } if err := apiClient.Account(accountSid).Sip.CredentialList(credentialListSid).Delete(); err != nil { Fail(fmt.Sprintf("Failed to delete credential list. Error %s", err.Error())) } }) It("Then the credential list mapping is created, fetched and deleted", func() { credentialListMappingsClient := apiClient.Account(accountSid).Sip.Domain(domainSid).Auth.Registrations.CredentialListMappings createResp, createErr := credentialListMappingsClient.Create(&registrationCredentialListMappings.CreateCredentialListMappingInput{ CredentialListSid: credentialListSid, }) Expect(createErr).To(BeNil()) Expect(createResp).ToNot(BeNil()) Expect(createResp.Sid).ToNot(BeNil()) pageResp, pageErr := credentialListMappingsClient.Page(&registrationCredentialListMappings.CredentialListMappingsPageOptions{}) Expect(pageErr).To(BeNil()) Expect(pageResp).ToNot(BeNil()) Expect(len(pageResp.CredentialListMappings)).Should(BeNumerically(">=", 1)) paginator := credentialListMappingsClient.NewCredentialListMappingsPaginator() for paginator.Next() { } Expect(paginator.Error()).To(BeNil()) Expect(len(paginator.CredentialListMappings)).Should(BeNumerically(">=", 1)) credentialListMappingClient := apiClient.Account(accountSid).Sip.Domain(domainSid).Auth.Registrations.CredentialListMapping(createResp.Sid) fetchResp, fetchErr := credentialListMappingClient.Fetch() Expect(fetchErr).To(BeNil()) Expect(fetchResp).ToNot(BeNil()) deleteErr := credentialListMappingClient.Delete() Expect(deleteErr).To(BeNil()) }) }) // TODO SMS Media tests // TODO Incoming Phone Number tests // TODO Queue Members tests // TODO Conference tests // TODO Conference Participants tests // TODO Recording & Call Recording & conference recording tests }) func poll(maxAttempts int, delay int, client *v2010.V2010, accountSid string, messageSid string) error { for i := 0; i < maxAttempts; i++ { resp, err := client.Account(accountSid).Message(messageSid).Fetch() if err != nil { return fmt.Errorf("Failed to poll message: %s", err) } if resp.Status == "failed" || resp.Status == "undelivered" { return fmt.Errorf("Mesage failed") } if resp.Status == "delivered" { return nil } time.Sleep(time.Duration(delay) * time.Millisecond) } return fmt.Errorf("Reached max polling attempts without a completed message delivery") }
[ "\"TWILIO_ACCOUNT_SID\"", "\"TWILIO_AUTH_TOKEN\"", "\"DESTINATION_PHONE_NUMBER\"", "\"TWILIO_PHONE_NUMBER\"", "\"DESTINATION_PHONE_NUMBER\"", "\"TWILIO_PHONE_NUMBER\"", "\"TWILIO_CUSTOMER_NAME\"", "\"TWILIO_ADDRESS_STREET\"", "\"TWILIO_ADDRESS_CITY\"", "\"TWILIO_ADDRESS_REGION\"", "\"TWILIO_ADDRESS_POSTAL_CODE\"", "\"TWILIO_ADDRESS_ISO_COUNTRY\"", "\"DESTINATION_PHONE_NUMBER\"", "\"TWILIO_PHONE_NUMBER\"" ]
[]
[ "TWILIO_CUSTOMER_NAME", "TWILIO_ADDRESS_POSTAL_CODE", "TWILIO_ADDRESS_STREET", "DESTINATION_PHONE_NUMBER", "TWILIO_ADDRESS_CITY", "TWILIO_ADDRESS_REGION", "TWILIO_PHONE_NUMBER", "TWILIO_AUTH_TOKEN", "TWILIO_ADDRESS_ISO_COUNTRY", "TWILIO_ACCOUNT_SID" ]
[]
["TWILIO_CUSTOMER_NAME", "TWILIO_ADDRESS_POSTAL_CODE", "TWILIO_ADDRESS_STREET", "DESTINATION_PHONE_NUMBER", "TWILIO_ADDRESS_CITY", "TWILIO_ADDRESS_REGION", "TWILIO_PHONE_NUMBER", "TWILIO_AUTH_TOKEN", "TWILIO_ADDRESS_ISO_COUNTRY", "TWILIO_ACCOUNT_SID"]
go
10
0
app.py
# ########################################################################################################## # FLASK APPLICATION # Created by Jon Kostyniuk on 07JUN2015 # Last modified by Jon Kostyniuk on 07JUN2015 # Property of JK Enterprises # v0.01a # ########################################################################################################## # # Version History: # ---------------- # 07JUN2015 v0.01a - JK # - Initial Version. # # Usage: # ------ # This file originates from the source found on 'https://github.com/openshift-quickstart/flask-base' # repository for use on the OpenShift platform. It has been adapted for use with Python Flask as a generic # start file with OpenShift. The 'flaskapp.py' file referenced below is modified for application-specific # functionality. # # This file may be used instead of Apache mod_wsgi to run your python web application in a different # framework. A few examples are provided (cherrypi, gevent), but this file may be altered to run whatever # framework is desired - or a completely customized service. # # Instructions: # ------------- # From the command line, run 'python app.py' within this directory for development purposes. For live use, # load and run from the OpenShift platform. # # ########################################################################################################## # MODULES AND DEFINITIONS # ########################################################################################################## #!/usr/bin/env python import imp import os import sys # ########################################################################################################## # MAIN PROGRAM # ########################################################################################################## # Environment Initialization try: virtenv = os.path.join(os.environ.get('OPENSHIFT_PYTHON_DIR','.'), 'virtenv') python_version = "python" + str(sys.version_info[0]) + "." + str(sys.version_info[1]) os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib', python_version, 'site-packages') virtualenv = os.path.join(virtenv, 'bin','activate_this.py') if(sys.version_info[0] < 3): execfile(virtualenv, dict(__file__=virtualenv)) else: exec(open(virtualenv).read(), dict(__file__=virtualenv)) except IOError: pass # # IMPORTANT: Put any additional includes below this line. If placed above this # line, it's possible required libraries won't be in your searchable path # # Main Program if __name__ == '__main__': # Connection Information application = imp.load_source('app', 'flaskapp.py') port = application.app.config['PORT'] ip = application.app.config['IP'] app_name = application.app.config['APP_NAME'] host_name = application.app.config['HOST_NAME'] # Determine Server Type fwtype = "wsgiref" for fw in ("gevent", "cherrypy", "flask"): try: imp.find_module(fw) fwtype = fw except ImportError: pass # Start WSGI Server and Run Forever print 'Starting WSGIServer type %s on %s:%d ... ' % (fwtype, ip, port) if fwtype == "gevent": from gevent.pywsgi import WSGIServer WSGIServer((ip, port), application.app).serve_forever() elif fwtype == "cherrypy": from cherrypy import wsgiserver server = wsgiserver.CherryPyWSGIServer( (ip, port), application.app, server_name=host_name) server.start() elif fwtype == "flask": from flask import Flask server = Flask(__name__) server.wsgi_app = application.app server.run(host=ip, port=port) else: from wsgiref.simple_server import make_server make_server(ip, port, application.app).serve_forever() # ########################################################################################################## # END OF SCRIPT # ##########################################################################################################
[]
[]
[ "PYTHON_EGG_CACHE", "OPENSHIFT_PYTHON_DIR" ]
[]
["PYTHON_EGG_CACHE", "OPENSHIFT_PYTHON_DIR"]
python
2
0
manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BundesLigaMatches.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
analysis/report_plots/machine_learning/print_neural_network_results_summary.py
import csv import os import sys import collections import math import cPickle as pickle import sexpdata import numpy as np import matplotlib import matplotlib.pyplot as plt import py_common from inlining_tree import parse_time, geometric_mean Entry = collections.namedtuple( "Entry", ["plugin", "benchmark", "time", "speedup"]) PLUGIN_SUBDIR = os.environ.get("PLUGINS_SUBDIR", "plugins-valid") def read(algo): with open("report_plots/data_generation/" % algo, 'rb') as f: (exec_times, initial_exec_times) = pickle.load(f) return (exec_times, initial_exec_times) def read_plugin_times(benchmark, plugin_name): bench_dir = "../results/%s/%s/" % (benchmark, PLUGIN_SUBDIR) with open(os.path.join(bench_dir, "plugin_%s.csv" % plugin_name), "rb") as f: times = [] for line in csv.reader(f): for i in range(4, len(line)): times.append(parse_time(line[i])) if len(times) >= 1: return geometric_mean(times) else: return None def get_initial_time_from_records(benchmark): initial_exec_times = [] try: with open("../pca-data/%s.csv" % benchmark, "rb") as f: for line in csv.reader(f): t = parse_time(line[-1] + "s") if "initial" in line[0]: initial_exec_times.append(t) if initial_exec_times: return geometric_mean(initial_exec_times) else: return None except IOError: return None def get_initial_time_from_results(benchmark): return read_plugin_times(benchmark, plugin_name="nothing") def get_initial_exec_time(benchmark): arr = [] time_from_pca = get_initial_time_from_records(benchmark) if time_from_pca is not None: arr.append(time_from_pca) t = get_initial_time_from_results(benchmark) if t is not None: arr.append(t) if arr: return min(arr) else: return None ALL_PLUGINS = [ "nothing", "v1_neural_network_lasso_general", "v1_neural_network_lasso_hand", "v1_neural_network_lasso_star", "v1_neural_network_ridge_general_0.00005", "v1_neural_network_ridge_general_0.0001", "v1_neural_network_ridge_general_0.0005", "v1_neural_network_ridge_general_0.001", "v1_neural_network_ridge_general_0.005", "v1_neural_network_ridge_general_0.01", "v1_neural_network_ridge_general_0.05", "v1_neural_network_ridge_hand_0.00005", "v1_neural_network_ridge_hand_0.0001", "v1_neural_network_ridge_hand_0.0005", "v1_neural_network_ridge_hand_0.001", "v1_neural_network_ridge_hand_0.005", "v1_neural_network_ridge_hand_0.01", "v1_neural_network_ridge_hand_0.05", "v1_neural_network_ridge_star_0.00005", "v1_neural_network_ridge_star_0.0001", "v1_neural_network_ridge_star_0.0005", "v1_neural_network_ridge_star_0.001", "v1_neural_network_ridge_star_0.005", "v1_neural_network_ridge_star_0.01", "v1_neural_network_ridge_star_0.05", "v1_neural_network_ridge_moe", "v1_neural_network_lasso_moe", ] def main(): initial_exec_time_by_bench = {} entries_by_bench = {} all_records_by_bench = collections.defaultdict(list) all_records_by_plugin = collections.defaultdict(list) exps = py_common.EXPERIMENT_TO_PARAMETERS.keys() for benchmark in exps: initial_exec_times = [] best_time = None initial_exec_time_by_bench[benchmark] = get_initial_exec_time(benchmark) for benchmark in exps: for plugin_name in ALL_PLUGINS: initial_exec_time = initial_exec_time_by_bench[benchmark] time = read_plugin_times(benchmark, plugin_name=plugin_name) if time is not None: ratio = None if initial_exec_time is not None: speedup = (initial_exec_time - time) / initial_exec_time else: speedup = None else: time = None speedup = None entry = Entry( plugin=plugin_name, benchmark=benchmark, time=time, speedup=speedup) all_records_by_bench[benchmark].append(entry) all_records_by_plugin[plugin_name].append(entry) for benchmark in exps: all_records_by_bench[benchmark].sort(key=lambda e : -np.inf if e.plugin == "nothing" else e.time) for plugin_name in ALL_PLUGINS: all_records_by_plugin[plugin_name].sort(key=lambda e : -np.inf if e.plugin == "nothing" else e.speedup) for plugin_name in ALL_PLUGINS: arr = [e for e in all_records_by_plugin[plugin_name] if ("fyq" not in e.benchmark and e.benchmark not in py_common.INITIAL_EXPERIMENTS)] arr.sort(key=lambda e: e.speedup) first_quartile = arr[int(0.25 * len(arr))].speedup * 100 median = arr[int(0.5 * len(arr))].speedup * 100 third_quartile = arr[int(0.75 * len(arr))].speedup * 100 minimum = arr[0].speedup * 100 maximum = arr[-1].speedup * 100 bad = 0 no_diff = 0 good = 0 for e in arr: if e.speedup < -0.01: bad += 1 elif e.speedup > 0.01: good += 1 else: no_diff +=1 plugin_name = translate(plugin_name.replace("v1_neural_network_", "").replace("_", "-")) print "%s & %.3f\\%% & %.3f\\%% & %.4f\\%% & %.3f\\%% & %.3f\\%% & %d & %d & %d \\\\" % (plugin_name, first_quartile, median, third_quartile, minimum, maximum, bad, no_diff, good) def translate(a): if a == "nothing": return " & Baseline & " elif "ridge" in a and "moe" not in a: _ridge, name, factor = a.split("-") factor = float(factor) if name == "star": return "L2 & $H_{*}$ & %f" % factor elif name == "general": return "L2 & $h_{general}$ & %f" % factor elif name == "hand": return "L2 & $h_{hand}$ & %f" % factor else: assert False elif "lasso" in a and "moe" not in a: lasso_, name = a.split("-") if name == "star": return "L1 & $H_{*}$ & -" elif name == "general": return "L1 & $h_{general}$ & -" elif name == "hand": return "L1 & $h_{hand}$ & -" else: assert False else: return a if __name__ == "__main__": main()
[]
[]
[ "PLUGINS_SUBDIR" ]
[]
["PLUGINS_SUBDIR"]
python
1
0
test/kaniko_task_test.go
// +build e2e /* Copyright 2018 Knative Authors LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package test import ( "fmt" "io/ioutil" "os" "regexp" "strings" "testing" "time" "k8s.io/client-go/kubernetes" "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote" knativetest "github.com/knative/pkg/test" "github.com/knative/pkg/test/logging" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/knative/build-pipeline/pkg/apis/pipeline/v1alpha1" tb "github.com/knative/build-pipeline/test/builder" ) const ( kanikoTaskName = "kanikotask" kanikoTaskRunName = "kanikotask-run" kanikoResourceName = "go-example-git" kanikoBuildOutput = "Build successful" ) func getGitResource(namespace string) *v1alpha1.PipelineResource { return tb.PipelineResource(kanikoResourceName, namespace, tb.PipelineResourceSpec( v1alpha1.PipelineResourceTypeGit, tb.PipelineResourceSpecParam("Url", "https://github.com/pivotal-nader-ziada/gohelloworld"), )) } func getDockerRepo() (string, error) { // according to knative/test-infra readme (https://github.com/knative/test-infra/blob/13055d769cc5e1756e605fcb3bcc1c25376699f1/scripts/README.md) // the KO_DOCKER_REPO will be set with according to the project where the cluster is created // it is used here to dynamically get the docker registry to push the image to dockerRepo := os.Getenv("KO_DOCKER_REPO") if dockerRepo == "" { return "", fmt.Errorf("KO_DOCKER_REPO env variable is required") } return fmt.Sprintf("%s/kanikotasktest", dockerRepo), nil } func createSecret(c *knativetest.KubeClient, namespace string) (bool, error) { // when running e2e in cluster, this will not be set so just hop out early file := os.Getenv("GCP_SERVICE_ACCOUNT_KEY_PATH") if file == "" { return false, nil } sec := &corev1.Secret{} sec.Name = "kaniko-secret" sec.Namespace = namespace bs, err := ioutil.ReadFile(file) if err != nil { return false, fmt.Errorf("couldn't read kaniko secret json: %v", err) } sec.Data = map[string][]byte{ "config.json": bs, } _, err = c.Kube.CoreV1().Secrets(namespace).Create(sec) return true, err } func getTask(repo, namespace string, withSecretConfig bool) *v1alpha1.Task { taskSpecOps := []tb.TaskSpecOp{ tb.TaskInputs(tb.InputsResource("gitsource", v1alpha1.PipelineResourceTypeGit)), tb.TaskTimeout(2 * time.Minute), } stepOps := []tb.ContainerOp{ tb.Args( "--dockerfile=/workspace/gitsource/Dockerfile", fmt.Sprintf("--destination=%s", repo), "--context=/workspace/gitsource", ), } if withSecretConfig { stepOps = append(stepOps, tb.VolumeMount(corev1.VolumeMount{Name: "kaniko-secret", MountPath: "/secrets"}), tb.EnvVar("GOOGLE_APPLICATION_CREDENTIALS", "/secrets/config.json"), ) taskSpecOps = append(taskSpecOps, tb.TaskVolume("kaniko-secret", tb.VolumeSource(corev1.VolumeSource{ Secret: &corev1.SecretVolumeSource{ SecretName: "kaniko-secret", }, }))) } step := tb.Step("kaniko", "gcr.io/kaniko-project/executor", stepOps...) taskSpecOps = append(taskSpecOps, step) return tb.Task(kanikoTaskName, namespace, tb.TaskSpec(taskSpecOps...)) } func getTaskRun(namespace string) *v1alpha1.TaskRun { return tb.TaskRun(kanikoTaskRunName, namespace, tb.TaskRunSpec( tb.TaskRunTaskRef(kanikoTaskName), tb.TaskRunInputs(tb.TaskRunInputsResource("gitsource", tb.TaskResourceBindingRef(kanikoResourceName))), )) } // TestTaskRun is an integration test that will verify a TaskRun using kaniko func TestKanikoTaskRun(t *testing.T) { logger := logging.GetContextLogger(t.Name()) c, namespace := setup(t, logger) t.Parallel() repo, err := getDockerRepo() if err != nil { t.Errorf("Expected to get docker repo") } knativetest.CleanupOnInterrupt(func() { tearDown(t, logger, c, namespace) }, logger) defer tearDown(t, logger, c, namespace) hasSecretConfig, err := createSecret(c.KubeClient, namespace) if err != nil { t.Fatalf("Expected to create kaniko creds: %v", err) } if hasSecretConfig { logger.Info("Creating service account secret") } else { logger.Info("Not creating service account secret. This could cause the test to fail locally!") } logger.Infof("Creating Git PipelineResource %s", kanikoResourceName) if _, err := c.PipelineResourceClient.Create(getGitResource(namespace)); err != nil { t.Fatalf("Failed to create Pipeline Resource `%s`: %s", kanikoResourceName, err) } logger.Infof("Creating Task %s", kanikoTaskName) if _, err := c.TaskClient.Create(getTask(repo, namespace, hasSecretConfig)); err != nil { t.Fatalf("Failed to create Task `%s`: %s", kanikoTaskName, err) } logger.Infof("Creating TaskRun %s", kanikoTaskRunName) if _, err := c.TaskRunClient.Create(getTaskRun(namespace)); err != nil { t.Fatalf("Failed to create TaskRun `%s`: %s", kanikoTaskRunName, err) } // Verify status of TaskRun (wait for it) var podName string if err := WaitForTaskRunState(c, kanikoTaskRunName, func(tr *v1alpha1.TaskRun) (bool, error) { podName = tr.Status.PodName return TaskRunSucceed(kanikoTaskRunName)(tr) }, "TaskRunCompleted"); err != nil { t.Errorf("Error waiting for TaskRun %s to finish: %s", kanikoTaskRunName, err) } // There will be a Pod with the expected name. if _, err := c.KubeClient.Kube.CoreV1().Pods(namespace).Get(podName, metav1.GetOptions{}); err != nil { t.Fatalf("Error getting build pod: %v", err) } logs, err := getAllLogsFromPod(c.KubeClient.Kube, podName, namespace) if err != nil { t.Fatalf("Expected to get logs from pod %s: %v", podName, err) } // check the logs contain our success criteria if !strings.Contains(logs, kanikoBuildOutput) { t.Fatalf("Expected output %s from pod %s but got %s", kanikoBuildOutput, podName, logs) } // make sure the pushed digest matches the one we pushed re := regexp.MustCompile("digest: (sha256:\\w+)") match := re.FindStringSubmatch(logs) // make sure we found a match and it has the capture group if len(match) != 2 { t.Fatalf("Expected to find an image digest in the build output") } // match the local digest, which is first capture group against the remote image digest := match[1] remoteDigest, err := getRemoteDigest(repo) if err != nil { t.Fatalf("Expected to get digest for remote image %s", repo) } if digest != remoteDigest { t.Fatalf("Expected local digest %s to match remote digest %s", digest, remoteDigest) } } func getContainerLogs(c kubernetes.Interface, pod, namespace string, containers ...string) (string, error) { sb := strings.Builder{} for _, container := range containers { req := c.CoreV1().Pods(namespace).GetLogs(pod, &corev1.PodLogOptions{Follow: true, Container: container}) rc, err := req.Stream() if err != nil { return "", err } bs, err := ioutil.ReadAll(rc) if err != nil { return "", err } sb.Write(bs) } return sb.String(), nil } func getAllLogsFromPod(c kubernetes.Interface, pod, namespace string) (string, error) { p, err := c.CoreV1().Pods(namespace).Get(pod, metav1.GetOptions{}) if err != nil { return "", err } var containers []string for _, initContainer := range p.Spec.InitContainers { containers = append(containers, initContainer.Name) } for _, container := range p.Spec.Containers { containers = append(containers, container.Name) } return getContainerLogs(c, pod, namespace, containers...) } func getRemoteDigest(image string) (string, error) { ref, err := name.ParseReference(image, name.WeakValidation) if err != nil { return "", fmt.Errorf("could not parse image reference %q: %v", image, err) } img, err := remote.Image(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain)) if err != nil { return "", fmt.Errorf("could not pull remote ref %s: %v", ref, err) } digest, err := img.Digest() if err != nil { return "", fmt.Errorf("could not get digest for image %s: %v", img, err) } return digest.String(), nil }
[ "\"KO_DOCKER_REPO\"", "\"GCP_SERVICE_ACCOUNT_KEY_PATH\"" ]
[]
[ "KO_DOCKER_REPO", "GCP_SERVICE_ACCOUNT_KEY_PATH" ]
[]
["KO_DOCKER_REPO", "GCP_SERVICE_ACCOUNT_KEY_PATH"]
go
2
0
server/routes/alarms/route.py
""" This module handles all the api routing for this server. """ import os import datetime from flask import request, render_template from server import app from .alarm_scheduler import cancel_alarm, schedule_alarm, get_alarms from .notification import get_notifications, remove_notification # The format the date string from input[type="datetime-local"] is in __DATE_FORMAT = "%Y-%m-%dT%H:%M" @app.route("/") @app.route("/index") def render_interface(): """ Renders the main alarm interface using the template specified in config.interface_template """ # the title of the alarm to be removed deleted_alarm_title = request.args.get("alarm_item", default="") # the title of the notification to be removed notification_title = request.args.get("notif", default="") # the time when an alarm will be scheduled new_alarm_time = request.args.get("alarm", default="") # the title of the alarm new_alarm_title = request.args.get("two", default="") # whether to include news briefing when the alarm fires include_news = request.args.get("news", default="") # whether to include weather briefing when the alarm fires include_weather = request.args.get("weather", default="") if notification_title: # the notif param is passed # delete the given notification remove_notification(notification_title) notifications = get_notifications(refresh=False) else: # refresh the list of notifications when the alarm title is not present # because we dont want to fetch news when the user is trying to remove alarms notifications = get_notifications(refresh=not deleted_alarm_title) if deleted_alarm_title: # the alarm_item param is passed # delete the given alarm cancel_alarm(deleted_alarm_title) alarms = get_alarms() if new_alarm_time and new_alarm_title: # the user wants to schedule an alarm schedule_alarm( title=new_alarm_title, at_time=datetime.datetime.strptime(new_alarm_time, __DATE_FORMAT), should_include_news=include_news, should_include_weather=include_weather, ) return render_template( os.environ["INTERFACE_TEMPLATE"], notifications=notifications, alarms=alarms, image="logo.gif", )
[]
[]
[ "INTERFACE_TEMPLATE" ]
[]
["INTERFACE_TEMPLATE"]
python
1
0
marquez_client/client.py
# 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 logging import os import requests from six.moves.urllib.parse import quote from marquez_client import errors from marquez_client.constants import (DEFAULT_TIMEOUT_MS, API_PATH_V1) from marquez_client.models import (DatasetType, JobType) from marquez_client.utils import Utils from marquez_client.version import VERSION _USER_AGENT = f'marquez-python/{VERSION}' _HEADERS = {'User-Agent': _USER_AGENT} log = logging.getLogger(__name__) # Marquez Client class MarquezClient: def __init__(self, url, timeout_ms=None, api_key: str = None): self._timeout = Utils.to_seconds(timeout_ms or os.environ.get( 'MARQUEZ_TIMEOUT_MS', DEFAULT_TIMEOUT_MS) ) self._api_base = f"{url}{API_PATH_V1}" if api_key: Utils.add_auth_to(_HEADERS, api_key) # Namespace API def create_namespace(self, namespace_name, owner_name, description=None): Utils.check_name_length(namespace_name, 'namespace_name') Utils.check_name_length(owner_name, 'owner_name') payload = { 'ownerName': owner_name } if description: payload['description'] = description return self._put( self._url('/namespaces/{0}', namespace_name), payload=payload ) def get_namespace(self, namespace_name): Utils.check_name_length(namespace_name, 'namespace_name') return self._get(self._url('/namespaces/{0}', namespace_name)) def list_namespaces(self, limit=None, offset=None): return self._get( self._url('/namespaces'), params={ 'limit': limit, 'offset': offset } ) # Source API def create_source(self, source_name, source_type, connection_url, description=None): Utils.check_name_length(source_name, 'source_name') Utils.is_valid_connection_url(connection_url) payload = { 'type': source_type.upper(), 'connectionUrl': connection_url } if description: payload['description'] = description return self._put(self._url('/sources/{0}', source_name), payload=payload) def get_source(self, source_name): Utils.check_name_length(source_name, 'source_name') return self._get(self._url('/sources/{0}', source_name)) def list_sources(self, limit=None, offset=None): return self._get( self._url('/sources'), params={ 'limit': limit, 'offset': offset } ) # Datasets API def create_dataset(self, namespace_name, dataset_name, dataset_type, physical_name, source_name, description=None, run_id=None, schema_location=None, fields=None, tags=None): Utils.check_name_length(namespace_name, 'namespace_name') Utils.check_name_length(dataset_name, 'dataset_name') Utils.is_instance_of(dataset_type, DatasetType) if dataset_type == DatasetType.STREAM: MarquezClient._is_none(schema_location, 'schema_location') Utils.check_name_length(physical_name, 'physical_name') Utils.check_name_length(source_name, 'source_name') payload = { 'type': dataset_type.value, 'physicalName': physical_name, 'sourceName': source_name, } if description: payload['description'] = description if run_id: payload['runId'] = run_id if fields: payload['fields'] = Utils.mk_fields_from(fields) if tags: payload['tags'] = tags if schema_location: payload['schemaLocation'] = schema_location return self._put( self._url('/namespaces/{0}/datasets/{1}', namespace_name, dataset_name), payload=payload ) def get_dataset(self, namespace_name, dataset_name): Utils.check_name_length(namespace_name, 'namespace_name') Utils.check_name_length(dataset_name, 'dataset_name') return self._get( self._url('/namespaces/{0}/datasets/{1}', namespace_name, dataset_name) ) def list_datasets(self, namespace_name, limit=None, offset=None): Utils.check_name_length(namespace_name, 'namespace_name') return self._get( self._url('/namespaces/{0}/datasets', namespace_name), params={ 'limit': limit, 'offset': offset } ) def tag_dataset(self, namespace_name, dataset_name, tag_name): Utils.check_name_length(namespace_name, 'namespace_name') Utils.check_name_length(dataset_name, 'dataset_name') if not tag_name: raise ValueError('tag_name must not be None') return self._post( self._url('/namespaces/{0}/datasets/{1}/tags/{2}', namespace_name, dataset_name, tag_name) ) def tag_dataset_field(self, namespace_name, dataset_name, field_name, tag_name): Utils.check_name_length(namespace_name, 'namespace_name') Utils.check_name_length(dataset_name, 'dataset_name') Utils.check_name_length(field_name, 'field_name') Utils.check_name_length(tag_name, 'tag_name') return self._post( self._url('/namespaces/{0}/datasets/{1}/fields/{2}/tags/{3}', namespace_name, dataset_name, field_name, tag_name) ) # Job API def create_job(self, namespace_name, job_name, job_type, location=None, input_dataset=None, output_dataset=None, description=None, context=None, run_id=None): Utils.check_name_length(namespace_name, 'namespace_name') Utils.check_name_length(job_name, 'job_name') Utils.is_instance_of(job_type, JobType) payload = { 'inputs': input_dataset or [], 'outputs': output_dataset or [], 'type': job_type.name } if run_id: payload['runId'] = run_id if context: payload['context'] = context if location: payload['location'] = location if description: payload['description'] = description return self._put( self._url('/namespaces/{0}/jobs/{1}', namespace_name, job_name), payload=payload ) def get_job(self, namespace_name, job_name): Utils.check_name_length(namespace_name, 'namespace_name') Utils.check_name_length(job_name, 'job_name') return self._get( self._url('/namespaces/{0}/jobs/{1}', namespace_name, job_name) ) def list_jobs(self, namespace_name, limit=None, offset=None): Utils.check_name_length(namespace_name, 'namespace_name') return self._get( self._url('/namespaces/{0}/jobs', namespace_name), params={ 'limit': limit, 'offset': offset } ) def create_job_run(self, namespace_name, job_name, run_id=None, nominal_start_time=None, nominal_end_time=None, run_args=None, mark_as_running=False): Utils.check_name_length(namespace_name, 'namespace_name') Utils.check_name_length(job_name, 'job_name') payload = {} if run_id: payload['id'] = run_id if nominal_start_time: payload['nominalStartTime'] = nominal_start_time if nominal_end_time: payload['nominalEndTime'] = nominal_end_time if run_args: payload['args'] = run_args response = self._post( self._url('/namespaces/{0}/jobs/{1}/runs', namespace_name, job_name), payload=payload) if mark_as_running: response = self.mark_job_run_as_started(run_id) return response def list_job_runs(self, namespace_name, job_name, limit=None, offset=None): Utils.check_name_length(namespace_name, 'namespace_name') Utils.check_name_length(job_name, 'job_name') return self._get( self._url( '/namespaces/{0}/jobs/{1}/runs', namespace_name, job_name), params={ 'limit': limit, 'offset': offset } ) def get_job_run(self, run_id): self._is_valid_uuid(run_id, 'run_id') return self._get(self._url('/jobs/runs/{0}', run_id)) def mark_job_run_as_started(self, run_id, action_at=None): return self.__mark_job_run_as(run_id, 'start', action_at) def mark_job_run_as_completed(self, run_id, action_at=None): return self.__mark_job_run_as(run_id, 'complete', action_at) def mark_job_run_as_failed(self, run_id, action_at=None): return self.__mark_job_run_as(run_id, 'fail', action_at) def mark_job_run_as_aborted(self, run_id, action_at=None): return self.__mark_job_run_as(run_id, 'abort', action_at) def list_tags(self, limit=None, offset=None): return self._get( self._url('/tags'), params={ 'limit': limit, 'offset': offset } ) def __mark_job_run_as(self, run_id, action, action_at=None): Utils.is_valid_uuid(run_id, 'run_id') return self._post( self._url('/jobs/runs/{0}/{1}?at={2}', run_id, action, action_at if action_at else Utils.utc_now()), payload={} ) # Common def _url(self, path, *args): encoded_args = [quote(arg.encode('utf-8'), safe='') for arg in args] return f'{self._api_base}{path.format(*encoded_args)}' def _post(self, url, payload, as_json=True): now_ms = Utils.now_ms() response = requests.post( url=url, headers=_HEADERS, json=payload, timeout=self._timeout) post_details = {} post_details['url'] = url post_details['http_method'] = 'POST' post_details['http_headers'] = _HEADERS post_details['payload'] = payload post_details['duration_ms'] = (self._now_ms() - now_ms) log.info(post_details) return self._response(response, as_json) def _put(self, url, payload=None, as_json=True): now_ms = Utils.now_ms() response = requests.put( url=url, headers=_HEADERS, json=payload, timeout=self._timeout) put_details = {} put_details['url'] = url put_details['http_method'] = 'POST' put_details['http_headers'] = _HEADERS put_details['payload'] = payload put_details['duration_ms'] = (self._now_ms() - now_ms) log.info(put_details) return self._response(response, as_json) def _get(self, url, params=None, as_json=True): now_ms = Utils.now_ms() response = requests.get( url, params=params, headers=_HEADERS, timeout=self._timeout) get_details = {} get_details['url'] = url get_details['http_method'] = 'POST' get_details['http_headers'] = _HEADERS get_details['payload'] = params get_details['duration_ms'] = (self._now_ms() - now_ms) log.info(get_details) return self._response(response, as_json) def _response(self, response, as_json): try: response.raise_for_status() except requests.exceptions.HTTPError as e: self._raise_api_error(e) return response.json() if as_json else response.text def _raise_api_error(self, e): # TODO: https://github.com/MarquezProject/marquez-python/issues/55 raise errors.APIError() from e
[]
[]
[ "MARQUEZ_TIMEOUT_MS" ]
[]
["MARQUEZ_TIMEOUT_MS"]
python
1
0
py/ptvsd/_vendored/pydevd/_pydevd_bundle/pydevd_filtering.py
import fnmatch import glob import os.path import sys from _pydev_bundle import pydev_log import pydevd_file_utils import json from collections import namedtuple from _pydev_imps._pydev_saved_modules import threading try: xrange # noqa except NameError: xrange = range # noqa ExcludeFilter = namedtuple('ExcludeFilter', 'name, exclude, is_path') def _convert_to_str_and_clear_empty(roots): if sys.version_info[0] <= 2: # In py2 we need bytes for the files. roots = [ root if not isinstance(root, unicode) else root.encode(sys.getfilesystemencoding()) for root in roots ] new_roots = [] for root in roots: assert isinstance(root, str), '%s not str (found: %s)' % (root, type(root)) if root: new_roots.append(root) return new_roots def _check_matches(patterns, paths): if not patterns and not paths: # Matched to the end. return True if (not patterns and paths) or (patterns and not paths): return False pattern = patterns[0] path = paths[0] if not glob.has_magic(pattern): if pattern != path: return False elif pattern == '**': if len(patterns) == 1: return True # if ** is the last one it matches anything to the right. for i in xrange(len(paths)): # Recursively check the remaining patterns as the # current pattern could match any number of paths. if _check_matches(patterns[1:], paths[i:]): return True elif not fnmatch.fnmatch(path, pattern): # Current part doesn't match. return False return _check_matches(patterns[1:], paths[1:]) def glob_matches_path(path, pattern, sep=os.sep, altsep=os.altsep): if altsep: pattern = pattern.replace(altsep, sep) path = path.replace(altsep, sep) drive = '' if len(path) > 1 and path[1] == ':': drive, path = path[0], path[2:] if drive and len(pattern) > 1: if pattern[1] == ':': if drive.lower() != pattern[0].lower(): return False pattern = pattern[2:] patterns = pattern.split(sep) paths = path.split(sep) if paths: if paths[0] == '': paths = paths[1:] if patterns: if patterns[0] == '': patterns = patterns[1:] return _check_matches(patterns, paths) class FilesFiltering(object): ''' Note: calls at FilesFiltering are uncached. The actual API used should be through PyDB. ''' def __init__(self): self._exclude_filters = [] self._project_roots = [] self._library_roots = [] # Filter out libraries? self._use_libraries_filter = False self.require_module = False # True if some exclude filter filters by the module. self.set_use_libraries_filter(os.getenv('PYDEVD_FILTER_LIBRARIES') is not None) project_roots = os.getenv('IDE_PROJECT_ROOTS', None) if project_roots is not None: project_roots = project_roots.split(os.pathsep) else: project_roots = [] self.set_project_roots(project_roots) library_roots = os.getenv('LIBRARY_ROOTS', None) if library_roots is not None: library_roots = library_roots.split(os.pathsep) else: library_roots = self._get_default_library_roots() self.set_library_roots(library_roots) # Stepping filters. pydevd_filters = os.getenv('PYDEVD_FILTERS', '') if pydevd_filters: pydev_log.debug("PYDEVD_FILTERS %s", (pydevd_filters,)) if pydevd_filters.startswith('{'): # dict(glob_pattern (str) -> exclude(True or False)) exclude_filters = [] for key, val in json.loads(pydevd_filters).items(): exclude_filters.append(ExcludeFilter(key, val, True)) self._exclude_filters = exclude_filters else: # A ';' separated list of strings with globs for the # list of excludes. filters = pydevd_filters.split(';') new_filters = [] for new_filter in filters: if new_filter.strip(): new_filters.append(ExcludeFilter(new_filter.strip(), True, True)) self._exclude_filters = new_filters @classmethod def _get_default_library_roots(cls): # Provide sensible defaults if not in env vars. import site roots = [] try: import sysconfig # Python 2.7 onwards only. except ImportError: pass else: for path_name in set(('stdlib', 'platstdlib', 'purelib', 'platlib')) & set(sysconfig.get_path_names()): roots.append(sysconfig.get_path(path_name)) # Make sure we always get at least the standard library location (based on the `os` and # `threading` modules -- it's a bit weird that it may be different on the ci, but it happens). roots.append(os.path.dirname(os.__file__)) roots.append(os.path.dirname(threading.__file__)) if hasattr(site, 'getusersitepackages'): site_paths = site.getusersitepackages() if isinstance(site_paths, (list, tuple)): for site_path in site_paths: roots.append(site_path) else: roots.append(site_paths) if hasattr(site, 'getsitepackages'): site_paths = site.getsitepackages() if isinstance(site_paths, (list, tuple)): for site_path in site_paths: roots.append(site_path) else: roots.append(site_paths) for path in sys.path: if os.path.exists(path) and os.path.basename(path) == 'site-packages': roots.append(path) roots.extend([os.path.realpath(path) for path in roots]) return sorted(set(roots)) def _normpath(self, filename): return pydevd_file_utils.get_abs_path_real_path_and_base_from_file(filename)[0] def _fix_roots(self, roots): roots = _convert_to_str_and_clear_empty(roots) new_roots = [] for root in roots: new_roots.append(self._normpath(root)) return new_roots def set_project_roots(self, project_roots): self._project_roots = self._fix_roots(project_roots) pydev_log.debug("IDE_PROJECT_ROOTS %s\n" % project_roots) def _get_project_roots(self): return self._project_roots def set_library_roots(self, roots): self._library_roots = self._fix_roots(roots) pydev_log.debug("LIBRARY_ROOTS %s\n" % roots) def _get_library_roots(self): return self._library_roots def in_project_roots(self, filename): ''' Note: don't call directly. Use PyDb.in_project_scope (no caching here). ''' if filename.startswith('<'): # Note: always use only startswith (pypy can have: "<builtin>some other name"). # This is a dummy filename that is usually used for eval or exec. Assume # that it is user code, with one exception: <frozen ...> is used in the # standard library. in_project = not filename.startswith('<frozen ') return in_project project_roots = self._get_project_roots() filename = self._normpath(filename) found_in_project = [] for root in project_roots: if root and filename.startswith(root): found_in_project.append(root) found_in_library = [] library_roots = self._get_library_roots() for root in library_roots: if root and filename.startswith(root): found_in_library.append(root) if not project_roots: # If we have no project roots configured, consider it being in the project # roots if it's not found in site-packages (because we have defaults for those # and not the other way around). in_project = not found_in_library else: in_project = False if found_in_project: if not found_in_library: in_project = True else: # Found in both, let's see which one has the bigger path matched. if max(len(x) for x in found_in_project) > max(len(x) for x in found_in_library): in_project = True return in_project def use_libraries_filter(self): ''' Should we debug only what's inside project folders? ''' return self._use_libraries_filter def set_use_libraries_filter(self, use): pydev_log.debug("pydevd: Use libraries filter: %s\n" % use) self._use_libraries_filter = use def use_exclude_filters(self): # Enabled if we have any filters registered. return len(self._exclude_filters) > 0 def exclude_by_filter(self, filename, module_name): ''' :return: True if it should be excluded, False if it should be included and None if no rule matched the given file. ''' for exclude_filter in self._exclude_filters: # : :type exclude_filter: ExcludeFilter if exclude_filter.is_path: if glob_matches_path(filename, exclude_filter.name): return exclude_filter.exclude else: # Module filter. if exclude_filter.name == module_name or module_name.startswith(exclude_filter.name + '.'): return exclude_filter.exclude return None def set_exclude_filters(self, exclude_filters): ''' :param list(ExcludeFilter) exclude_filters: ''' self._exclude_filters = exclude_filters self.require_module = False for exclude_filter in exclude_filters: if not exclude_filter.is_path: self.require_module = True break
[]
[]
[ "PYDEVD_FILTERS", "LIBRARY_ROOTS", "IDE_PROJECT_ROOTS", "PYDEVD_FILTER_LIBRARIES" ]
[]
["PYDEVD_FILTERS", "LIBRARY_ROOTS", "IDE_PROJECT_ROOTS", "PYDEVD_FILTER_LIBRARIES"]
python
4
0
migrate.go
// Copyright 2013 bee authors // // Licensed under the Apache License, Version 2.0 (the "License"): you may // not use this file except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. package main import ( "database/sql" "fmt" "os" "os/exec" "path" "strconv" "strings" "time" ) var cmdMigrate = &Command{ UsageLine: "migrate [Command]", Short: "run database migrations", Long: ` bee migrate [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] run all outstanding migrations -driver: [mysql | postgres | sqlite] (default: mysql) -conn: the connection string used by the driver, the default is root:@tcp(127.0.0.1:3306)/test bee migrate rollback [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] rollback the last migration operation -driver: [mysql | postgres | sqlite] (default: mysql) -conn: the connection string used by the driver, the default is root:@tcp(127.0.0.1:3306)/test bee migrate reset [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] rollback all migrations -driver: [mysql | postgres | sqlite] (default: mysql) -conn: the connection string used by the driver, the default is root:@tcp(127.0.0.1:3306)/test bee migrate refresh [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] rollback all migrations and run them all again -driver: [mysql | postgres | sqlite] (default: mysql) -conn: the connection string used by the driver, the default is root:@tcp(127.0.0.1:3306)/test `, } var mDriver docValue var mConn docValue func init() { cmdMigrate.Run = runMigration cmdMigrate.Flag.Var(&mDriver, "driver", "database driver: mysql, postgres, sqlite, etc.") cmdMigrate.Flag.Var(&mConn, "conn", "connection string used by the driver to connect to a database instance") } // runMigration is the entry point for starting a migration func runMigration(cmd *Command, args []string) int { crupath, _ := os.Getwd() gopath := os.Getenv("GOPATH") Debugf("gopath:%s", gopath) if gopath == "" { ColorLog("[ERRO] $GOPATH not found\n") ColorLog("[HINT] Set $GOPATH in your environment vairables\n") os.Exit(2) } // load config err := loadConfig() if err != nil { ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err) } // getting command line arguments if len(args) != 0 { cmd.Flag.Parse(args[1:]) } if mDriver == "" { mDriver = docValue(conf.Database.Driver) if mDriver == "" { mDriver = "mysql" } } if mConn == "" { mConn = docValue(conf.Database.Conn) if mConn == "" { mConn = "root:@tcp(127.0.0.1:3306)/test" } } ColorLog("[INFO] Using '%s' as 'driver'\n", mDriver) ColorLog("[INFO] Using '%s' as 'conn'\n", mConn) driverStr, connStr := string(mDriver), string(mConn) if len(args) == 0 { // run all outstanding migrations ColorLog("[INFO] Running all outstanding migrations\n") migrateUpdate(crupath, driverStr, connStr) } else { mcmd := args[0] switch mcmd { case "rollback": ColorLog("[INFO] Rolling back the last migration operation\n") migrateRollback(crupath, driverStr, connStr) case "reset": ColorLog("[INFO] Reseting all migrations\n") migrateReset(crupath, driverStr, connStr) case "refresh": ColorLog("[INFO] Refreshing all migrations\n") migrateRefresh(crupath, driverStr, connStr) default: ColorLog("[ERRO] Command is missing\n") os.Exit(2) } } ColorLog("[SUCC] Migration successful!\n") return 0 } // migrateUpdate does the schema update func migrateUpdate(crupath, driver, connStr string) { migrate("upgrade", crupath, driver, connStr) } // migrateRollback rolls back the latest migration func migrateRollback(crupath, driver, connStr string) { migrate("rollback", crupath, driver, connStr) } // migrateReset rolls back all migrations func migrateReset(crupath, driver, connStr string) { migrate("reset", crupath, driver, connStr) } // migrationRefresh rolls back all migrations and start over again func migrateRefresh(crupath, driver, connStr string) { migrate("refresh", crupath, driver, connStr) } // migrate generates source code, build it, and invoke the binary who does the actual migration func migrate(goal, crupath, driver, connStr string) { dir := path.Join(crupath, "database", "migrations") binary := "m" source := binary + ".go" // connect to database db, err := sql.Open(driver, connStr) if err != nil { ColorLog("[ERRO] Could not connect to %s: %s\n", driver, connStr) ColorLog("[ERRO] Error: %v", err.Error()) os.Exit(2) } defer db.Close() checkForSchemaUpdateTable(db, driver) latestName, latestTime := getLatestMigration(db, goal) writeMigrationSourceFile(dir, source, driver, connStr, latestTime, latestName, goal) buildMigrationBinary(dir, binary) runMigrationBinary(dir, binary) removeTempFile(dir, source) removeTempFile(dir, binary) } // checkForSchemaUpdateTable checks the existence of migrations table. // It checks for the proper table structures and creates the table using MYSQL_MIGRATION_DDL if it does not exist. func checkForSchemaUpdateTable(db *sql.DB, driver string) { showTableSql := showMigrationsTableSql(driver) if rows, err := db.Query(showTableSql); err != nil { ColorLog("[ERRO] Could not show migrations table: %s\n", err) os.Exit(2) } else if !rows.Next() { // no migrations table, create anew createTableSql := createMigrationsTableSql(driver) ColorLog("[INFO] Creating 'migrations' table...\n") if _, err := db.Query(createTableSql); err != nil { ColorLog("[ERRO] Could not create migrations table: %s\n", err) os.Exit(2) } } // checking that migrations table schema are expected selectTableSql := selectMigrationsTableSql(driver) if rows, err := db.Query(selectTableSql); err != nil { ColorLog("[ERRO] Could not show columns of migrations table: %s\n", err) os.Exit(2) } else { for rows.Next() { var fieldBytes, typeBytes, nullBytes, keyBytes, defaultBytes, extraBytes []byte if err := rows.Scan(&fieldBytes, &typeBytes, &nullBytes, &keyBytes, &defaultBytes, &extraBytes); err != nil { ColorLog("[ERRO] Could not read column information: %s\n", err) os.Exit(2) } fieldStr, typeStr, nullStr, keyStr, defaultStr, extraStr := string(fieldBytes), string(typeBytes), string(nullBytes), string(keyBytes), string(defaultBytes), string(extraBytes) if fieldStr == "id_migration" { if keyStr != "PRI" || extraStr != "auto_increment" { ColorLog("[ERRO] Column migration.id_migration type mismatch: KEY: %s, EXTRA: %s\n", keyStr, extraStr) ColorLog("[HINT] Expecting KEY: PRI, EXTRA: auto_increment\n") os.Exit(2) } } else if fieldStr == "name" { if !strings.HasPrefix(typeStr, "varchar") || nullStr != "YES" { ColorLog("[ERRO] Column migration.name type mismatch: TYPE: %s, NULL: %s\n", typeStr, nullStr) ColorLog("[HINT] Expecting TYPE: varchar, NULL: YES\n") os.Exit(2) } } else if fieldStr == "created_at" { if typeStr != "timestamp" || defaultStr != "CURRENT_TIMESTAMP" { ColorLog("[ERRO] Column migration.timestamp type mismatch: TYPE: %s, DEFAULT: %s\n", typeStr, defaultStr) ColorLog("[HINT] Expecting TYPE: timestamp, DEFAULT: CURRENT_TIMESTAMP\n") os.Exit(2) } } } } } func showMigrationsTableSql(driver string) string { switch driver { case "mysql": return "SHOW TABLES LIKE 'migrations'" case "postgres": return "SELECT * FROM pg_catalog.pg_tables WHERE tablename = 'migrations';" default: return "SHOW TABLES LIKE 'migrations'" } } func createMigrationsTableSql(driver string) string { switch driver { case "mysql": return MYSQL_MIGRATION_DDL case "postgres": return POSTGRES_MIGRATION_DDL default: return MYSQL_MIGRATION_DDL } } func selectMigrationsTableSql(driver string) string { switch driver { case "mysql": return "DESC migrations" case "postgres": return "SELECT * FROM migrations WHERE false ORDER BY id_migration;" default: return "DESC migrations" } } // getLatestMigration retrives latest migration with status 'update' func getLatestMigration(db *sql.DB, goal string) (file string, createdAt int64) { sql := "SELECT name FROM migrations where status = 'update' ORDER BY id_migration DESC LIMIT 1" if rows, err := db.Query(sql); err != nil { ColorLog("[ERRO] Could not retrieve migrations: %s\n", err) os.Exit(2) } else { if rows.Next() { if err := rows.Scan(&file); err != nil { ColorLog("[ERRO] Could not read migrations in database: %s\n", err) os.Exit(2) } createdAtStr := file[len(file)-15:] if t, err := time.Parse("20060102_150405", createdAtStr); err != nil { ColorLog("[ERRO] Could not parse time: %s\n", err) os.Exit(2) } else { createdAt = t.Unix() } } else { // migration table has no 'update' record, no point rolling back if goal == "rollback" { ColorLog("[ERRO] There is nothing to rollback\n") os.Exit(2) } file, createdAt = "", 0 } } return } // writeMigrationSourceFile create the source file based on MIGRATION_MAIN_TPL func writeMigrationSourceFile(dir, source, driver, connStr string, latestTime int64, latestName string, task string) { changeDir(dir) if f, err := os.OpenFile(source, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err != nil { ColorLog("[ERRO] Could not create file: %s\n", err) os.Exit(2) } else { content := strings.Replace(MIGRATION_MAIN_TPL, "{{DBDriver}}", driver, -1) content = strings.Replace(content, "{{ConnStr}}", connStr, -1) content = strings.Replace(content, "{{LatestTime}}", strconv.FormatInt(latestTime, 10), -1) content = strings.Replace(content, "{{LatestName}}", latestName, -1) content = strings.Replace(content, "{{Task}}", task, -1) if _, err := f.WriteString(content); err != nil { ColorLog("[ERRO] Could not write to file: %s\n", err) os.Exit(2) } f.Close() } } // buildMigrationBinary changes directory to database/migrations folder and go-build the source func buildMigrationBinary(dir, binary string) { changeDir(dir) cmd := exec.Command("go", "build", "-o", binary) if out, err := cmd.CombinedOutput(); err != nil { ColorLog("[ERRO] Could not build migration binary: %s\n", err) formatShellErrOutput(string(out)) removeTempFile(dir, binary) removeTempFile(dir, binary+".go") os.Exit(2) } } // runMigrationBinary runs the migration program who does the actual work func runMigrationBinary(dir, binary string) { changeDir(dir) cmd := exec.Command("./" + binary) if out, err := cmd.CombinedOutput(); err != nil { formatShellOutput(string(out)) ColorLog("[ERRO] Could not run migration binary: %s\n", err) removeTempFile(dir, binary) removeTempFile(dir, binary+".go") os.Exit(2) } else { formatShellOutput(string(out)) } } // changeDir changes working directory to dir. // It exits the system when encouter an error func changeDir(dir string) { if err := os.Chdir(dir); err != nil { ColorLog("[ERRO] Could not find migration directory: %s\n", err) os.Exit(2) } } // removeTempFile removes a file in dir func removeTempFile(dir, file string) { changeDir(dir) if err := os.Remove(file); err != nil { ColorLog("[WARN] Could not remove temporary file: %s\n", err) } } // formatShellErrOutput formats the error shell output func formatShellErrOutput(o string) { for _, line := range strings.Split(o, "\n") { if line != "" { ColorLog("[ERRO] -| ") fmt.Println(line) } } } // formatShellOutput formats the normal shell output func formatShellOutput(o string) { for _, line := range strings.Split(o, "\n") { if line != "" { ColorLog("[INFO] -| ") fmt.Println(line) } } } const ( MIGRATION_MAIN_TPL = `package main import( "os" "beeGo/astaxie/beego/orm" "beeGo/astaxie/beego/migration" _ "beeGo/go-sql-driver/mysql" _ "beeGo/lib/pq" ) func init(){ orm.RegisterDataBase("default", "{{DBDriver}}","{{ConnStr}}") } func main(){ task := "{{Task}}" switch task { case "upgrade": if err := migration.Upgrade({{LatestTime}}); err != nil { os.Exit(2) } case "rollback": if err := migration.Rollback("{{LatestName}}"); err != nil { os.Exit(2) } case "reset": if err := migration.Reset(); err != nil { os.Exit(2) } case "refresh": if err := migration.Refresh(); err != nil { os.Exit(2) } } } ` MYSQL_MIGRATION_DDL = ` CREATE TABLE migrations ( id_migration int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'surrogate key', name varchar(255) DEFAULT NULL COMMENT 'migration name, unique', created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'date migrated or rolled back', statements longtext COMMENT 'SQL statements for this migration', rollback_statements longtext COMMENT 'SQL statment for rolling back migration', status ENUM('update', 'rollback') COMMENT 'update indicates it is a normal migration while rollback means this migration is rolled back', PRIMARY KEY (id_migration) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ` POSTGRES_MIGRATION_DDL = ` CREATE TYPE migrations_status AS ENUM('update', 'rollback'); CREATE TABLE migrations ( id_migration SERIAL PRIMARY KEY, name varchar(255) DEFAULT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, statements text, rollback_statements text, status migrations_status )` )
[ "\"GOPATH\"" ]
[]
[ "GOPATH" ]
[]
["GOPATH"]
go
1
0
dataset.py
# The following code includes modification from t5, see LICENSE. # we are using tensorflow just for preprocessing (using codes from google/t5) # so force to use cpus import os cuda_devices = os.environ["CUDA_VISIBLE_DEVICES"] os.environ["CUDA_VISIBLE_DEVICES"] = "-1" import tensorflow.compat.v2 as tf gpus = tf.config.experimental.list_physical_devices('GPU') for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) # prevent tensorflow from pre-allocating memory os.environ["CUDA_VISIBLE_DEVICES"] = cuda_devices import torch from torch.utils.data import Dataset from tokenizer import ByT5KoreanTokenizer tokenizer_jamo = ByT5KoreanTokenizer() from transformers import AutoTokenizer tokenizer_google = AutoTokenizer.from_pretrained('google/byt5-small') from t5.data.preprocessors import random_spans_helper, random_spans_noise_mask from preprocessors import noise_span_to_unique_sentinel, nonnoise_span_to_unique_sentinel # customized import glob import gzip import json from tqdm import tqdm # parameters inputs_length = 1024 noise_density = 0.15 mean_noise_span_length = 20 extra_tokens_per_span_inputs = 1 extra_tokens_per_span_targets = 1 def random_span_masking(ids, noise_density, seeds, sentinel_id, extra_ids_increment, mean_noise_span_length): noise_mask = random_spans_noise_mask(tf.size(ids), noise_density, seeds, mean_noise_span_length) input_ids = noise_span_to_unique_sentinel(ids, noise_mask, sentinel_start=sentinel_id, sentinel_inc=extra_ids_increment) labels = nonnoise_span_to_unique_sentinel(ids, noise_mask, sentinel_start=sentinel_id, sentinel_inc=extra_ids_increment) return input_ids, labels def add_eos(ids, eos_id=1): return tf.pad(ids, paddings=tf.constant([[0, 1]]), constant_values=tf.constant(eos_id)) tokens_length, targets_length = random_spans_helper(inputs_length, noise_density, mean_noise_span_length, extra_tokens_per_span_inputs, extra_tokens_per_span_targets) # ids = tokenizer('안녕하세요.', padding=True, truncation=True, max_length=tokens_length, add_special_tokens=False).input_ids # input_ids, labels = random_span_masking(tf.constant(ids), noise_density, [(2, 3), (4, 5)], 259, mean_noise_span_length) # dataset # c4_ko = [] c4_ko_train = [] c4_ko_eval = [] # with open('/data/shared/c4/c4/multilingual/c4-ko.tfrecord-00000-of-01024.json') as f: # for line in f: # c4_ko.append(json.loads(line)) # # c4_ko.append(tokenizer(json.loads(line)['text'], add_special_tokens=False).input_ids) def load_eval_all(): n_texts = 0 # for filename in tqdm(sorted(glob.glob("/data/shared/c4/c4/multilingual/c4-ko.tfrecord-*.gz"))): for filename in sorted(glob.glob("/data/shared/c4/c4/multilingual/c4-ko.tfrecord-*.gz")): with gzip.open(filename) as f: for line in f: n_texts += 1 if n_texts % 100 != 0 or len(c4_ko_eval) >= 1000: # c4_ko_train.append(json.loads(line)) continue else: c4_ko_eval.append(json.loads(line)) if len(c4_ko_eval) >= 1000: return load_eval_all() def get_train_record(files = '/data/shared/c4/c4/multilingual/c4-ko.tfrecord-*.gz'): n_texts = 0 for filename in tqdm(sorted(glob.glob(files))): with gzip.open(filename) as f: for line in f: n_texts += 1 if n_texts % 100 != 0 or len(c4_ko_eval) >= 1000: yield json.loads(line) else: continue # from Korpora import Korpora # corpus = Korpora.load("kowikitext") # ids = tokenizer(corpus.train.texts, padding=True, truncation=True, max_length=512).input_ids # ids_train = ids[:int(len(ids)*0.8)] # ids_eval = ids[int(len(ids)*0.8):] class KoreanDataset(Dataset): def __init__(self, evaluate: bool = False, tokenizer_name: str = 'utf8-korean'): self.evaluate = evaluate self.tokenizer_name = tokenizer_name self.records = get_train_record() if not evaluate else (record for record in c4_ko_eval) return def __len__(self): if self.evaluate: return len(c4_ko_eval) else: return 7617632 def __getitem__(self, i): # print('record:', i) if self.evaluate: record = c4_ko_eval[i]['text'] else: record = next(self.records)['text'] if self.tokenizer_name == 'utf8-korean': ids = tokenizer_jamo(record, padding=True, truncation=True, max_length=tokens_length, add_special_tokens=False).input_ids input_ids, labels = random_span_masking(tf.constant(ids), noise_density, [(i, i), (i, i)], 259 + 19 + 21 + 28, 1, mean_noise_span_length) # byt5-korean encoding else: ids = tokenizer_google(record, padding=True, truncation=True, max_length=tokens_length, add_special_tokens=False).input_ids input_ids, labels = random_span_masking(tf.constant(ids), noise_density, [(i, i), (i, i)], 258, -1, mean_noise_span_length) # google style # input_ids, labels = random_span_masking(tf.constant(ids), noise_density, [(i, i), (i, i)], 259, 1, mean_noise_span_length) # huggingface style: explicit extra ids input_ids = add_eos(input_ids) labels = add_eos(labels) return { 'input_ids': torch.tensor(input_ids.numpy()), 'labels': torch.tensor(labels.numpy()) } # return { 'input_ids': torch.tensor(self.examples[i]), 'decoder_input_ids': torch.tensor(self.examples[i]), 'label_ids': torch.tensor(self.examples[i]) } # return { 'input_ids': torch.tensor(self.examples[i]), 'label_ids': torch.tensor([0]) } if __name__ == "__main__": ds_train = KoreanDataset(evaluate=False) ds_eval = KoreanDataset(evaluate=True) print(ds_train[0]) print(ds_eval[0]) print('Done.')
[]
[]
[ "CUDA_VISIBLE_DEVICES" ]
[]
["CUDA_VISIBLE_DEVICES"]
python
1
0
django_pdf_form_filler/wsgi.py
""" WSGI config for django_pdf_form_filler 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/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_pdf_form_filler.settings") application = get_wsgi_application()
[]
[]
[]
[]
[]
python
0
0
pkg/cli/cmds/root.go
package cmds import ( "fmt" "os" "github.com/rancher/k3s/pkg/version" "github.com/sirupsen/logrus" "github.com/urfave/cli" ) var ( Debug bool ) func init() { // hack - force "file,dns" lookup order if go dns is used if os.Getenv("RES_OPTIONS") == "" { os.Setenv("RES_OPTIONS", " ") } } func NewApp() *cli.App { app := cli.NewApp() app.Name = appName app.Usage = "Kubernetes, but small and simple" app.Version = fmt.Sprintf("%s (%s)", version.Version, version.GitCommit) cli.VersionPrinter = func(c *cli.Context) { fmt.Printf("%s version %s\n", app.Name, app.Version) } app.Flags = []cli.Flag{ cli.BoolFlag{ Name: "debug", Usage: "Turn on debug logs", Destination: &Debug, EnvVar: version.ProgramUpper + "_DEBUG", }, } app.Before = func(ctx *cli.Context) error { if Debug { logrus.SetLevel(logrus.DebugLevel) } return nil } return app }
[ "\"RES_OPTIONS\"" ]
[]
[ "RES_OPTIONS" ]
[]
["RES_OPTIONS"]
go
1
0
youtube_dl/YoutubeDL.py
#!/usr/bin/env python # coding: utf-8 from __future__ import absolute_import, unicode_literals from PIL import Image import PIL import collections import contextlib import copy import datetime import errno import fileinput import io import itertools import json import locale import operator import os import platform import re import shutil import subprocess import socket import sys import time import tokenize import traceback import random from string import ascii_letters from .compat import ( compat_basestring, compat_cookiejar, compat_get_terminal_size, compat_http_client, compat_kwargs, compat_numeric_types, compat_os_name, compat_str, compat_tokenize_tokenize, compat_urllib_error, compat_urllib_request, compat_urllib_request_DataHandler, ) from .utils import ( age_restricted, args_to_str, ContentTooShortError, date_from_str, DateRange, DEFAULT_OUTTMPL, determine_ext, determine_protocol, DownloadError, encode_compat_str, encodeFilename, error_to_compat_str, expand_path, ExtractorError, format_bytes, formatSeconds, GeoRestrictedError, int_or_none, ISO3166Utils, locked_file, make_HTTPS_handler, MaxDownloadsReached, orderedSet, PagedList, parse_filesize, PerRequestProxyHandler, platform_name, PostProcessingError, preferredencoding, prepend_extension, register_socks_protocols, render_table, replace_extension, SameFileError, sanitize_filename, sanitize_path, sanitize_url, sanitized_Request, std_headers, str_or_none, subtitles_filename, UnavailableVideoError, url_basename, version_tuple, write_json_file, write_string, YoutubeDLCookieJar, YoutubeDLCookieProcessor, YoutubeDLHandler, YoutubeDLRedirectHandler, ) from .cache import Cache from .extractor import get_info_extractor, gen_extractor_classes, _LAZY_LOADER from .extractor.openload import PhantomJSwrapper from .downloader import get_suitable_downloader from .downloader.rtmp import rtmpdump_version from .postprocessor import ( FFmpegFixupM3u8PP, FFmpegFixupM4aPP, FFmpegFixupStretchedPP, FFmpegMergerPP, FFmpegPostProcessor, get_postprocessor, ) from .version import __version__ if compat_os_name == 'nt': import ctypes class YoutubeDL(object): """YoutubeDL class. YoutubeDL objects are the ones responsible of downloading the actual video file and writing it to disk if the user has requested it, among some other tasks. In most cases there should be one per program. As, given a video URL, the downloader doesn't know how to extract all the needed information, task that InfoExtractors do, it has to pass the URL to one of them. For this, YoutubeDL objects have a method that allows InfoExtractors to be registered in a given order. When it is passed a URL, the YoutubeDL object handles it to the first InfoExtractor it finds that reports being able to handle it. The InfoExtractor extracts all the information about the video or videos the URL refers to, and YoutubeDL process the extracted information, possibly using a File Downloader to download the video. YoutubeDL objects accept a lot of parameters. In order not to saturate the object constructor with arguments, it receives a dictionary of options instead. These options are available through the params attribute for the InfoExtractors to use. The YoutubeDL also registers itself as the downloader in charge for the InfoExtractors that are added to it, so this is a "mutual registration". Available options: username: Username for authentication purposes. password: Password for authentication purposes. videopassword: Password for accessing a video. ap_mso: Adobe Pass multiple-system operator identifier. ap_username: Multiple-system operator account username. ap_password: Multiple-system operator account password. usenetrc: Use netrc for authentication instead. verbose: Print additional info to stdout. quiet: Do not print messages to stdout. no_warnings: Do not print out anything for warnings. forceurl: Force printing final URL. forcetitle: Force printing title. forceid: Force printing ID. forcethumbnail: Force printing thumbnail URL. forcedescription: Force printing description. forcefilename: Force printing final filename. forceduration: Force printing duration. forcejson: Force printing info_dict as JSON. dump_single_json: Force printing the info_dict of the whole playlist (or video) as a single JSON line. simulate: Do not download the video files. format: Video format code. See options.py for more information. outtmpl: Template for output names. outtmpl_na_placeholder: Placeholder for unavailable meta fields. restrictfilenames: Do not allow "&" and spaces in file names ignoreerrors: Do not stop on download errors. force_generic_extractor: Force downloader to use the generic extractor nooverwrites: Prevent overwriting files. playliststart: Playlist item to start at. playlistend: Playlist item to end at. playlist_items: Specific indices of playlist to download. playlistreverse: Download playlist items in reverse order. playlistrandom: Download playlist items in random order. matchtitle: Download only matching titles. rejecttitle: Reject downloads for matching titles. logger: Log messages to a logging.Logger instance. logtostderr: Log messages to stderr instead of stdout. writedescription: Write the video description to a .description file writeinfojson: Write the video description to a .info.json file writeannotations: Write the video annotations to a .annotations.xml file writethumbnail: Write the thumbnail image to a file write_all_thumbnails: Write all thumbnail formats to files writesubtitles: Write the video subtitles to a file writeautomaticsub: Write the automatically generated subtitles to a file allsubtitles: Downloads all the subtitles of the video (requires writesubtitles or writeautomaticsub) listsubtitles: Lists all available subtitles for the video subtitlesformat: The format code for subtitles subtitleslangs: List of languages of the subtitles to download keepvideo: Keep the video file after post-processing daterange: A DateRange object, download only if the upload_date is in the range. skip_download: Skip the actual download of the video file cachedir: Location of the cache files in the filesystem. False to disable filesystem cache. noplaylist: Download single video instead of a playlist if in doubt. age_limit: An integer representing the user's age in years. Unsuitable videos for the given age are skipped. min_views: An integer representing the minimum view count the video must have in order to not be skipped. Videos without view count information are always downloaded. None for no limit. max_views: An integer representing the maximum view count. Videos that are more popular than that are not downloaded. Videos without view count information are always downloaded. None for no limit. download_archive: File name of a file where all downloads are recorded. Videos already present in the file are not downloaded again. cookiefile: File name where cookies should be read from and dumped to. nocheckcertificate:Do not verify SSL certificates prefer_insecure: Use HTTP instead of HTTPS to retrieve information. At the moment, this is only supported by YouTube. proxy: URL of the proxy server to use geo_verification_proxy: URL of the proxy to use for IP address verification on geo-restricted sites. socket_timeout: Time to wait for unresponsive hosts, in seconds bidi_workaround: Work around buggy terminals without bidirectional text support, using fridibi debug_printtraffic:Print out sent and received HTTP traffic include_ads: Download ads as well default_search: Prepend this string if an input url is not valid. 'auto' for elaborate guessing encoding: Use this encoding instead of the system-specified. extract_flat: Do not resolve URLs, return the immediate result. Pass in 'in_playlist' to only show this behavior for playlist items. postprocessors: A list of dictionaries, each with an entry * key: The name of the postprocessor. See youtube_dl/postprocessor/__init__.py for a list. as well as any further keyword arguments for the postprocessor. progress_hooks: A list of functions that get called on download progress, with a dictionary with the entries * status: One of "downloading", "error", or "finished". Check this first and ignore unknown values. If status is one of "downloading", or "finished", the following properties may also be present: * filename: The final filename (always present) * tmpfilename: The filename we're currently writing to * downloaded_bytes: Bytes on disk * total_bytes: Size of the whole file, None if unknown * total_bytes_estimate: Guess of the eventual file size, None if unavailable. * elapsed: The number of seconds since download started. * eta: The estimated time in seconds, None if unknown * speed: The download speed in bytes/second, None if unknown * fragment_index: The counter of the currently downloaded video fragment. * fragment_count: The number of fragments (= individual files that will be merged) Progress hooks are guaranteed to be called at least once (with status "finished") if the download is successful. merge_output_format: Extension to use when merging formats. fixup: Automatically correct known faults of the file. One of: - "never": do nothing - "warn": only emit a warning - "detect_or_warn": check whether we can do anything about it, warn otherwise (default) source_address: Client-side IP address to bind to. call_home: Boolean, true iff we are allowed to contact the youtube-dl servers for debugging. sleep_interval: Number of seconds to sleep before each download when used alone or a lower bound of a range for randomized sleep before each download (minimum possible number of seconds to sleep) when used along with max_sleep_interval. max_sleep_interval:Upper bound of a range for randomized sleep before each download (maximum possible number of seconds to sleep). Must only be used along with sleep_interval. Actual sleep time will be a random float from range [sleep_interval; max_sleep_interval]. listformats: Print an overview of available video formats and exit. list_thumbnails: Print a table of all thumbnails and exit. match_filter: A function that gets called with the info_dict of every video. If it returns a message, the video is ignored. If it returns None, the video is downloaded. match_filter_func in utils.py is one example for this. no_color: Do not emit color codes in output. geo_bypass: Bypass geographic restriction via faking X-Forwarded-For HTTP header geo_bypass_country: Two-letter ISO 3166-2 country code that will be used for explicit geographic restriction bypassing via faking X-Forwarded-For HTTP header geo_bypass_ip_block: IP range in CIDR notation that will be used similarly to geo_bypass_country The following options determine which downloader is picked: external_downloader: Executable of the external downloader to call. None or unset for standard (built-in) downloader. hls_prefer_native: Use the native HLS downloader instead of ffmpeg/avconv if True, otherwise use ffmpeg/avconv if False, otherwise use downloader suggested by extractor if None. The following parameters are not used by YoutubeDL itself, they are used by the downloader (see youtube_dl/downloader/common.py): nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test, noresizebuffer, retries, continuedl, noprogress, consoletitle, xattr_set_filesize, external_downloader_args, hls_use_mpegts, http_chunk_size. The following options are used by the post processors: prefer_ffmpeg: If False, use avconv instead of ffmpeg if both are available, otherwise prefer ffmpeg. ffmpeg_location: Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory. postprocessor_args: A list of additional command-line arguments for the postprocessor. The following options are used by the Youtube extractor: youtube_include_dash_manifest: If True (default), DASH manifests and related data will be downloaded and processed by extractor. You can reduce network I/O by disabling it if you don't care about DASH. """ _NUMERIC_FIELDS = set(( 'width', 'height', 'tbr', 'abr', 'asr', 'vbr', 'fps', 'filesize', 'filesize_approx', 'timestamp', 'upload_year', 'upload_month', 'upload_day', 'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count', 'average_rating', 'comment_count', 'age_limit', 'start_time', 'end_time', 'chapter_number', 'season_number', 'episode_number', 'track_number', 'disc_number', 'release_year', 'playlist_index', )) params = None _ies = [] _pps = [] _download_retcode = None _num_downloads = None _playlist_level = 0 _playlist_urls = set() _screen_file = None def __init__(self, params=None, auto_init=True): """Create a FileDownloader object with the given options.""" if params is None: params = {} self._ies = [] self._ies_instances = {} self._pps = [] self._progress_hooks = [] self._download_retcode = 0 self._num_downloads = 0 self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)] self._err_file = sys.stderr self.params = { # Default parameters 'nocheckcertificate': False, } self.params.update(params) self.cache = Cache(self) def check_deprecated(param, option, suggestion): if self.params.get(param) is not None: self.report_warning( '%s is deprecated. Use %s instead.' % (option, suggestion)) return True return False if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'): if self.params.get('geo_verification_proxy') is None: self.params['geo_verification_proxy'] = self.params['cn_verification_proxy'] check_deprecated('autonumber_size', '--autonumber-size', 'output template with %(autonumber)0Nd, where N in the number of digits') check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"') check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"') if params.get('bidi_workaround', False): try: import pty master, slave = pty.openpty() width = compat_get_terminal_size().columns if width is None: width_args = [] else: width_args = ['-w', str(width)] sp_kwargs = dict( stdin=subprocess.PIPE, stdout=slave, stderr=self._err_file) try: self._output_process = subprocess.Popen( ['bidiv'] + width_args, **sp_kwargs ) except OSError: self._output_process = subprocess.Popen( ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs) self._output_channel = os.fdopen(master, 'rb') except OSError as ose: if ose.errno == errno.ENOENT: self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.') else: raise if (sys.platform != 'win32' and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968'] and not params.get('restrictfilenames', False)): # Unicode filesystem API will throw errors (#1474, #13027) self.report_warning( 'Assuming --restrict-filenames since file system encoding ' 'cannot encode all characters. ' 'Set the LC_ALL environment variable to fix this.') self.params['restrictfilenames'] = True if isinstance(params.get('outtmpl'), bytes): self.report_warning( 'Parameter outtmpl is bytes, but should be a unicode string. ' 'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.') self._setup_opener() if auto_init: self.print_debug_header() self.add_default_info_extractors() for pp_def_raw in self.params.get('postprocessors', []): pp_class = get_postprocessor(pp_def_raw['key']) pp_def = dict(pp_def_raw) del pp_def['key'] pp = pp_class(self, **compat_kwargs(pp_def)) self.add_post_processor(pp) for ph in self.params.get('progress_hooks', []): self.add_progress_hook(ph) register_socks_protocols() def warn_if_short_id(self, argv): # short YouTube ID starting with dash? idxs = [ i for i, a in enumerate(argv) if re.match(r'^-[0-9A-Za-z_-]{10}$', a)] if idxs: correct_argv = ( ['youtube-dl'] + [a for i, a in enumerate(argv) if i not in idxs] + ['--'] + [argv[i] for i in idxs] ) self.report_warning( 'Long argument string detected. ' 'Use -- to separate parameters and URLs, like this:\n%s\n' % args_to_str(correct_argv)) def add_info_extractor(self, ie): """Add an InfoExtractor object to the end of the list.""" self._ies.append(ie) if not isinstance(ie, type): self._ies_instances[ie.ie_key()] = ie ie.set_downloader(self) def get_info_extractor(self, ie_key): """ Get an instance of an IE with name ie_key, it will try to get one from the _ies list, if there's no instance it will create a new one and add it to the extractor list. """ ie = self._ies_instances.get(ie_key) if ie is None: ie = get_info_extractor(ie_key)() self.add_info_extractor(ie) return ie def add_default_info_extractors(self): """ Add the InfoExtractors returned by gen_extractors to the end of the list """ for ie in gen_extractor_classes(): self.add_info_extractor(ie) def add_post_processor(self, pp): """Add a PostProcessor object to the end of the chain.""" self._pps.append(pp) pp.set_downloader(self) def add_progress_hook(self, ph): """Add the progress hook (currently only for the file downloader)""" self._progress_hooks.append(ph) def _bidi_workaround(self, message): if not hasattr(self, '_output_channel'): return message assert hasattr(self, '_output_process') assert isinstance(message, compat_str) line_count = message.count('\n') + 1 self._output_process.stdin.write((message + '\n').encode('utf-8')) self._output_process.stdin.flush() res = ''.join(self._output_channel.readline().decode('utf-8') for _ in range(line_count)) return res[:-len('\n')] def to_screen(self, message, skip_eol=False): """Print message to stdout if not in quiet mode.""" return self.to_stdout(message, skip_eol, check_quiet=True) def _write_string(self, s, out=None): write_string(s, out=out, encoding=self.params.get('encoding')) def to_stdout(self, message, skip_eol=False, check_quiet=False): """Print message to stdout if not in quiet mode.""" if self.params.get('logger'): self.params['logger'].debug(message) elif not check_quiet or not self.params.get('quiet', False): message = self._bidi_workaround(message) terminator = ['\n', ''][skip_eol] output = message + terminator self._write_string(output, self._screen_file) def to_stderr(self, message): """Print message to stderr.""" assert isinstance(message, compat_str) if self.params.get('logger'): self.params['logger'].error(message) else: message = self._bidi_workaround(message) output = message + '\n' self._write_string(output, self._err_file) def to_console_title(self, message): if not self.params.get('consoletitle', False): return if compat_os_name == 'nt': if ctypes.windll.kernel32.GetConsoleWindow(): # c_wchar_p() might not be necessary if `message` is # already of type unicode() ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message)) elif 'TERM' in os.environ: self._write_string('\033]0;%s\007' % message, self._screen_file) def save_console_title(self): if not self.params.get('consoletitle', False): return if self.params.get('simulate', False): return if compat_os_name != 'nt' and 'TERM' in os.environ: # Save the title on stack self._write_string('\033[22;0t', self._screen_file) def restore_console_title(self): if not self.params.get('consoletitle', False): return if self.params.get('simulate', False): return if compat_os_name != 'nt' and 'TERM' in os.environ: # Restore the title from stack self._write_string('\033[23;0t', self._screen_file) def __enter__(self): self.save_console_title() return self def __exit__(self, *args): self.restore_console_title() if self.params.get('cookiefile') is not None: self.cookiejar.save(ignore_discard=True, ignore_expires=True) def trouble(self, message=None, tb=None): """Determine action to take when a download problem appears. Depending on if the downloader has been configured to ignore download errors or not, this method may throw an exception or not when errors are found, after printing the message. tb, if given, is additional traceback information. """ if message is not None: self.to_stderr(message) if self.params.get('verbose'): if tb is None: if sys.exc_info()[0]: # if .trouble has been called from an except block tb = '' if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]: tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info)) tb += encode_compat_str(traceback.format_exc()) else: tb_data = traceback.format_list(traceback.extract_stack()) tb = ''.join(tb_data) self.to_stderr(tb) if not self.params.get('ignoreerrors', False): if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]: exc_info = sys.exc_info()[1].exc_info else: exc_info = sys.exc_info() raise DownloadError(message, exc_info) self._download_retcode = 1 def report_warning(self, message): ''' Print the message to stderr, it will be prefixed with 'WARNING:' If stderr is a tty file the 'WARNING:' will be colored ''' if self.params.get('logger') is not None: self.params['logger'].warning(message) else: if self.params.get('no_warnings'): return if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt': _msg_header = '\033[0;33mWARNING:\033[0m' else: _msg_header = 'WARNING:' warning_message = '%s %s' % (_msg_header, message) self.to_stderr(warning_message) def report_error(self, message, tb=None): ''' Do the same as trouble, but prefixes the message with 'ERROR:', colored in red if stderr is a tty file. ''' if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt': _msg_header = '\033[0;31mERROR:\033[0m' else: _msg_header = 'ERROR:' error_message = '%s %s' % (_msg_header, message) self.trouble(error_message, tb) def report_file_already_downloaded(self, file_name): """Report file has already been fully downloaded.""" try: self.to_screen('[download] %s has already been downloaded' % file_name) except UnicodeEncodeError: self.to_screen('[download] The file has already been downloaded') def prepare_filename(self, info_dict): """Generate the output filename.""" try: template_dict = dict(info_dict) template_dict['epoch'] = int(time.time()) autonumber_size = self.params.get('autonumber_size') if autonumber_size is None: autonumber_size = 5 template_dict['autonumber'] = self.params.get('autonumber_start', 1) - 1 + self._num_downloads if template_dict.get('resolution') is None: if template_dict.get('width') and template_dict.get('height'): template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height']) elif template_dict.get('height'): template_dict['resolution'] = '%sp' % template_dict['height'] elif template_dict.get('width'): template_dict['resolution'] = '%dx?' % template_dict['width'] sanitize = lambda k, v: sanitize_filename( compat_str(v), restricted=self.params.get('restrictfilenames'), is_id=(k == 'id' or k.endswith('_id'))) template_dict = dict((k, v if isinstance(v, compat_numeric_types) else sanitize(k, v)) for k, v in template_dict.items() if v is not None and not isinstance(v, (list, tuple, dict))) template_dict = collections.defaultdict(lambda: self.params.get('outtmpl_na_placeholder', 'NA'), template_dict) outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL) # For fields playlist_index and autonumber convert all occurrences # of %(field)s to %(field)0Nd for backward compatibility field_size_compat_map = { 'playlist_index': len(str(template_dict['n_entries'])), 'autonumber': autonumber_size, } FIELD_SIZE_COMPAT_RE = r'(?<!%)%\((?P<field>autonumber|playlist_index)\)s' mobj = re.search(FIELD_SIZE_COMPAT_RE, outtmpl) if mobj: outtmpl = re.sub( FIELD_SIZE_COMPAT_RE, r'%%(\1)0%dd' % field_size_compat_map[mobj.group('field')], outtmpl) # Missing numeric fields used together with integer presentation types # in format specification will break the argument substitution since # string NA placeholder is returned for missing fields. We will patch # output template for missing fields to meet string presentation type. for numeric_field in self._NUMERIC_FIELDS: if numeric_field not in template_dict: # As of [1] format syntax is: # %[mapping_key][conversion_flags][minimum_width][.precision][length_modifier]type # 1. https://docs.python.org/2/library/stdtypes.html#string-formatting FORMAT_RE = r'''(?x) (?<!%) % \({0}\) # mapping key (?:[#0\-+ ]+)? # conversion flags (optional) (?:\d+)? # minimum field width (optional) (?:\.\d+)? # precision (optional) [hlL]? # length modifier (optional) [diouxXeEfFgGcrs%] # conversion type ''' outtmpl = re.sub( FORMAT_RE.format(numeric_field), r'%({0})s'.format(numeric_field), outtmpl) # expand_path translates '%%' into '%' and '$$' into '$' # correspondingly that is not what we want since we need to keep # '%%' intact for template dict substitution step. Working around # with boundary-alike separator hack. sep = ''.join([random.choice(ascii_letters) for _ in range(32)]) outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep)) # outtmpl should be expand_path'ed before template dict substitution # because meta fields may contain env variables we don't want to # be expanded. For example, for outtmpl "%(title)s.%(ext)s" and # title "Hello $PATH", we don't want `$PATH` to be expanded. filename = expand_path(outtmpl).replace(sep, '') % template_dict # Temporary fix for #4787 # 'Treat' all problem characters by passing filename through preferredencoding # to workaround encoding issues with subprocess on python2 @ Windows if sys.version_info < (3, 0) and sys.platform == 'win32': filename = encodeFilename(filename, True).decode(preferredencoding()) return sanitize_path(filename) except ValueError as err: self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')') return None def _match_entry(self, info_dict, incomplete): """ Returns None iff the file should be downloaded """ video_title = info_dict.get('title', info_dict.get('id', 'video')) if 'title' in info_dict: # This can happen when we're just evaluating the playlist title = info_dict['title'] matchtitle = self.params.get('matchtitle', False) if matchtitle: if not re.search(matchtitle, title, re.IGNORECASE): return '"' + title + '" title did not match pattern "' + matchtitle + '"' rejecttitle = self.params.get('rejecttitle', False) if rejecttitle: if re.search(rejecttitle, title, re.IGNORECASE): return '"' + title + '" title matched reject pattern "' + rejecttitle + '"' date = info_dict.get('upload_date') if date is not None: dateRange = self.params.get('daterange', DateRange()) if date not in dateRange: return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange) view_count = info_dict.get('view_count') if view_count is not None: min_views = self.params.get('min_views') if min_views is not None and view_count < min_views: return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views) max_views = self.params.get('max_views') if max_views is not None and view_count > max_views: return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views) if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')): return 'Skipping "%s" because it is age restricted' % video_title if self.in_download_archive(info_dict): return '%s has already been recorded in archive' % video_title if not incomplete: match_filter = self.params.get('match_filter') if match_filter is not None: ret = match_filter(info_dict) if ret is not None: return ret return None @staticmethod def add_extra_info(info_dict, extra_info): '''Set the keys from extra_info in info dict if they are missing''' for key, value in extra_info.items(): info_dict.setdefault(key, value) """ Return a list with a dictionary for each video extracted. Arguments: url -- URL to extract Keyword arguments: download -- whether to download videos during extraction ie_key -- extractor key hint extra_info -- dictionary containing the extra values to add to each result process -- whether to resolve all unresolved references (URLs, playlist items), must be True for download to work. force_generic_extractor -- force using the generic extractor """ def extract_info(self, url, download=True, ie_key=None, extra_info={}, process=True, force_generic_extractor=False): ''' Returns a list with a dictionary for each video we find. If 'download', also downloads the videos. extra_info is a dict containing the extra values to add to each result ''' if not ie_key and force_generic_extractor: ie_key = 'Generic' if ie_key: ies = [self.get_info_extractor(ie_key)] else: ies = self._ies for ie in ies: if not ie.suitable(url): continue ie = self.get_info_extractor(ie.ie_key()) if not ie.working(): self.report_warning('The program functionality for this site has been marked as broken, ' 'and will probably not work.') return self.__extract_info(url, ie, download, extra_info, process) else: self.report_error('no suitable InfoExtractor for URL %s' % url) def __handle_extraction_exceptions(func): def wrapper(self, *args, **kwargs): try: return func(self, *args, **kwargs) except GeoRestrictedError as e: msg = e.msg if e.countries: msg += '\nThis video is available in %s.' % ', '.join( map(ISO3166Utils.short2full, e.countries)) msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.' self.report_error(msg) except ExtractorError as e: # An error we somewhat expected self.report_error(compat_str(e), e.format_traceback()) except MaxDownloadsReached: raise except Exception as e: if self.params.get('ignoreerrors', False): self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc())) else: raise return wrapper @__handle_extraction_exceptions def __extract_info(self, url, ie, download, extra_info, process): ie_result = ie.extract(url) if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here) return if isinstance(ie_result, list): # Backwards compatibility: old IE result format ie_result = { '_type': 'compat_list', 'entries': ie_result, } self.add_default_extra_info(ie_result, ie, url) if process: return self.process_ie_result(ie_result, download, extra_info) else: return ie_result def add_default_extra_info(self, ie_result, ie, url): self.add_extra_info(ie_result, { 'extractor': ie.IE_NAME, 'webpage_url': url, 'webpage_url_basename': url_basename(url), 'extractor_key': ie.ie_key(), }) def process_ie_result(self, ie_result, download=True, extra_info={}): """ Take the result of the ie(may be modified) and resolve all unresolved references (URLs, playlist items). It will also download the videos if 'download'. Returns the resolved ie_result. """ result_type = ie_result.get('_type', 'video') if result_type in ('url', 'url_transparent'): ie_result['url'] = sanitize_url(ie_result['url']) extract_flat = self.params.get('extract_flat', False) if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) or extract_flat is True): self.__forced_printings( ie_result, self.prepare_filename(ie_result), incomplete=True) return ie_result if result_type == 'video': self.add_extra_info(ie_result, extra_info) return self.process_video_result(ie_result, download=download) elif result_type == 'url': # We have to add extra_info to the results because it may be # contained in a playlist return self.extract_info(ie_result['url'], download, ie_key=ie_result.get('ie_key'), extra_info=extra_info) elif result_type == 'url_transparent': # Use the information from the embedding page info = self.extract_info( ie_result['url'], ie_key=ie_result.get('ie_key'), extra_info=extra_info, download=False, process=False) # extract_info may return None when ignoreerrors is enabled and # extraction failed with an error, don't crash and return early # in this case if not info: return info force_properties = dict( (k, v) for k, v in ie_result.items() if v is not None) for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'): if f in force_properties: del force_properties[f] new_result = info.copy() new_result.update(force_properties) # Extracted info may not be a video result (i.e. # info.get('_type', 'video') != video) but rather an url or # url_transparent. In such cases outer metadata (from ie_result) # should be propagated to inner one (info). For this to happen # _type of info should be overridden with url_transparent. This # fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163. if new_result.get('_type') == 'url': new_result['_type'] = 'url_transparent' return self.process_ie_result( new_result, download=download, extra_info=extra_info) elif result_type in ('playlist', 'multi_video'): # Protect from infinite recursion due to recursively nested playlists # (see https://github.com/ytdl-org/youtube-dl/issues/27833) webpage_url = ie_result['webpage_url'] if webpage_url in self._playlist_urls: self.to_screen( '[download] Skipping already downloaded playlist: %s' % ie_result.get('title') or ie_result.get('id')) return self._playlist_level += 1 self._playlist_urls.add(webpage_url) try: return self.__process_playlist(ie_result, download) finally: self._playlist_level -= 1 if not self._playlist_level: self._playlist_urls.clear() elif result_type == 'compat_list': self.report_warning( 'Extractor %s returned a compat_list result. ' 'It needs to be updated.' % ie_result.get('extractor')) def _fixup(r): self.add_extra_info( r, { 'extractor': ie_result['extractor'], 'webpage_url': ie_result['webpage_url'], 'webpage_url_basename': url_basename(ie_result['webpage_url']), 'extractor_key': ie_result['extractor_key'], } ) return r ie_result['entries'] = [ self.process_ie_result(_fixup(r), download, extra_info) for r in ie_result['entries'] ] return ie_result else: raise Exception('Invalid result type: %s' % result_type) def __process_playlist(self, ie_result, download): # We process each entry in the playlist playlist = ie_result.get('title') or ie_result.get('id') self.to_screen('[download] Downloading playlist: %s' % playlist) playlist_results = [] playliststart = self.params.get('playliststart', 1) - 1 playlistend = self.params.get('playlistend') # For backwards compatibility, interpret -1 as whole list if playlistend == -1: playlistend = None playlistitems_str = self.params.get('playlist_items') playlistitems = None if playlistitems_str is not None: def iter_playlistitems(format): for string_segment in format.split(','): if '-' in string_segment: start, end = string_segment.split('-') for item in range(int(start), int(end) + 1): yield int(item) else: yield int(string_segment) playlistitems = orderedSet(iter_playlistitems(playlistitems_str)) ie_entries = ie_result['entries'] def make_playlistitems_entries(list_ie_entries): num_entries = len(list_ie_entries) return [ list_ie_entries[i - 1] for i in playlistitems if -num_entries <= i - 1 < num_entries] def report_download(num_entries): self.to_screen( '[%s] playlist %s: Downloading %d videos' % (ie_result['extractor'], playlist, num_entries)) if isinstance(ie_entries, list): n_all_entries = len(ie_entries) if playlistitems: entries = make_playlistitems_entries(ie_entries) else: entries = ie_entries[playliststart:playlistend] n_entries = len(entries) self.to_screen( '[%s] playlist %s: Collected %d video ids (downloading %d of them)' % (ie_result['extractor'], playlist, n_all_entries, n_entries)) elif isinstance(ie_entries, PagedList): if playlistitems: entries = [] for item in playlistitems: entries.extend(ie_entries.getslice( item - 1, item )) else: entries = ie_entries.getslice( playliststart, playlistend) n_entries = len(entries) report_download(n_entries) else: # iterable if playlistitems: entries = make_playlistitems_entries(list(itertools.islice( ie_entries, 0, max(playlistitems)))) else: entries = list(itertools.islice( ie_entries, playliststart, playlistend)) n_entries = len(entries) report_download(n_entries) if self.params.get('playlistreverse', False): entries = entries[::-1] if self.params.get('playlistrandom', False): random.shuffle(entries) x_forwarded_for = ie_result.get('__x_forwarded_for_ip') for i, entry in enumerate(entries, 1): self.to_screen('[download] Downloading video %s of %s' % (i, n_entries)) # This __x_forwarded_for_ip thing is a bit ugly but requires # minimal changes if x_forwarded_for: entry['__x_forwarded_for_ip'] = x_forwarded_for extra = { 'n_entries': n_entries, 'playlist': playlist, 'playlist_id': ie_result.get('id'), 'playlist_title': ie_result.get('title'), 'playlist_uploader': ie_result.get('uploader'), 'playlist_uploader_id': ie_result.get('uploader_id'), 'playlist_index': playlistitems[i - 1] if playlistitems else i + playliststart, 'extractor': ie_result['extractor'], 'webpage_url': ie_result['webpage_url'], 'webpage_url_basename': url_basename(ie_result['webpage_url']), 'extractor_key': ie_result['extractor_key'], } reason = self._match_entry(entry, incomplete=True) if reason is not None: self.to_screen('[download] ' + reason) continue entry_result = self.__process_iterable_entry(entry, download, extra) # TODO: skip failed (empty) entries? playlist_results.append(entry_result) ie_result['entries'] = playlist_results self.to_screen('[download] Finished downloading playlist: %s' % playlist) return ie_result @__handle_extraction_exceptions def __process_iterable_entry(self, entry, download, extra_info): return self.process_ie_result( entry, download=download, extra_info=extra_info) def _build_format_filter(self, filter_spec): " Returns a function to filter the formats according to the filter_spec " OPERATORS = { '<': operator.lt, '<=': operator.le, '>': operator.gt, '>=': operator.ge, '=': operator.eq, '!=': operator.ne, } operator_rex = re.compile(r'''(?x)\s* (?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps) \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s* (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?) $ ''' % '|'.join(map(re.escape, OPERATORS.keys()))) m = operator_rex.search(filter_spec) if m: try: comparison_value = int(m.group('value')) except ValueError: comparison_value = parse_filesize(m.group('value')) if comparison_value is None: comparison_value = parse_filesize(m.group('value') + 'B') if comparison_value is None: raise ValueError( 'Invalid value %r in format specification %r' % ( m.group('value'), filter_spec)) op = OPERATORS[m.group('op')] if not m: STR_OPERATORS = { '=': operator.eq, '^=': lambda attr, value: attr.startswith(value), '$=': lambda attr, value: attr.endswith(value), '*=': lambda attr, value: value in attr, } str_operator_rex = re.compile(r'''(?x) \s*(?P<key>ext|acodec|vcodec|container|protocol|format_id|language) \s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)? \s*(?P<value>[a-zA-Z0-9._-]+) \s*$ ''' % '|'.join(map(re.escape, STR_OPERATORS.keys()))) m = str_operator_rex.search(filter_spec) if m: comparison_value = m.group('value') str_op = STR_OPERATORS[m.group('op')] if m.group('negation'): op = lambda attr, value: not str_op(attr, value) else: op = str_op if not m: raise ValueError('Invalid filter specification %r' % filter_spec) def _filter(f): actual_value = f.get(m.group('key')) if actual_value is None: return m.group('none_inclusive') return op(actual_value, comparison_value) return _filter def _default_format_spec(self, info_dict, download=True): def can_merge(): merger = FFmpegMergerPP(self) return merger.available and merger.can_merge() def prefer_best(): if self.params.get('simulate', False): return False if not download: return False if self.params.get('outtmpl', DEFAULT_OUTTMPL) == '-': return True if info_dict.get('is_live'): return True if not can_merge(): return True return False req_format_list = ['bestvideo+bestaudio', 'best'] if prefer_best(): req_format_list.reverse() return '/'.join(req_format_list) def build_format_selector(self, format_spec): def syntax_error(note, start): message = ( 'Invalid format specification: ' '{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1])) return SyntaxError(message) PICKFIRST = 'PICKFIRST' MERGE = 'MERGE' SINGLE = 'SINGLE' GROUP = 'GROUP' FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters']) def _parse_filter(tokens): filter_parts = [] for type, string, start, _, _ in tokens: if type == tokenize.OP and string == ']': return ''.join(filter_parts) else: filter_parts.append(string) def _remove_unused_ops(tokens): # Remove operators that we don't use and join them with the surrounding strings # for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9' ALLOWED_OPS = ('/', '+', ',', '(', ')') last_string, last_start, last_end, last_line = None, None, None, None for type, string, start, end, line in tokens: if type == tokenize.OP and string == '[': if last_string: yield tokenize.NAME, last_string, last_start, last_end, last_line last_string = None yield type, string, start, end, line # everything inside brackets will be handled by _parse_filter for type, string, start, end, line in tokens: yield type, string, start, end, line if type == tokenize.OP and string == ']': break elif type == tokenize.OP and string in ALLOWED_OPS: if last_string: yield tokenize.NAME, last_string, last_start, last_end, last_line last_string = None yield type, string, start, end, line elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]: if not last_string: last_string = string last_start = start last_end = end else: last_string += string if last_string: yield tokenize.NAME, last_string, last_start, last_end, last_line def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False): selectors = [] current_selector = None for type, string, start, _, _ in tokens: # ENCODING is only defined in python 3.x if type == getattr(tokenize, 'ENCODING', None): continue elif type in [tokenize.NAME, tokenize.NUMBER]: current_selector = FormatSelector(SINGLE, string, []) elif type == tokenize.OP: if string == ')': if not inside_group: # ')' will be handled by the parentheses group tokens.restore_last_token() break elif inside_merge and string in ['/', ',']: tokens.restore_last_token() break elif inside_choice and string == ',': tokens.restore_last_token() break elif string == ',': if not current_selector: raise syntax_error('"," must follow a format selector', start) selectors.append(current_selector) current_selector = None elif string == '/': if not current_selector: raise syntax_error('"/" must follow a format selector', start) first_choice = current_selector second_choice = _parse_format_selection(tokens, inside_choice=True) current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), []) elif string == '[': if not current_selector: current_selector = FormatSelector(SINGLE, 'best', []) format_filter = _parse_filter(tokens) current_selector.filters.append(format_filter) elif string == '(': if current_selector: raise syntax_error('Unexpected "("', start) group = _parse_format_selection(tokens, inside_group=True) current_selector = FormatSelector(GROUP, group, []) elif string == '+': if inside_merge: raise syntax_error('Unexpected "+"', start) video_selector = current_selector audio_selector = _parse_format_selection(tokens, inside_merge=True) if not video_selector or not audio_selector: raise syntax_error('"+" must be between two format selectors', start) current_selector = FormatSelector(MERGE, (video_selector, audio_selector), []) else: raise syntax_error('Operator not recognized: "{0}"'.format(string), start) elif type == tokenize.ENDMARKER: break if current_selector: selectors.append(current_selector) return selectors def _build_selector_function(selector): if isinstance(selector, list): fs = [_build_selector_function(s) for s in selector] def selector_function(ctx): for f in fs: for format in f(ctx): yield format return selector_function elif selector.type == GROUP: selector_function = _build_selector_function(selector.selector) elif selector.type == PICKFIRST: fs = [_build_selector_function(s) for s in selector.selector] def selector_function(ctx): for f in fs: picked_formats = list(f(ctx)) if picked_formats: return picked_formats return [] elif selector.type == SINGLE: format_spec = selector.selector def selector_function(ctx): formats = list(ctx['formats']) if not formats: return if format_spec == 'all': for f in formats: yield f elif format_spec in ['best', 'worst', None]: format_idx = 0 if format_spec == 'worst' else -1 audiovideo_formats = [ f for f in formats if f.get('vcodec') != 'none' and f.get('acodec') != 'none'] if audiovideo_formats: yield audiovideo_formats[format_idx] # for extractors with incomplete formats (audio only (soundcloud) # or video only (imgur)) we will fallback to best/worst # {video,audio}-only format elif ctx['incomplete_formats']: yield formats[format_idx] elif format_spec == 'bestaudio': audio_formats = [ f for f in formats if f.get('vcodec') == 'none'] if audio_formats: yield audio_formats[-1] elif format_spec == 'worstaudio': audio_formats = [ f for f in formats if f.get('vcodec') == 'none'] if audio_formats: yield audio_formats[0] elif format_spec == 'bestvideo': video_formats = [ f for f in formats if f.get('acodec') == 'none'] if video_formats: yield video_formats[-1] elif format_spec == 'worstvideo': video_formats = [ f for f in formats if f.get('acodec') == 'none'] if video_formats: yield video_formats[0] else: extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav'] if format_spec in extensions: filter_f = lambda f: f['ext'] == format_spec else: filter_f = lambda f: f['format_id'] == format_spec matches = list(filter(filter_f, formats)) if matches: yield matches[-1] elif selector.type == MERGE: def _merge(formats_info): format_1, format_2 = [f['format_id'] for f in formats_info] # The first format must contain the video and the # second the audio if formats_info[0].get('vcodec') == 'none': self.report_error('The first format must ' 'contain the video, try using ' '"-f %s+%s"' % (format_2, format_1)) return # Formats must be opposite (video+audio) if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none': self.report_error( 'Both formats %s and %s are video-only, you must specify "-f video+audio"' % (format_1, format_2)) return output_ext = ( formats_info[0]['ext'] if self.params.get('merge_output_format') is None else self.params['merge_output_format']) return { 'requested_formats': formats_info, 'format': '%s+%s' % (formats_info[0].get('format'), formats_info[1].get('format')), 'format_id': '%s+%s' % (formats_info[0].get('format_id'), formats_info[1].get('format_id')), 'width': formats_info[0].get('width'), 'height': formats_info[0].get('height'), 'resolution': formats_info[0].get('resolution'), 'fps': formats_info[0].get('fps'), 'vcodec': formats_info[0].get('vcodec'), 'vbr': formats_info[0].get('vbr'), 'stretched_ratio': formats_info[0].get('stretched_ratio'), 'acodec': formats_info[1].get('acodec'), 'abr': formats_info[1].get('abr'), 'ext': output_ext, } video_selector, audio_selector = map(_build_selector_function, selector.selector) def selector_function(ctx): for pair in itertools.product( video_selector(copy.deepcopy(ctx)), audio_selector(copy.deepcopy(ctx))): yield _merge(pair) filters = [self._build_format_filter(f) for f in selector.filters] def final_selector(ctx): ctx_copy = copy.deepcopy(ctx) for _filter in filters: ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats'])) return selector_function(ctx_copy) return final_selector stream = io.BytesIO(format_spec.encode('utf-8')) try: tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline))) except tokenize.TokenError: raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec))) class TokenIterator(object): def __init__(self, tokens): self.tokens = tokens self.counter = 0 def __iter__(self): return self def __next__(self): if self.counter >= len(self.tokens): raise StopIteration() value = self.tokens[self.counter] self.counter += 1 return value next = __next__ def restore_last_token(self): self.counter -= 1 parsed_selector = _parse_format_selection(iter(TokenIterator(tokens))) return _build_selector_function(parsed_selector) def _calc_headers(self, info_dict): res = std_headers.copy() add_headers = info_dict.get('http_headers') if add_headers: res.update(add_headers) cookies = self._calc_cookies(info_dict) if cookies: res['Cookie'] = cookies if 'X-Forwarded-For' not in res: x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip') if x_forwarded_for_ip: res['X-Forwarded-For'] = x_forwarded_for_ip return res def _calc_cookies(self, info_dict): pr = sanitized_Request(info_dict['url']) self.cookiejar.add_cookie_header(pr) return pr.get_header('Cookie') def process_video_result(self, info_dict, download=True): assert info_dict.get('_type', 'video') == 'video' if 'id' not in info_dict: raise ExtractorError('Missing "id" field in extractor result') if 'title' not in info_dict: raise ExtractorError('Missing "title" field in extractor result') def report_force_conversion(field, field_not, conversion): self.report_warning( '"%s" field is not %s - forcing %s conversion, there is an error in extractor' % (field, field_not, conversion)) def sanitize_string_field(info, string_field): field = info.get(string_field) if field is None or isinstance(field, compat_str): return report_force_conversion(string_field, 'a string', 'string') info[string_field] = compat_str(field) def sanitize_numeric_fields(info): for numeric_field in self._NUMERIC_FIELDS: field = info.get(numeric_field) if field is None or isinstance(field, compat_numeric_types): continue report_force_conversion(numeric_field, 'numeric', 'int') info[numeric_field] = int_or_none(field) sanitize_string_field(info_dict, 'id') sanitize_numeric_fields(info_dict) if 'playlist' not in info_dict: # It isn't part of a playlist info_dict['playlist'] = None info_dict['playlist_index'] = None thumbnails = info_dict.get('thumbnails') if thumbnails is None: thumbnail = info_dict.get('thumbnail') if thumbnail: info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}] if thumbnails: thumbnails.sort(key=lambda t: ( t.get('preference') if t.get('preference') is not None else -1, t.get('width') if t.get('width') is not None else -1, t.get('height') if t.get('height') is not None else -1, t.get('id') if t.get('id') is not None else '', t.get('url'))) for i, t in enumerate(thumbnails): t['url'] = sanitize_url(t['url']) if t.get('width') and t.get('height'): t['resolution'] = '%dx%d' % (t['width'], t['height']) if t.get('id') is None: t['id'] = '%d' % i if self.params.get('list_thumbnails'): self.list_thumbnails(info_dict) return thumbnail = info_dict.get('thumbnail') if thumbnail: info_dict['thumbnail'] = sanitize_url(thumbnail) elif thumbnails: info_dict['thumbnail'] = thumbnails[-1]['url'] if 'display_id' not in info_dict and 'id' in info_dict: info_dict['display_id'] = info_dict['id'] for ts_key, date_key in ( ('timestamp', 'upload_date'), ('release_timestamp', 'release_date'), ): if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None: # Working around out-of-range timestamp values (e.g. negative ones on Windows, # see http://bugs.python.org/issue1646728) try: upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key]) info_dict[date_key] = upload_date.strftime('%Y%m%d') except (ValueError, OverflowError, OSError): pass # Auto generate title fields corresponding to the *_number fields when missing # in order to always have clean titles. This is very common for TV series. for field in ('chapter', 'season', 'episode'): if info_dict.get('%s_number' % field) is not None and not info_dict.get(field): info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field]) for cc_kind in ('subtitles', 'automatic_captions'): cc = info_dict.get(cc_kind) if cc: for _, subtitle in cc.items(): for subtitle_format in subtitle: if subtitle_format.get('url'): subtitle_format['url'] = sanitize_url(subtitle_format['url']) if subtitle_format.get('ext') is None: subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower() automatic_captions = info_dict.get('automatic_captions') subtitles = info_dict.get('subtitles') if self.params.get('listsubtitles', False): if 'automatic_captions' in info_dict: self.list_subtitles( info_dict['id'], automatic_captions, 'automatic captions') self.list_subtitles(info_dict['id'], subtitles, 'subtitles') return info_dict['requested_subtitles'] = self.process_subtitles( info_dict['id'], subtitles, automatic_captions) # We now pick which formats have to be downloaded if info_dict.get('formats') is None: # There's only one format available formats = [info_dict] else: formats = info_dict['formats'] if not formats: raise ExtractorError('No video formats found!') def is_wellformed(f): url = f.get('url') if not url: self.report_warning( '"url" field is missing or empty - skipping format, ' 'there is an error in extractor') return False if isinstance(url, bytes): sanitize_string_field(f, 'url') return True # Filter out malformed formats for better extraction robustness formats = list(filter(is_wellformed, formats)) formats_dict = {} # We check that all the formats have the format and format_id fields for i, format in enumerate(formats): sanitize_string_field(format, 'format_id') sanitize_numeric_fields(format) format['url'] = sanitize_url(format['url']) if not format.get('format_id'): format['format_id'] = compat_str(i) else: # Sanitize format_id from characters used in format selector expression format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id']) format_id = format['format_id'] if format_id not in formats_dict: formats_dict[format_id] = [] formats_dict[format_id].append(format) # Make sure all formats have unique format_id for format_id, ambiguous_formats in formats_dict.items(): if len(ambiguous_formats) > 1: for i, format in enumerate(ambiguous_formats): format['format_id'] = '%s-%d' % (format_id, i) for i, format in enumerate(formats): if format.get('format') is None: format['format'] = '{id} - {res}{note}'.format( id=format['format_id'], res=self.format_resolution(format), note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '', ) # Automatically determine file extension if missing if format.get('ext') is None: format['ext'] = determine_ext(format['url']).lower() # Automatically determine protocol if missing (useful for format # selection purposes) if format.get('protocol') is None: format['protocol'] = determine_protocol(format) # Add HTTP headers, so that external programs can use them from the # json output full_format_info = info_dict.copy() full_format_info.update(format) format['http_headers'] = self._calc_headers(full_format_info) # Remove private housekeeping stuff if '__x_forwarded_for_ip' in info_dict: del info_dict['__x_forwarded_for_ip'] # TODO Central sorting goes here if formats[0] is not info_dict: # only set the 'formats' fields if the original info_dict list them # otherwise we end up with a circular reference, the first (and unique) # element in the 'formats' field in info_dict is info_dict itself, # which can't be exported to json info_dict['formats'] = formats if self.params.get('listformats'): self.list_formats(info_dict) return req_format = self.params.get('format') if req_format is None: req_format = self._default_format_spec(info_dict, download=download) if self.params.get('verbose'): self._write_string('[debug] Default format spec: %s\n' % req_format) format_selector = self.build_format_selector(req_format) # While in format selection we may need to have an access to the original # format set in order to calculate some metrics or do some processing. # For now we need to be able to guess whether original formats provided # by extractor are incomplete or not (i.e. whether extractor provides only # video-only or audio-only formats) for proper formats selection for # extractors with such incomplete formats (see # https://github.com/ytdl-org/youtube-dl/pull/5556). # Since formats may be filtered during format selection and may not match # the original formats the results may be incorrect. Thus original formats # or pre-calculated metrics should be passed to format selection routines # as well. # We will pass a context object containing all necessary additional data # instead of just formats. # This fixes incorrect format selection issue (see # https://github.com/ytdl-org/youtube-dl/issues/10083). incomplete_formats = ( # All formats are video-only or all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats) # all formats are audio-only or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats)) ctx = { 'formats': formats, 'incomplete_formats': incomplete_formats, } formats_to_download = list(format_selector(ctx)) if not formats_to_download: raise ExtractorError('requested format not available', expected=True) if download: if len(formats_to_download) > 1: self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download))) for format in formats_to_download: new_info = dict(info_dict) new_info.update(format) self.process_info(new_info) # We update the info dict with the best quality format (backwards compatibility) info_dict.update(formats_to_download[-1]) return info_dict def process_subtitles(self, video_id, normal_subtitles, automatic_captions): """Select the requested subtitles and their format""" available_subs = {} if normal_subtitles and self.params.get('writesubtitles'): available_subs.update(normal_subtitles) if automatic_captions and self.params.get('writeautomaticsub'): for lang, cap_info in automatic_captions.items(): if lang not in available_subs: available_subs[lang] = cap_info if (not self.params.get('writesubtitles') and not self.params.get('writeautomaticsub') or not available_subs): return None if self.params.get('allsubtitles', False): requested_langs = available_subs.keys() else: if self.params.get('subtitleslangs', False): requested_langs = self.params.get('subtitleslangs') elif 'en' in available_subs: requested_langs = ['en'] else: requested_langs = [list(available_subs.keys())[0]] formats_query = self.params.get('subtitlesformat', 'best') formats_preference = formats_query.split('/') if formats_query else [] subs = {} for lang in requested_langs: formats = available_subs.get(lang) if formats is None: self.report_warning('%s subtitles not available for %s' % (lang, video_id)) continue for ext in formats_preference: if ext == 'best': f = formats[-1] break matches = list(filter(lambda f: f['ext'] == ext, formats)) if matches: f = matches[-1] break else: f = formats[-1] self.report_warning( 'No subtitle format found matching "%s" for language %s, ' 'using %s' % (formats_query, lang, f['ext'])) subs[lang] = f return subs def __forced_printings(self, info_dict, filename, incomplete): def print_mandatory(field): if (self.params.get('force%s' % field, False) and (not incomplete or info_dict.get(field) is not None)): self.to_stdout(info_dict[field]) def print_optional(field): if (self.params.get('force%s' % field, False) and info_dict.get(field) is not None): self.to_stdout(info_dict[field]) print_mandatory('title') print_mandatory('id') if self.params.get('forceurl', False) and not incomplete: if info_dict.get('requested_formats') is not None: for f in info_dict['requested_formats']: self.to_stdout(f['url'] + f.get('play_path', '')) else: # For RTMP URLs, also include the playpath self.to_stdout(info_dict['url'] + info_dict.get('play_path', '')) print_optional('thumbnail') print_optional('description') if self.params.get('forcefilename', False) and filename is not None: self.to_stdout(filename) if self.params.get('forceduration', False) and info_dict.get('duration') is not None: self.to_stdout(formatSeconds(info_dict['duration'])) print_mandatory('format') if self.params.get('forcejson', False): self.to_stdout(json.dumps(info_dict)) def process_info(self, info_dict): """Process a single resolved IE result.""" assert info_dict.get('_type', 'video') == 'video' max_downloads = self.params.get('max_downloads') if max_downloads is not None: if self._num_downloads >= int(max_downloads): raise MaxDownloadsReached() # TODO: backward compatibility, to be removed info_dict['fulltitle'] = info_dict['title'] if 'format' not in info_dict: info_dict['format'] = info_dict['ext'] reason = self._match_entry(info_dict, incomplete=False) if reason is not None: self.to_screen('[download] ' + reason) return self._num_downloads += 1 info_dict['_filename'] = filename = self.prepare_filename(info_dict) # Forced printings self.__forced_printings(info_dict, filename, incomplete=False) # Do nothing else if in simulate mode if self.params.get('simulate', False): return if filename is None: return def ensure_dir_exists(path): try: dn = os.path.dirname(path) if dn and not os.path.exists(dn): os.makedirs(dn) return True except (OSError, IOError) as err: if isinstance(err, OSError) and err.errno == errno.EEXIST: return True self.report_error('unable to create directory ' + error_to_compat_str(err)) return False if not ensure_dir_exists(sanitize_path(encodeFilename(filename))): return if self.params.get('writedescription', False): descfn = replace_extension(filename, 'description', info_dict.get('ext')) if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)): self.to_screen('[info] Video description is already present') elif info_dict.get('description') is None: self.report_warning('There\'s no description to write.') else: try: self.to_screen('[info] Writing video description to: ' + descfn) with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile: descfile.write(info_dict['description']) except (OSError, IOError): self.report_error('Cannot write description file ' + descfn) return if self.params.get('writeannotations', False): annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext')) if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)): self.to_screen('[info] Video annotations are already present') elif not info_dict.get('annotations'): self.report_warning('There are no annotations to write.') else: try: self.to_screen('[info] Writing video annotations to: ' + annofn) with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile: annofile.write(info_dict['annotations']) except (KeyError, TypeError): self.report_warning('There are no annotations to write.') except (OSError, IOError): self.report_error('Cannot write annotations file: ' + annofn) return subtitles_are_requested = any([self.params.get('writesubtitles', False), self.params.get('writeautomaticsub')]) if subtitles_are_requested and info_dict.get('requested_subtitles'): # subtitles download errors are already managed as troubles in relevant IE # that way it will silently go on when used with unsupporting IE subtitles = info_dict['requested_subtitles'] ie = self.get_info_extractor(info_dict['extractor_key']) for sub_lang, sub_info in subtitles.items(): sub_format = sub_info['ext'] sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext')) if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)): self.to_screen('[info] Video subtitle %s.%s is already present' % (sub_lang, sub_format)) else: self.to_screen('[info] Writing video subtitles to: ' + sub_filename) if sub_info.get('data') is not None: try: # Use newline='' to prevent conversion of newline characters # See https://github.com/ytdl-org/youtube-dl/issues/10268 with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile: subfile.write(sub_info['data']) except (OSError, IOError): self.report_error('Cannot write subtitles file ' + sub_filename) return else: try: sub_data = ie._request_webpage( sub_info['url'], info_dict['id'], note=False).read() with io.open(encodeFilename(sub_filename), 'wb') as subfile: subfile.write(sub_data) except (ExtractorError, IOError, OSError, ValueError) as err: self.report_warning('Unable to download subtitle for "%s": %s' % (sub_lang, error_to_compat_str(err))) continue if self.params.get('writeinfojson', False): infofn = replace_extension(filename, 'info.json', info_dict.get('ext')) if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)): self.to_screen('[info] Video description metadata is already present') else: self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn) try: write_json_file(self.filter_requested_info(info_dict), infofn) except (OSError, IOError): self.report_error('Cannot write metadata to JSON file ' + infofn) return self._write_thumbnails(info_dict, filename) if not self.params.get('skip_download', False): try: def dl(name, info): fd = get_suitable_downloader(info, self.params)(self, self.params) for ph in self._progress_hooks: fd.add_progress_hook(ph) if self.params.get('verbose'): self.to_screen('[debug] Invoking downloader on %r' % info.get('url')) return fd.download(name, info) if info_dict.get('requested_formats') is not None: downloaded = [] success = True merger = FFmpegMergerPP(self) if not merger.available: postprocessors = [] self.report_warning('You have requested multiple ' 'formats but ffmpeg or avconv are not installed.' ' The formats won\'t be merged.') else: postprocessors = [merger] def compatible_formats(formats): video, audio = formats # Check extension video_ext, audio_ext = video.get('ext'), audio.get('ext') if video_ext and audio_ext: COMPATIBLE_EXTS = ( ('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma'), ('webm') ) for exts in COMPATIBLE_EXTS: if video_ext in exts and audio_ext in exts: return True # TODO: Check acodec/vcodec return False filename_real_ext = os.path.splitext(filename)[1][1:] filename_wo_ext = ( os.path.splitext(filename)[0] if filename_real_ext == info_dict['ext'] else filename) requested_formats = info_dict['requested_formats'] if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats): info_dict['ext'] = 'mkv' self.report_warning( 'Requested formats are incompatible for merge and will be merged into mkv.') # Ensure filename always has a correct extension for successful merge filename = '%s.%s' % (filename_wo_ext, info_dict['ext']) if os.path.exists(encodeFilename(filename)): self.to_screen( '[download] %s has already been downloaded and ' 'merged' % filename) else: for f in requested_formats: new_info = dict(info_dict) new_info.update(f) fname = prepend_extension( self.prepare_filename(new_info), 'f%s' % f['format_id'], new_info['ext']) if not ensure_dir_exists(fname): return downloaded.append(fname) partial_success = dl(fname, new_info) success = success and partial_success info_dict['__postprocessors'] = postprocessors info_dict['__files_to_merge'] = downloaded else: # Just a single file success = dl(filename, info_dict) except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err: self.report_error('unable to download video data: %s' % error_to_compat_str(err)) return except (OSError, IOError) as err: raise UnavailableVideoError(err) except (ContentTooShortError, ) as err: self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded)) return if success and filename != '-': # Fixup content fixup_policy = self.params.get('fixup') if fixup_policy is None: fixup_policy = 'detect_or_warn' INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.' stretched_ratio = info_dict.get('stretched_ratio') if stretched_ratio is not None and stretched_ratio != 1: if fixup_policy == 'warn': self.report_warning('%s: Non-uniform pixel ratio (%s)' % ( info_dict['id'], stretched_ratio)) elif fixup_policy == 'detect_or_warn': stretched_pp = FFmpegFixupStretchedPP(self) if stretched_pp.available: info_dict.setdefault('__postprocessors', []) info_dict['__postprocessors'].append(stretched_pp) else: self.report_warning( '%s: Non-uniform pixel ratio (%s). %s' % (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE)) else: assert fixup_policy in ('ignore', 'never') if (info_dict.get('requested_formats') is None and info_dict.get('container') == 'm4a_dash'): if fixup_policy == 'warn': self.report_warning( '%s: writing DASH m4a. ' 'Only some players support this container.' % info_dict['id']) elif fixup_policy == 'detect_or_warn': fixup_pp = FFmpegFixupM4aPP(self) if fixup_pp.available: info_dict.setdefault('__postprocessors', []) info_dict['__postprocessors'].append(fixup_pp) else: self.report_warning( '%s: writing DASH m4a. ' 'Only some players support this container. %s' % (info_dict['id'], INSTALL_FFMPEG_MESSAGE)) else: assert fixup_policy in ('ignore', 'never') if (info_dict.get('protocol') == 'm3u8_native' or info_dict.get('protocol') == 'm3u8' and self.params.get('hls_prefer_native')): if fixup_policy == 'warn': self.report_warning('%s: malformed AAC bitstream detected.' % ( info_dict['id'])) elif fixup_policy == 'detect_or_warn': fixup_pp = FFmpegFixupM3u8PP(self) if fixup_pp.available: info_dict.setdefault('__postprocessors', []) info_dict['__postprocessors'].append(fixup_pp) else: self.report_warning( '%s: malformed AAC bitstream detected. %s' % (info_dict['id'], INSTALL_FFMPEG_MESSAGE)) else: assert fixup_policy in ('ignore', 'never') try: self.post_process(filename, info_dict) except (PostProcessingError) as err: self.report_error('postprocessing: %s' % str(err)) return self.record_download_archive(info_dict) def download(self, url_list): """Download a given list of URLs.""" outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL) if (len(url_list) > 1 and outtmpl != '-' and '%' not in outtmpl and self.params.get('max_downloads') != 1): raise SameFileError(outtmpl) for url in url_list: try: # It also downloads the videos res = self.extract_info( url, force_generic_extractor=self.params.get('force_generic_extractor', False)) except UnavailableVideoError: self.report_error('unable to download video') except MaxDownloadsReached: self.to_screen('[info] Maximum number of downloaded files reached.') raise else: if self.params.get('dump_single_json', False): self.to_stdout(json.dumps(res)) return self._download_retcode def download_with_info_file(self, info_filename): with contextlib.closing(fileinput.FileInput( [info_filename], mode='r', openhook=fileinput.hook_encoded('utf-8'))) as f: # FileInput doesn't have a read method, we can't call json.load info = self.filter_requested_info(json.loads('\n'.join(f))) try: self.process_ie_result(info, download=True) except DownloadError: webpage_url = info.get('webpage_url') if webpage_url is not None: self.report_warning('The info failed to download, trying with "%s"' % webpage_url) return self.download([webpage_url]) else: raise return self._download_retcode @staticmethod def filter_requested_info(info_dict): return dict( (k, v) for k, v in info_dict.items() if k not in ['requested_formats', 'requested_subtitles']) def post_process(self, filename, ie_info): """Run all the postprocessors on the given file.""" info = dict(ie_info) info['filepath'] = filename pps_chain = [] if ie_info.get('__postprocessors') is not None: pps_chain.extend(ie_info['__postprocessors']) pps_chain.extend(self._pps) for pp in pps_chain: files_to_delete = [] try: files_to_delete, info = pp.run(info) except PostProcessingError as e: self.report_error(e.msg) if files_to_delete and not self.params.get('keepvideo', False): for old_filename in files_to_delete: self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename) try: os.remove(encodeFilename(old_filename)) except (IOError, OSError): self.report_warning('Unable to remove downloaded original file') def _make_archive_id(self, info_dict): video_id = info_dict.get('id') if not video_id: return # Future-proof against any change in case # and backwards compatibility with prior versions extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist if extractor is None: url = str_or_none(info_dict.get('url')) if not url: return # Try to find matching extractor for the URL and take its ie_key for ie in self._ies: if ie.suitable(url): extractor = ie.ie_key() break else: return return extractor.lower() + ' ' + video_id def in_download_archive(self, info_dict): fn = self.params.get('download_archive') if fn is None: return False vid_id = self._make_archive_id(info_dict) if not vid_id: return False # Incomplete video information try: with locked_file(fn, 'r', encoding='utf-8') as archive_file: for line in archive_file: if line.strip() == vid_id: return True except IOError as ioe: if ioe.errno != errno.ENOENT: raise return False def record_download_archive(self, info_dict): fn = self.params.get('download_archive') if fn is None: return vid_id = self._make_archive_id(info_dict) assert vid_id with locked_file(fn, 'a', encoding='utf-8') as archive_file: archive_file.write(vid_id + '\n') @staticmethod def format_resolution(format, default='unknown'): if format.get('vcodec') == 'none': return 'audio only' if format.get('resolution') is not None: return format['resolution'] if format.get('height') is not None: if format.get('width') is not None: res = '%sx%s' % (format['width'], format['height']) else: res = '%sp' % format['height'] elif format.get('width') is not None: res = '%dx?' % format['width'] else: res = default return res def _format_note(self, fdict): res = '' if fdict.get('ext') in ['f4f', 'f4m']: res += '(unsupported) ' if fdict.get('language'): if res: res += ' ' res += '[%s] ' % fdict['language'] if fdict.get('format_note') is not None: res += fdict['format_note'] + ' ' if fdict.get('tbr') is not None: res += '%4dk ' % fdict['tbr'] if fdict.get('container') is not None: if res: res += ', ' res += '%s container' % fdict['container'] if (fdict.get('vcodec') is not None and fdict.get('vcodec') != 'none'): if res: res += ', ' res += fdict['vcodec'] if fdict.get('vbr') is not None: res += '@' elif fdict.get('vbr') is not None and fdict.get('abr') is not None: res += 'video@' if fdict.get('vbr') is not None: res += '%4dk' % fdict['vbr'] if fdict.get('fps') is not None: if res: res += ', ' res += '%sfps' % fdict['fps'] if fdict.get('acodec') is not None: if res: res += ', ' if fdict['acodec'] == 'none': res += 'video only' else: res += '%-5s' % fdict['acodec'] elif fdict.get('abr') is not None: if res: res += ', ' res += 'audio' if fdict.get('abr') is not None: res += '@%3dk' % fdict['abr'] if fdict.get('asr') is not None: res += ' (%5dHz)' % fdict['asr'] if fdict.get('filesize') is not None: if res: res += ', ' res += format_bytes(fdict['filesize']) elif fdict.get('filesize_approx') is not None: if res: res += ', ' res += '~' + format_bytes(fdict['filesize_approx']) return res def list_formats(self, info_dict): formats = info_dict.get('formats', [info_dict]) table = [ [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)] for f in formats if f.get('preference') is None or f['preference'] >= -1000] if len(formats) > 1: table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)' header_line = ['format code', 'extension', 'resolution', 'note'] self.to_screen( '[info] Available formats for %s:\n%s' % (info_dict['id'], render_table(header_line, table))) def list_thumbnails(self, info_dict): thumbnails = info_dict.get('thumbnails') if not thumbnails: self.to_screen('[info] No thumbnails present for %s' % info_dict['id']) return self.to_screen( '[info] Thumbnails for %s:' % info_dict['id']) self.to_screen(render_table( ['ID', 'width', 'height', 'URL'], [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails])) def list_subtitles(self, video_id, subtitles, name='subtitles'): if not subtitles: self.to_screen('%s has no %s' % (video_id, name)) return self.to_screen( 'Available %s for %s:' % (name, video_id)) self.to_screen(render_table( ['Language', 'formats'], [[lang, ', '.join(f['ext'] for f in reversed(formats))] for lang, formats in subtitles.items()])) def urlopen(self, req): """ Start an HTTP download """ if isinstance(req, compat_basestring): req = sanitized_Request(req) return self._opener.open(req, timeout=self._socket_timeout) def print_debug_header(self): if not self.params.get('verbose'): return if type('') is not compat_str: # Python 2.6 on SLES11 SP1 (https://github.com/ytdl-org/youtube-dl/issues/3326) self.report_warning( 'Your Python is broken! Update to a newer and supported version') stdout_encoding = getattr( sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__) encoding_str = ( '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % ( locale.getpreferredencoding(), sys.getfilesystemencoding(), stdout_encoding, self.get_encoding())) write_string(encoding_str, encoding=None) self._write_string('[debug] youtube-dl version ' + __version__ + '\n') if _LAZY_LOADER: self._write_string('[debug] Lazy loading extractors enabled' + '\n') try: sp = subprocess.Popen( ['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(os.path.abspath(__file__))) out, err = sp.communicate() out = out.decode().strip() if re.match('[0-9a-f]+', out): self._write_string('[debug] Git HEAD: ' + out + '\n') except Exception: try: sys.exc_clear() except Exception: pass def python_implementation(): impl_name = platform.python_implementation() if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'): return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3] return impl_name self._write_string('[debug] Python version %s (%s) - %s\n' % ( platform.python_version(), python_implementation(), platform_name())) exe_versions = FFmpegPostProcessor.get_versions(self) exe_versions['rtmpdump'] = rtmpdump_version() exe_versions['phantomjs'] = PhantomJSwrapper._version() exe_str = ', '.join( '%s %s' % (exe, v) for exe, v in sorted(exe_versions.items()) if v ) if not exe_str: exe_str = 'none' self._write_string('[debug] exe versions: %s\n' % exe_str) proxy_map = {} for handler in self._opener.handlers: if hasattr(handler, 'proxies'): proxy_map.update(handler.proxies) self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n') if self.params.get('call_home', False): ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8') self._write_string('[debug] Public IP address: %s\n' % ipaddr) latest_version = self.urlopen( 'https://yt-dl.org/latest/version').read().decode('utf-8') if version_tuple(latest_version) > version_tuple(__version__): self.report_warning( 'You are using an outdated version (newest version: %s)! ' 'See https://yt-dl.org/update if you need help updating.' % latest_version) def _setup_opener(self): timeout_val = self.params.get('socket_timeout') self._socket_timeout = 600 if timeout_val is None else float(timeout_val) opts_cookiefile = self.params.get('cookiefile') opts_proxy = self.params.get('proxy') if opts_cookiefile is None: self.cookiejar = compat_cookiejar.CookieJar() else: opts_cookiefile = expand_path(opts_cookiefile) self.cookiejar = YoutubeDLCookieJar(opts_cookiefile) if os.access(opts_cookiefile, os.R_OK): self.cookiejar.load(ignore_discard=True, ignore_expires=True) cookie_processor = YoutubeDLCookieProcessor(self.cookiejar) if opts_proxy is not None: if opts_proxy == '': proxies = {} else: proxies = {'http': opts_proxy, 'https': opts_proxy} else: proxies = compat_urllib_request.getproxies() # Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805) if 'http' in proxies and 'https' not in proxies: proxies['https'] = proxies['http'] proxy_handler = PerRequestProxyHandler(proxies) debuglevel = 1 if self.params.get('debug_printtraffic') else 0 https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel) ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel) redirect_handler = YoutubeDLRedirectHandler() data_handler = compat_urllib_request_DataHandler() # When passing our own FileHandler instance, build_opener won't add the # default FileHandler and allows us to disable the file protocol, which # can be used for malicious purposes (see # https://github.com/ytdl-org/youtube-dl/issues/8227) file_handler = compat_urllib_request.FileHandler() def file_open(*args, **kwargs): raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons') file_handler.file_open = file_open opener = compat_urllib_request.build_opener( proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler) # Delete the default user-agent header, which would otherwise apply in # cases where our custom HTTP handler doesn't come into play # (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details) opener.addheaders = [] self._opener = opener def encode(self, s): if isinstance(s, bytes): return s # Already encoded try: return s.encode(self.get_encoding()) except UnicodeEncodeError as err: err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.' raise def get_encoding(self): encoding = self.params.get('encoding') if encoding is None: encoding = preferredencoding() return encoding def _write_thumbnails(self, info_dict, filename): if self.params.get('writethumbnail', False): thumbnails = info_dict.get('thumbnails') if thumbnails: thumbnails = [thumbnails[-1]] elif self.params.get('write_all_thumbnails', False): thumbnails = info_dict.get('thumbnails') else: return if not thumbnails: # No thumbnails present, so return immediately return for t in thumbnails: thumb_ext = determine_ext(t['url'], 'jpg') suffix = '_%s' % t['id'] if len(thumbnails) > 1 else '' thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else '' t['filename'] = thumb_filename = replace_extension(filename + suffix, thumb_ext, info_dict.get('ext')) if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)): self.to_screen('[%s] %s: Thumbnail %sis already present' % (info_dict['extractor'], info_dict['id'], thumb_display_id)) else: self.to_screen('[%s] %s: Downloading thumbnail %s...' % (info_dict['extractor'], info_dict['id'], thumb_display_id)) try: uf = self.urlopen(t['url']) with open(encodeFilename(thumb_filename), 'wb') as thumbf: shutil.copyfileobj(uf, thumbf) if info_dict['extractor'] == 'youtube': img_for_size=PIL.Image.open(thumb_filename) width_image, height_image = img_for_size.size if width_image == 1280 and height_image == 720: self.to_screen('[%s] %s: Resizing thumbnail %sto: 720x720px' % (info_dict['extractor'], info_dict['id'], thumb_display_id)) img=Image.open(thumb_filename) b=(280,0,1000,720) c_i=img.crop(box=b) c_i.save(thumb_filename) else : pass self.to_screen('[%s] %s: Writing thumbnail %sto: %s' % (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename)) except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err: self.report_warning('Unable to download thumbnail "%s": %s' % (t['url'], error_to_compat_str(err)))
[]
[]
[]
[]
[]
python
0
0
test/plugins/test_symbols.py
import os import sys import pytest from pygls import uris from pygls.plugins.symbols import pygls_document_symbols from pygls.lsp import SymbolKind from pygls.workspace import Document PY2 = sys.version[0] == '2' LINUX = sys.platform.startswith('linux') CI = os.environ.get('CI') DOC_URI = uris.from_fs_path(__file__) DOC = """import sys a = 'hello' class B: def __init__(self): x = 2 self.y = x def main(x): y = 2 * x return y """ def helper_check_symbols_all_scope(symbols): # All eight symbols (import sys, a, B, __init__, x, y, main, y) assert len(symbols) == 8 def sym(name): return [s for s in symbols if s['name'] == name][0] # Check we have some sane mappings to VSCode constants assert sym('a')['kind'] == SymbolKind.Variable assert sym('B')['kind'] == SymbolKind.Class assert sym('__init__')['kind'] == SymbolKind.Method assert sym('main')['kind'] == SymbolKind.Function # Not going to get too in-depth here else we're just testing Jedi assert sym('a')['location']['range']['start'] == {'line': 2, 'character': 0} def test_symbols(config, workspace): doc = Document(DOC_URI, workspace, DOC) config.update({'plugins': {'jedi_symbols': {'all_scopes': False}}}) symbols = pygls_document_symbols(config, doc) # All four symbols (import sys, a, B, main) # y is not in the root scope, it shouldn't be returned assert len(symbols) == 5 def sym(name): return [s for s in symbols if s['name'] == name][0] # Check we have some sane mappings to VSCode constants assert sym('a')['kind'] == SymbolKind.Variable assert sym('B')['kind'] == SymbolKind.Class assert sym('main')['kind'] == SymbolKind.Function # Not going to get too in-depth here else we're just testing Jedi assert sym('a')['location']['range']['start'] == {'line': 2, 'character': 0} # Ensure that the symbol range spans the whole definition assert sym('main')['location']['range']['start'] == {'line': 9, 'character': 0} assert sym('main')['location']['range']['end'] == {'line': 12, 'character': 0} def test_symbols_all_scopes(config, workspace): doc = Document(DOC_URI, workspace, DOC) symbols = pygls_document_symbols(config, doc) helper_check_symbols_all_scope(symbols) @pytest.mark.skipif(PY2 or not LINUX or not CI, reason="tested on linux and python 3 only") def test_symbols_all_scopes_with_jedi_environment(workspace): doc = Document(DOC_URI, workspace, DOC) # Update config extra environment env_path = '/tmp/pyenv/bin/python' settings = {'pygls': {'plugins': {'jedi': {'environment': env_path}}}} doc.update_config(settings) symbols = pygls_document_symbols(doc._config, doc) helper_check_symbols_all_scope(symbols)
[]
[]
[ "CI" ]
[]
["CI"]
python
1
0
connectorx-python/connectorx/tests/test_redshift.py
import os import numpy as np import pandas as pd import pytest from pandas.testing import assert_frame_equal from .. import read_sql @pytest.fixture(scope="module") # type: ignore def redshift_url() -> str: conn = os.environ["REDSHIFT_URL"] return conn @pytest.mark.skipif(os.environ.get("TEST_COVER", "main") != "all", reason="Only test main wire protocols unless TEST_COVER=all") def test_redshift_without_partition(redshift_url: str) -> None: query = "SELECT * FROM test_table" df = read_sql(redshift_url, query, protocol="cursor") # result from redshift might have different order each time df.sort_values(by="test_int", inplace=True, ignore_index=True) expected = pd.DataFrame( index=range(6), data={ "test_int": pd.Series([0, 1, 2, 3, 4, 1314], dtype="Int64"), "test_nullint": pd.Series([5, 3, None, 7, 9, 2], dtype="Int64"), "test_str": pd.Series( ["a", "str1", "str2", "b", "c", None], dtype="object" ), "test_float": pd.Series([3.1, None, 2.2, 3, 7.8, -10], dtype="float64"), "test_bool": pd.Series( [None, True, False, False, None, True], dtype="boolean" ), }, ) assert_frame_equal(df, expected, check_names=True) @pytest.mark.skipif(os.environ.get("TEST_COVER", "main") != "all", reason="Only test main wire protocols unless TEST_COVER=all") def test_redshift_with_partition(redshift_url: str) -> None: query = "SELECT * FROM test_table" df = read_sql( redshift_url, query, partition_on="test_int", partition_range=(0, 2000), partition_num=3, protocol="cursor" ) # result from redshift might have different order each time df.sort_values(by="test_int", inplace=True, ignore_index=True) expected = pd.DataFrame( index=range(6), data={ "test_int": pd.Series([0, 1, 2, 3, 4, 1314], dtype="Int64"), "test_nullint": pd.Series([5, 3, None, 7, 9, 2], dtype="Int64"), "test_str": pd.Series( ["a", "str1", "str2", "b", "c", None], dtype="object" ), "test_float": pd.Series([3.1, None, 2.2, 3, 7.8, -10], dtype="float64"), "test_bool": pd.Series( [None, True, False, False, None, True], dtype="boolean" ), }, ) assert_frame_equal(df, expected, check_names=True) @pytest.mark.skipif(os.environ.get("TEST_COVER", "main") != "all", reason="Only test main wire protocols unless TEST_COVER=all") def test_redshift_types(redshift_url: str) -> None: query = "SELECT test_int16, test_char, test_time, test_datetime FROM test_types" df = read_sql(redshift_url, query, protocol="cursor") # result from redshift might have different order each time df.sort_values(by="test_int16", inplace=True, ignore_index=True) expected = pd.DataFrame( index=range(4), data={ "test_int16": pd.Series([0, 1, 2, 3], dtype="Int64"), "test_char": pd.Series(["a", "b", "c", "d"], dtype="object"), "test_time": pd.Series( ["08:12:40", "10:03:00", "23:00:10", "18:30:00"], dtype="object" ), "test_datetime": pd.Series( [ np.datetime64("2007-01-01T10:00:19"), np.datetime64("2005-01-01T22:03:00"), None, np.datetime64("1987-01-01T11:00:00"), ], dtype="datetime64[ns]" ), }, ) assert_frame_equal(df, expected, check_names=True) @pytest.mark.skipif(os.environ.get("TEST_COVER", "main") != "all", reason="Only test main wire protocols unless TEST_COVER=all") def test_read_sql_on_utf8(redshift_url: str) -> None: query = "SELECT * FROM test_str" df = read_sql(redshift_url, query, protocol="cursor") # result from redshift might have different order each time df.sort_values(by="id", inplace=True, ignore_index=True) expected = pd.DataFrame( index=range(8), data={ "id": pd.Series([0, 1, 2, 3, 4, 5, 6, 7], dtype="Int64"), "test_language": pd.Series( [ "English", "中文", "日本語", "русский", "Emoji", "Latin1", "Extra", "Mixed", ], dtype="object", ), "test_hello": pd.Series( [ "Hello", "你好", "こんにちは", "Здра́вствуйте", "😁😂😜", "¥§¤®ð", "y̆", "Ha好ち😁ðy̆", ], dtype="object", ), }, ) assert_frame_equal(df, expected, check_names=True)
[]
[]
[ "TEST_COVER", "REDSHIFT_URL" ]
[]
["TEST_COVER", "REDSHIFT_URL"]
python
2
0
pkg/config/config.go
package config import ( "bytes" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strings" "time" "github.com/BurntSushi/toml" "github.com/mitchellh/go-homedir" log "github.com/sirupsen/logrus" "github.com/spf13/viper" prefixed "github.com/x-cray/logrus-prefixed-formatter" "github.com/stripe/stripe-cli/pkg/ansi" ) // ColorOn represnets the on-state for colors const ColorOn = "on" // ColorOff represents the off-state for colors const ColorOff = "off" // ColorAuto represents the auto-state for colors const ColorAuto = "auto" // Config handles all overall configuration for the CLI type Config struct { Color string LogLevel string Profile Profile ProfilesFile string } // GetConfigFolder retrieves the folder where the profiles file is stored // It searches for the xdg environment path first and will secondarily // place it in the home directory func (c *Config) GetConfigFolder(xdgPath string) string { configPath := xdgPath log.WithFields(log.Fields{ "prefix": "config.Config.GetProfilesFolder", "path": configPath, }).Debug("Using profiles file") if configPath == "" { home, err := homedir.Dir() if err != nil { fmt.Println(err) os.Exit(1) } configPath = filepath.Join(home, ".config") } return filepath.Join(configPath, "stripe") } // InitConfig reads in profiles file and ENV variables if set. func (c *Config) InitConfig() { logFormatter := &prefixed.TextFormatter{ FullTimestamp: true, TimestampFormat: time.RFC1123, } if c.ProfilesFile != "" { viper.SetConfigFile(c.ProfilesFile) } else { configFolder := c.GetConfigFolder(os.Getenv("XDG_CONFIG_HOME")) configFile := filepath.Join(configFolder, "config.toml") c.ProfilesFile = configFile viper.SetConfigType("toml") viper.SetConfigFile(configFile) } // If a profiles file is found, read it in. if err := viper.ReadInConfig(); err == nil { log.WithFields(log.Fields{ "prefix": "config.Config.InitConfig", "path": viper.ConfigFileUsed(), }).Debug("Using profiles file") } if c.Profile.DeviceName == "" { deviceName, err := os.Hostname() if err != nil { deviceName = "unknown" } c.Profile.DeviceName = deviceName } color, err := c.Profile.GetColor() if err != nil { log.Fatalf("%s", err) } switch color { case ColorOn: ansi.ForceColors = true logFormatter.ForceColors = true case ColorOff: ansi.DisableColors = true logFormatter.DisableColors = true case ColorAuto: // Nothing to do default: log.Fatalf("Unrecognized color value: %s. Expected one of on, off, auto.", c.Color) } log.SetFormatter(logFormatter) // Set log level switch c.LogLevel { case "debug": log.SetLevel(log.DebugLevel) case "info": log.SetLevel(log.InfoLevel) case "warn": log.SetLevel(log.WarnLevel) case "error": log.SetLevel(log.ErrorLevel) default: log.Fatalf("Unrecognized log level value: %s. Expected one of debug, info, warn, error.", c.LogLevel) } } // EditConfig opens the configuration file in the default editor. func (c *Config) EditConfig() error { var err error fmt.Println("Opening config file:", c.ProfilesFile) switch runtime.GOOS { case "darwin", "linux": editor := os.Getenv("EDITOR") if editor == "" { editor = "vi" } cmd := exec.Command(editor, c.ProfilesFile) // Some editors detect whether they have control of stdin/out and will // fail if they do not. cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout return cmd.Run() case "windows": // As far as I can tell, Windows doesn't have an easily accesible or // comparable option to $EDITOR, so default to notepad for now err = exec.Command("notepad", c.ProfilesFile).Run() default: err = fmt.Errorf("unsupported platform") } return err } // PrintConfig outputs the contents of the configuration file. func (c *Config) PrintConfig() error { if c.Profile.ProfileName == "default" { configFile, err := ioutil.ReadFile(c.ProfilesFile) if err != nil { return err } fmt.Print(string(configFile)) } else { configs := viper.GetStringMapString(c.Profile.ProfileName) if len(configs) > 0 { fmt.Println(fmt.Sprintf("[%s]", c.Profile.ProfileName)) for field, value := range configs { fmt.Println(fmt.Sprintf(" %s=%s", field, value)) } } } return nil } // Temporary workaround until https://github.com/spf13/viper/pull/519 can remove a key from viper func removeKey(v *viper.Viper, key string) (*viper.Viper, error) { configMap := v.AllSettings() path := strings.Split(key, ".") lastKey := strings.ToLower(path[len(path)-1]) deepestMap := deepSearch(configMap, path[0:len(path)-1]) delete(deepestMap, lastKey) buf := new(bytes.Buffer) encodeErr := toml.NewEncoder(buf).Encode(configMap) if encodeErr != nil { return nil, encodeErr } nv := viper.New() nv.SetConfigType("toml") // hint to viper that we've encoded the data as toml err := nv.ReadConfig(buf) if err != nil { return nil, err } return nv, nil } func makePath(path string) error { dir := filepath.Dir(path) if _, err := os.Stat(dir); os.IsNotExist(err) { err = os.MkdirAll(dir, os.ModePerm) if err != nil { return err } } return nil } // taken from https://github.com/spf13/viper/blob/master/util.go#L199, // we need this to delete configs, remove when viper supprts unset natively func deepSearch(m map[string]interface{}, path []string) map[string]interface{} { for _, k := range path { m2, ok := m[k] if !ok { // intermediate key does not exist // => create it and continue from there m3 := make(map[string]interface{}) m[k] = m3 m = m3 continue } m3, ok := m2.(map[string]interface{}) if !ok { // intermediate key is a value // => replace with a new map m3 = make(map[string]interface{}) m[k] = m3 } // continue search from here m = m3 } return m }
[ "\"XDG_CONFIG_HOME\"", "\"EDITOR\"" ]
[]
[ "EDITOR", "XDG_CONFIG_HOME" ]
[]
["EDITOR", "XDG_CONFIG_HOME"]
go
2
0
ns/nslogic.go
package ns /* Copyright 2019 Crunchy Data Solutions, 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 ( "bytes" "encoding/json" "errors" "os" "strings" "time" "github.com/crunchydata/postgres-operator/config" "github.com/crunchydata/postgres-operator/events" "github.com/crunchydata/postgres-operator/kubeapi" log "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/util/validation" "k8s.io/client-go/kubernetes" ) const PGO_TARGET_ROLE = "pgo-target-role" const PGO_TARGET_ROLE_BINDING = "pgo-target-role-binding" const PGO_TARGET_SERVICE_ACCOUNT = "pgo-target" const PGO_BACKREST_ROLE = "pgo-backrest-role" const PGO_BACKREST_SERVICE_ACCOUNT = "pgo-backrest" const PGO_BACKREST_ROLE_BINDING = "pgo-backrest-role-binding" //pgo-backrest-sa.json type PgoBackrestServiceAccount struct { TargetNamespace string } //pgo-target-sa.json type PgoTargetServiceAccount struct { TargetNamespace string } //pgo-target-role-binding.json type PgoTargetRoleBinding struct { TargetNamespace string OperatorNamespace string } //pgo-backrest-role.json type PgoBackrestRole struct { TargetNamespace string } //pgo-backrest-role-binding.json type PgoBackrestRoleBinding struct { TargetNamespace string } //pgo-target-role.json type PgoTargetRole struct { TargetNamespace string } // CreateNamespace ... func CreateNamespace(clientset *kubernetes.Clientset, installationName, pgoNamespace, createdBy, newNs string) error { log.Debugf("CreateNamespace %s %s %s", pgoNamespace, createdBy, newNs) //validate the list of args (namespaces) errs := validation.IsDNS1035Label(newNs) if len(errs) > 0 { return errors.New("invalid namespace name format " + errs[0] + " namespace name " + newNs) } _, found, _ := kubeapi.GetNamespace(clientset, newNs) if found { return errors.New("namespace " + newNs + " already exists on this Kube cluster") } //define the new namespace n := v1.Namespace{} n.ObjectMeta.Labels = make(map[string]string) n.ObjectMeta.Labels[config.LABEL_VENDOR] = config.LABEL_CRUNCHY n.ObjectMeta.Labels[config.LABEL_PGO_CREATED_BY] = createdBy n.ObjectMeta.Labels[config.LABEL_PGO_INSTALLATION_NAME] = installationName n.Name = newNs err := kubeapi.CreateNamespace(clientset, &n) if err != nil { return errors.New("namespace create error " + newNs + err.Error()) } log.Debugf("CreateNamespace %s created by %s", newNs, createdBy) //apply targeted rbac rules here err = installTargetRBAC(clientset, pgoNamespace, newNs) if err != nil { return errors.New("namespace RBAC create error " + newNs + err.Error()) } //publish event topics := make([]string, 1) topics[0] = events.EventTopicPGO f := events.EventPGOCreateNamespaceFormat{ EventHeader: events.EventHeader{ Namespace: pgoNamespace, Username: createdBy, Topic: topics, Timestamp: time.Now(), EventType: events.EventPGOCreateNamespace, }, CreatedNamespace: newNs, } err = events.Publish(f) if err != nil { return err } return nil } // DeleteNamespace ... func DeleteNamespace(clientset *kubernetes.Clientset, installationName, pgoNamespace, deletedBy, ns string) error { theNs, found, _ := kubeapi.GetNamespace(clientset, ns) if !found { return errors.New("namespace " + ns + " not found") } if theNs.ObjectMeta.Labels[config.LABEL_VENDOR] != config.LABEL_CRUNCHY || theNs.ObjectMeta.Labels[config.LABEL_PGO_INSTALLATION_NAME] != installationName { errors.New("namespace " + ns + " not owned by crunchy data or not part of Operator installation " + installationName) } err := kubeapi.DeleteNamespace(clientset, ns) if err != nil { return err } log.Debugf("DeleteNamespace %s deleted by %s", ns, deletedBy) //publish the namespace delete event topics := make([]string, 1) topics[0] = events.EventTopicPGO f := events.EventPGODeleteNamespaceFormat{ EventHeader: events.EventHeader{ Namespace: pgoNamespace, Username: deletedBy, Topic: topics, Timestamp: time.Now(), EventType: events.EventPGODeleteNamespace, }, DeletedNamespace: ns, } err = events.Publish(f) if err != nil { return err } return nil } func installTargetRBAC(clientset *kubernetes.Clientset, operatorNamespace, targetNamespace string) error { var err error err = CreatePGOTargetServiceAccount(clientset, targetNamespace) if err != nil { log.Error(err) return err } err = CreatePGOBackrestServiceAccount(clientset, targetNamespace) if err != nil { log.Error(err) return err } err = CreatePGOTargetRole(clientset, targetNamespace) if err != nil { log.Error(err) return err } err = CreatePGOTargetRoleBinding(clientset, targetNamespace, operatorNamespace) if err != nil { log.Error(err) return err } err = CreatePGOBackrestRole(clientset, targetNamespace) if err != nil { log.Error(err) return err } err = CreatePGOBackrestRoleBinding(clientset, targetNamespace) if err != nil { log.Error(err) return err } return nil } func CreatePGOTargetRoleBinding(clientset *kubernetes.Clientset, targetNamespace, operatorNamespace string) error { //check for rolebinding existing _, found, _ := kubeapi.GetRoleBinding(clientset, PGO_TARGET_ROLE_BINDING, targetNamespace) if found { log.Infof("rolebinding %s already exists, will delete and re-create", PGO_TARGET_ROLE_BINDING) err := kubeapi.DeleteRoleBinding(clientset, PGO_TARGET_ROLE_BINDING, targetNamespace) if err != nil { log.Errorf("error deleting rolebinding %s %s", PGO_TARGET_ROLE_BINDING, err.Error()) return err } } var buffer bytes.Buffer err := config.PgoTargetRoleBindingTemplate.Execute(&buffer, PgoTargetRoleBinding{ TargetNamespace: targetNamespace, OperatorNamespace: operatorNamespace, }) if err != nil { log.Error(err.Error()) return err } log.Info(buffer.String()) rb := rbacv1.RoleBinding{} err = json.Unmarshal(buffer.Bytes(), &rb) if err != nil { log.Error("error unmarshalling " + config.PGOTargetRoleBindingPath + " json RoleBinding " + err.Error()) return err } err = kubeapi.CreateRoleBinding(clientset, &rb, targetNamespace) if err != nil { return err } return err } func CreatePGOBackrestRole(clientset *kubernetes.Clientset, targetNamespace string) error { //check for role existing _, found, _ := kubeapi.GetRole(clientset, PGO_BACKREST_ROLE, targetNamespace) if found { log.Infof("role %s already exists, will delete and re-create", PGO_BACKREST_ROLE) err := kubeapi.DeleteRole(clientset, PGO_BACKREST_ROLE, targetNamespace) if err != nil { log.Errorf("error deleting role %s %s", PGO_BACKREST_ROLE, err.Error()) return err } } var buffer bytes.Buffer err := config.PgoBackrestRoleTemplate.Execute(&buffer, PgoBackrestRole{ TargetNamespace: targetNamespace, }) if err != nil { log.Error(err.Error()) return err } log.Info(buffer.String()) r := rbacv1.Role{} err = json.Unmarshal(buffer.Bytes(), &r) if err != nil { log.Error("error unmarshalling " + config.PGOBackrestRolePath + " json Role " + err.Error()) return err } err = kubeapi.CreateRole(clientset, &r, targetNamespace) if err != nil { return err } return err } func CreatePGOTargetRole(clientset *kubernetes.Clientset, targetNamespace string) error { //check for role existing _, found, _ := kubeapi.GetRole(clientset, PGO_TARGET_ROLE, targetNamespace) if found { log.Infof("role %s already exists, will delete and re-create", PGO_TARGET_ROLE) err := kubeapi.DeleteRole(clientset, PGO_TARGET_ROLE, targetNamespace) if err != nil { log.Errorf("error deleting role %s %s", PGO_TARGET_ROLE, err.Error()) return err } } var buffer bytes.Buffer err := config.PgoTargetRoleTemplate.Execute(&buffer, PgoTargetRole{ TargetNamespace: targetNamespace, }) if err != nil { log.Error(err.Error()) return err } log.Info(buffer.String()) r := rbacv1.Role{} err = json.Unmarshal(buffer.Bytes(), &r) if err != nil { log.Error("error unmarshalling " + config.PGOTargetRolePath + " json Role " + err.Error()) return err } err = kubeapi.CreateRole(clientset, &r, targetNamespace) if err != nil { return err } return err } func CreatePGOBackrestRoleBinding(clientset *kubernetes.Clientset, targetNamespace string) error { //check for rolebinding existing _, found, _ := kubeapi.GetRoleBinding(clientset, PGO_BACKREST_ROLE_BINDING, targetNamespace) if found { log.Infof("rolebinding %s already exists, will delete and re-create", PGO_BACKREST_ROLE_BINDING) err := kubeapi.DeleteRoleBinding(clientset, PGO_BACKREST_ROLE_BINDING, targetNamespace) if err != nil { log.Errorf("error deleting rolebinding %s %s", PGO_BACKREST_ROLE_BINDING, err.Error()) return err } } var buffer bytes.Buffer err := config.PgoBackrestRoleBindingTemplate.Execute(&buffer, PgoBackrestRoleBinding{ TargetNamespace: targetNamespace, }) if err != nil { log.Error(err.Error() + " on " + config.PGOBackrestRoleBindingPath) return err } log.Info(buffer.String()) rb := rbacv1.RoleBinding{} err = json.Unmarshal(buffer.Bytes(), &rb) if err != nil { log.Error("error unmarshalling " + config.PGOBackrestRoleBindingPath + " json RoleBinding " + err.Error()) return err } err = kubeapi.CreateRoleBinding(clientset, &rb, targetNamespace) if err != nil { return err } return err } // UpdateNamespace ... func UpdateNamespace(clientset *kubernetes.Clientset, installationName, pgoNamespace, updatedBy, ns string) error { log.Debugf("UpdateNamespace %s %s %s %s", installationName, pgoNamespace, updatedBy, ns) theNs, found, _ := kubeapi.GetNamespace(clientset, ns) if !found { return errors.New("namespace " + ns + " doesn't exist") } //update the labels on the namespace (own it) if found { if theNs.ObjectMeta.Labels == nil { theNs.ObjectMeta.Labels = make(map[string]string) } theNs.ObjectMeta.Labels[config.LABEL_VENDOR] = config.LABEL_CRUNCHY theNs.ObjectMeta.Labels[config.LABEL_PGO_INSTALLATION_NAME] = installationName err := kubeapi.UpdateNamespace(clientset, theNs) if err != nil { return err } } //apply targeted rbac rules here err := installTargetRBAC(clientset, pgoNamespace, ns) if err != nil { return errors.New("namespace RBAC create error " + ns + err.Error()) } //publish event topics := make([]string, 1) topics[0] = events.EventTopicPGO f := events.EventPGOCreateNamespaceFormat{ EventHeader: events.EventHeader{ Namespace: pgoNamespace, Username: updatedBy, Topic: topics, Timestamp: time.Now(), EventType: events.EventPGOCreateNamespace, }, CreatedNamespace: ns, } err = events.Publish(f) if err != nil { return err } return nil } func CreatePGOBackrestServiceAccount(clientset *kubernetes.Clientset, targetNamespace string) error { //check for serviceaccount existing _, found, _ := kubeapi.GetServiceAccount(clientset, PGO_BACKREST_SERVICE_ACCOUNT, targetNamespace) if found { log.Infof("serviceaccount %s already exists, will delete and re-create", PGO_BACKREST_SERVICE_ACCOUNT) err := kubeapi.DeleteServiceAccount(clientset, PGO_BACKREST_SERVICE_ACCOUNT, targetNamespace) if err != nil { log.Errorf("error deleting serviceaccount %s %s", PGO_BACKREST_SERVICE_ACCOUNT, err.Error()) return err } } var buffer bytes.Buffer err := config.PgoBackrestServiceAccountTemplate.Execute(&buffer, PgoBackrestServiceAccount{ TargetNamespace: targetNamespace, }) if err != nil { log.Error(err.Error() + " on " + config.PGOBackrestServiceAccountPath) return err } log.Info(buffer.String()) rb := v1.ServiceAccount{} err = json.Unmarshal(buffer.Bytes(), &rb) if err != nil { log.Error("error unmarshalling " + config.PGOBackrestServiceAccountPath + " json ServiceAccount " + err.Error()) return err } err = kubeapi.CreateServiceAccount(clientset, &rb, targetNamespace) if err != nil { return err } return err } func ValidateNamespaces(clientset *kubernetes.Clientset, installationName, pgoNamespace string) error { raw := os.Getenv("NAMESPACE") //the case of 'all' namespaces if raw == "" { return nil } allFound := false nsList := strings.Split(raw, ",") //check for the invalid case where a user has NAMESPACE=demo1,,demo2 if len(nsList) > 1 { for i := 0; i < len(nsList); i++ { if nsList[i] == "" { allFound = true } } } if allFound && len(nsList) > 1 { return errors.New("'' (empty string), found within the NAMESPACE environment variable along with other namespaces, this is not an accepted format") } //check for the case of a non-existing namespace being used for i := 0; i < len(nsList); i++ { namespace, found, _ := kubeapi.GetNamespace(clientset, nsList[i]) if !found { //return errors.New("NAMESPACE environment variable contains a namespace of " + nsList[i] + " but that is not found on this kube system") //create the namespace here err := CreateNamespace(clientset, installationName, pgoNamespace, "operator-bootstrap", nsList[i]) if err != nil { return err } } else { //verify the namespace doesn't belong to another //installation, if not, update it to belong to this //installation if namespace.ObjectMeta.Labels[config.LABEL_VENDOR] == config.LABEL_CRUNCHY && namespace.ObjectMeta.Labels[config.LABEL_PGO_INSTALLATION_NAME] != installationName { log.Errorf("%s namespace onwed by another installation, will not convert it to this installation", namespace.Name) } else if namespace.ObjectMeta.Labels[config.LABEL_VENDOR] == config.LABEL_CRUNCHY && namespace.ObjectMeta.Labels[config.LABEL_PGO_INSTALLATION_NAME] == installationName { log.Infof("%s namespace already part of this installation", namespace.Name) } else { log.Infof("%s namespace will be updated to be owned by this installation", namespace.Name) if namespace.ObjectMeta.Labels == nil { namespace.ObjectMeta.Labels = make(map[string]string) } namespace.ObjectMeta.Labels[config.LABEL_VENDOR] = config.LABEL_CRUNCHY namespace.ObjectMeta.Labels[config.LABEL_PGO_INSTALLATION_NAME] = installationName err := kubeapi.UpdateNamespace(clientset, namespace) if err != nil { return err } err = UpdateNamespace(clientset, installationName, pgoNamespace, "operator-bootstrap", namespace.Name) if err != nil { return err } } } } return nil } func GetNamespaces(clientset *kubernetes.Clientset, installationName string) []string { ns := make([]string, 0) nsList, err := kubeapi.GetNamespaces(clientset) if err != nil { log.Error(err.Error()) return ns } for _, v := range nsList.Items { labels := v.ObjectMeta.Labels if labels[config.LABEL_VENDOR] == config.LABEL_CRUNCHY && labels[config.LABEL_PGO_INSTALLATION_NAME] == installationName { ns = append(ns, v.Name) } } return ns } func WatchingNamespace(clientset *kubernetes.Clientset, requestedNS, installationName string) bool { log.Debugf("WatchingNamespace [%s]", requestedNS) nsList := GetNamespaces(clientset, installationName) //handle the case where we are watching all namespaces but //the user might enter an invalid namespace not on the kube if nsList[0] == "" { _, found, _ := kubeapi.GetNamespace(clientset, requestedNS) if !found { return false } else { return true } } for i := 0; i < len(nsList); i++ { if nsList[i] == requestedNS { return true } } return false } func CreatePGOTargetServiceAccount(clientset *kubernetes.Clientset, targetNamespace string) error { //check for serviceaccount existing _, found, _ := kubeapi.GetServiceAccount(clientset, PGO_TARGET_SERVICE_ACCOUNT, targetNamespace) if found { log.Infof("serviceaccount %s already exists, will delete and re-create", PGO_TARGET_SERVICE_ACCOUNT) err := kubeapi.DeleteServiceAccount(clientset, PGO_TARGET_SERVICE_ACCOUNT, targetNamespace) if err != nil { log.Errorf("error deleting serviceaccount %s %s", PGO_TARGET_SERVICE_ACCOUNT, err.Error()) return err } } var buffer bytes.Buffer err := config.PgoTargetServiceAccountTemplate.Execute(&buffer, PgoTargetServiceAccount{ TargetNamespace: targetNamespace, }) if err != nil { log.Error(err.Error() + " on " + config.PGOTargetServiceAccountPath) return err } log.Info(buffer.String()) rb := v1.ServiceAccount{} err = json.Unmarshal(buffer.Bytes(), &rb) if err != nil { log.Error("error unmarshalling " + config.PGOTargetServiceAccountPath + " json ServiceAccount " + err.Error()) return err } err = kubeapi.CreateServiceAccount(clientset, &rb, targetNamespace) if err != nil { return err } return err }
[ "\"NAMESPACE\"" ]
[]
[ "NAMESPACE" ]
[]
["NAMESPACE"]
go
1
0
cmd/influxd/upgrade/upgrade.go
package upgrade import ( "context" "errors" "fmt" "io/ioutil" "net/url" "os" "os/user" "path/filepath" "strings" "github.com/influxdata/influx-cli/v2/clients" "github.com/influxdata/influx-cli/v2/pkg/stdio" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorization" "github.com/influxdata/influxdb/v2/bolt" "github.com/influxdata/influxdb/v2/dbrp" "github.com/influxdata/influxdb/v2/internal/fs" "github.com/influxdata/influxdb/v2/kit/cli" "github.com/influxdata/influxdb/v2/kit/metric" "github.com/influxdata/influxdb/v2/kit/platform" "github.com/influxdata/influxdb/v2/kit/prom" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/kv/migration" "github.com/influxdata/influxdb/v2/kv/migration/all" "github.com/influxdata/influxdb/v2/storage" "github.com/influxdata/influxdb/v2/tenant" authv1 "github.com/influxdata/influxdb/v2/v1/authorization" "github.com/influxdata/influxdb/v2/v1/services/meta" "github.com/influxdata/influxdb/v2/v1/services/meta/filestore" "github.com/spf13/cobra" "github.com/spf13/viper" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) // Simplified 1.x config. type configV1 struct { Meta struct { Dir string `toml:"dir"` } `toml:"meta"` Data struct { Dir string `toml:"dir"` WALDir string `toml:"wal-dir"` } `toml:"data"` Http struct { BindAddress string `toml:"bind-address"` HttpsEnabled bool `toml:"https-enabled"` AuthEnabled bool `toml:"auth-enabled"` } `toml:"http"` } func (c *configV1) dbURL() string { address := c.Http.BindAddress if address == "" { // fallback to default address = ":8086" } var url url.URL if c.Http.HttpsEnabled { url.Scheme = "https" } else { url.Scheme = "http" } if strings.HasPrefix(address, ":") { // address is just :port url.Host = "localhost" + address } else { url.Host = address } return url.String() } type optionsV1 struct { metaDir string walDir string dataDir string dbURL string // cmd option dbDir string configFile string } // populateDirs sets values for expected sub-directories of o.dbDir func (o *optionsV1) populateDirs() { o.metaDir = filepath.Join(o.dbDir, "meta") o.dataDir = filepath.Join(o.dbDir, "data") o.walDir = filepath.Join(o.dbDir, "wal") } type optionsV2 struct { boltPath string cliConfigsPath string enginePath string cqPath string configPath string rmConflicts bool userName string password string orgName string bucket string orgID platform.ID userID platform.ID token string retention string } type options struct { // flags for source InfluxDB source optionsV1 // flags for target InfluxDB target optionsV2 force bool } type logOptions struct { logLevel zapcore.Level logPath string } func NewCommand(ctx context.Context, v *viper.Viper) (*cobra.Command, error) { // target flags v2dir, err := fs.InfluxDir() if err != nil { return nil, fmt.Errorf("error fetching default InfluxDB 2.0 dir: %w", err) } // DEPRECATED in favor of log-level=debug, but left for backwards-compatibility verbose := false logOptions := &logOptions{} options := &options{} cmd := &cobra.Command{ Use: "upgrade", Short: "Upgrade a 1.x version of InfluxDB", Long: ` Upgrades a 1.x version of InfluxDB by performing the following actions: 1. Reads the 1.x config file and creates a 2.x config file with matching options. Unsupported 1.x options are reported. 2. Copies 1.x database files. 3. Creates influx CLI configurations. 4. Exports any 1.x continuous queries to disk. If --config-file is not passed, 1.x db folder (--v1-dir options) is taken as an input. If neither option is given, the CLI will search for config under ${HOME}/.influxdb/ and /etc/influxdb/. If config can't be found, the CLI assumes a standard V1 directory structure under ${HOME}/.influxdb/. Target 2.x database dir is specified by the --engine-path option. If changed, the bolt path should be changed as well. `, RunE: func(cmd *cobra.Command, _ []string) error { logger, err := buildLogger(logOptions, verbose) if err != nil { return err } return runUpgradeE(ctx, clients.CLI{StdIO: stdio.TerminalStdio}, options, logger) }, Args: cobra.NoArgs, } opts := []cli.Opt{ { DestP: &options.source.dbDir, Flag: "v1-dir", Desc: "path to source 1.x db directory containing meta, data and wal sub-folders", }, { DestP: &verbose, Flag: "verbose", Default: false, Desc: "DEPRECATED: use --log-level=debug instead", Short: 'v', Hidden: true, }, { DestP: &options.target.boltPath, Flag: "bolt-path", Default: filepath.Join(v2dir, bolt.DefaultFilename), Desc: "path for boltdb database", Short: 'm', }, { DestP: &options.target.cliConfigsPath, Flag: "influx-configs-path", Default: filepath.Join(v2dir, "configs"), Desc: "path for 2.x CLI configurations file", Short: 'c', }, { DestP: &options.target.enginePath, Flag: "engine-path", Default: filepath.Join(v2dir, "engine"), Desc: "path for persistent engine files", Short: 'e', }, { DestP: &options.target.cqPath, Flag: "continuous-query-export-path", Default: filepath.Join(homeOrAnyDir(), "continuous_queries.txt"), Desc: "path for exported 1.x continuous queries", }, { DestP: &options.target.userName, Flag: "username", Default: "", Desc: "primary username", Short: 'u', }, { DestP: &options.target.password, Flag: "password", Default: "", Desc: "password for username", Short: 'p', }, { DestP: &options.target.orgName, Flag: "org", Default: "", Desc: "primary organization name", Short: 'o', }, { DestP: &options.target.bucket, Flag: "bucket", Default: "", Desc: "primary bucket name", Short: 'b', }, { DestP: &options.target.retention, Flag: "retention", Default: "", Desc: "optional: duration bucket will retain data (i.e '1w' or '72h'). Default is infinite.", Short: 'r', }, { DestP: &options.target.token, Flag: "token", Default: "", Desc: "optional: token for username, else auto-generated", Short: 't', }, { DestP: &options.source.configFile, Flag: "config-file", Desc: "optional: Custom InfluxDB 1.x config file path, else the default config file", }, { DestP: &options.target.configPath, Flag: "v2-config-path", Default: filepath.Join(v2dir, "config.toml"), Desc: "optional: Custom path where upgraded 2.x config should be written", }, { DestP: &logOptions.logLevel, Flag: "log-level", Default: zapcore.InfoLevel, Desc: "supported log levels are debug, info, warn and error", }, { DestP: &logOptions.logPath, Flag: "log-path", Default: filepath.Join(homeOrAnyDir(), "upgrade.log"), Desc: "optional: custom log file path", }, { DestP: &options.force, Flag: "force", Default: false, Desc: "skip the confirmation prompt", Short: 'f', }, { DestP: &options.target.rmConflicts, Flag: "overwrite-existing-v2", Default: false, Desc: "if files are present at an output path, overwrite them instead of aborting the upgrade process", }, } if err := cli.BindOptions(v, cmd, opts); err != nil { return nil, err } // add sub commands cmd.AddCommand(v1DumpMetaCommand) cmd.AddCommand(v2DumpMetaCommand) return cmd, nil } type influxDBv1 struct { meta *meta.Client } type influxDBv2 struct { log *zap.Logger boltClient *bolt.Client store *bolt.KVStore kvStore kv.SchemaStore tenantStore *tenant.Store ts *tenant.Service dbrpSvc influxdb.DBRPMappingServiceV2 bucketSvc influxdb.BucketService onboardSvc influxdb.OnboardingService authSvc *authv1.Service authSvcV2 influxdb.AuthorizationService meta *meta.Client } func (i *influxDBv2) close() error { err := i.meta.Close() if err != nil { return err } err = i.boltClient.Close() if err != nil { return err } err = i.store.Close() if err != nil { return err } return nil } func buildLogger(options *logOptions, verbose bool) (*zap.Logger, error) { config := zap.NewProductionConfig() config.Level = zap.NewAtomicLevelAt(options.logLevel) if verbose { config.Level.SetLevel(zap.DebugLevel) } logPath, err := options.zapSafeLogPath() if err != nil { return nil, err } config.OutputPaths = append(config.OutputPaths, logPath) config.ErrorOutputPaths = append(config.ErrorOutputPaths, logPath) log, err := config.Build() if err != nil { return nil, err } if verbose { log.Warn("--verbose is deprecated, use --log-level=debug instead") } return log, nil } func runUpgradeE(ctx context.Context, cli clients.CLI, options *options, log *zap.Logger) error { if options.source.configFile != "" && options.source.dbDir != "" { return errors.New("only one of --v1-dir or --config-file may be specified") } if options.source.configFile == "" && options.source.dbDir == "" { // Try finding config at usual paths options.source.configFile = influxConfigPathV1() // If not found, try loading a V1 dir under HOME. if options.source.configFile == "" { v1dir, err := influxDirV1() if err != nil { return fmt.Errorf("error fetching default InfluxDB 1.x dir: %w", err) } options.source.dbDir = v1dir } } v1Config := &configV1{} var genericV1ops *map[string]interface{} var err error if options.source.configFile != "" { // If config is present, use it to set data paths. v1Config, genericV1ops, err = loadV1Config(options.source.configFile) if err != nil { return err } options.source.metaDir = v1Config.Meta.Dir options.source.dataDir = v1Config.Data.Dir options.source.walDir = v1Config.Data.WALDir } else { // Otherwise, assume a standard directory layout // and the default port on localhost. options.source.populateDirs() } options.source.dbURL = v1Config.dbURL() if err := options.source.validatePaths(); err != nil { return err } checkV2paths := options.target.validatePaths if options.target.rmConflicts { checkV2paths = options.target.clearPaths } if err := checkV2paths(); err != nil { return err } log.Info("Starting InfluxDB 1.x upgrade") if genericV1ops != nil { log.Info("Upgrading config file", zap.String("file", options.source.configFile)) if err := upgradeConfig(*genericV1ops, options.target, log); err != nil { return err } log.Info( "Config file upgraded.", zap.String("1.x config", options.source.configFile), zap.String("2.x config", options.target.configPath), ) } else { log.Info("No InfluxDB 1.x config file specified, skipping its upgrade") } log.Info("Upgrade source paths", zap.String("meta", options.source.metaDir), zap.String("data", options.source.dataDir)) log.Info("Upgrade target paths", zap.String("bolt", options.target.boltPath), zap.String("engine", options.target.enginePath)) v1, err := newInfluxDBv1(&options.source) if err != nil { return err } v2, err := newInfluxDBv2(ctx, &options.target, log) if err != nil { return err } defer func() { if err := v2.close(); err != nil { log.Error("Failed to close 2.0 services", zap.Error(err)) } }() canOnboard, err := v2.onboardSvc.IsOnboarding(ctx) if err != nil { return err } if !canOnboard { return errors.New("InfluxDB has been already set up") } req, err := onboardingRequest(cli, options) if err != nil { return err } or, err := setupAdmin(ctx, v2, req) if err != nil { return err } options.target.orgID = or.Org.ID options.target.userID = or.User.ID options.target.token = or.Auth.Token err = saveLocalConfig(&options.source, &options.target, log) if err != nil { return err } db2BucketIds, err := upgradeDatabases(ctx, cli, v1, v2, options, or.Org.ID, log) if err != nil { // remove all files log.Error("Database upgrade error, removing data", zap.Error(err)) if e := os.Remove(options.target.boltPath); e != nil { log.Error("Unable to remove bolt database", zap.Error(e)) } if e := os.RemoveAll(options.target.enginePath); e != nil { log.Error("Unable to remove time series data", zap.Error(e)) } return err } usersUpgraded, err := upgradeUsers(ctx, v1, v2, &options.target, db2BucketIds, log) if err != nil { return err } if usersUpgraded > 0 && !v1Config.Http.AuthEnabled { log.Warn( "1.x users were upgraded, but 1.x auth was not enabled. Existing clients will fail authentication against 2.x if using invalid credentials", ) } log.Info( "Upgrade successfully completed. Start the influxd service now, then log in", zap.String("login_url", options.source.dbURL), ) return nil } // validatePaths ensures that all paths pointing to V1 inputs are usable by the upgrade command. func (o *optionsV1) validatePaths() error { if o.dbDir != "" { fi, err := os.Stat(o.dbDir) if err != nil { return fmt.Errorf("1.x DB dir '%s' does not exist", o.dbDir) } if !fi.IsDir() { return fmt.Errorf("1.x DB dir '%s' is not a directory", o.dbDir) } } metaDb := filepath.Join(o.metaDir, "meta.db") _, err := os.Stat(metaDb) if err != nil { return fmt.Errorf("1.x meta.db '%s' does not exist", metaDb) } return nil } // validatePaths ensures that none of the paths pointing to V2 outputs refer to existing files. func (o *optionsV2) validatePaths() error { if o.configPath != "" { if _, err := os.Stat(o.configPath); err == nil { return fmt.Errorf("file present at target path for upgraded 2.x config file %q", o.configPath) } else if !os.IsNotExist(err) { return fmt.Errorf("error checking for existing file at %q: %w", o.configPath, err) } } if _, err := os.Stat(o.boltPath); err == nil { return fmt.Errorf("file present at target path for upgraded 2.x bolt DB: %q", o.boltPath) } else if !os.IsNotExist(err) { return fmt.Errorf("error checking for existing file at %q: %w", o.boltPath, err) } if fi, err := os.Stat(o.enginePath); err == nil { if !fi.IsDir() { return fmt.Errorf("upgraded 2.x engine path %q is not a directory", o.enginePath) } entries, err := ioutil.ReadDir(o.enginePath) if err != nil { return fmt.Errorf("error checking contents of existing engine directory %q: %w", o.enginePath, err) } if len(entries) > 0 { return fmt.Errorf("upgraded 2.x engine directory %q must be empty", o.enginePath) } } else if !os.IsNotExist(err) { return fmt.Errorf("error checking for existing file at %q: %w", o.enginePath, err) } if _, err := os.Stat(o.cliConfigsPath); err == nil { return fmt.Errorf("file present at target path for 2.x CLI configs %q", o.cliConfigsPath) } else if !os.IsNotExist(err) { return fmt.Errorf("error checking for existing file at %q: %w", o.cliConfigsPath, err) } if _, err := os.Stat(o.cqPath); err == nil { return fmt.Errorf("file present at target path for exported continuous queries %q", o.cqPath) } else if !os.IsNotExist(err) { return fmt.Errorf("error checking for existing file at %q: %w", o.cqPath, err) } return nil } // clearPaths deletes any files already present at the specified V2 output paths. func (o *optionsV2) clearPaths() error { if o.configPath != "" { if err := os.RemoveAll(o.configPath); err != nil { return fmt.Errorf("couldn't delete existing file at %q: %w", o.configPath, err) } } if err := os.RemoveAll(o.boltPath); err != nil { return fmt.Errorf("couldn't delete existing file at %q: %w", o.boltPath, err) } if err := os.RemoveAll(o.enginePath); err != nil { return fmt.Errorf("couldn't delete existing file at %q: %w", o.enginePath, err) } if err := os.RemoveAll(o.cliConfigsPath); err != nil { return fmt.Errorf("couldn't delete existing file at %q: %w", o.cliConfigsPath, err) } if err := os.RemoveAll(o.cqPath); err != nil { return fmt.Errorf("couldn't delete existing file at %q: %w", o.cqPath, err) } return nil } func newInfluxDBv1(opts *optionsV1) (svc *influxDBv1, err error) { svc = &influxDBv1{} svc.meta, err = openV1Meta(opts.metaDir) if err != nil { return nil, fmt.Errorf("error opening 1.x meta.db: %w", err) } return svc, nil } func newInfluxDBv2(ctx context.Context, opts *optionsV2, log *zap.Logger) (svc *influxDBv2, err error) { reg := prom.NewRegistry(log.With(zap.String("service", "prom_registry"))) svc = &influxDBv2{} svc.log = log // Create BoltDB store and K/V service svc.boltClient = bolt.NewClient(log.With(zap.String("service", "bolt"))) svc.boltClient.Path = opts.boltPath if err := svc.boltClient.Open(ctx); err != nil { log.Error("Failed opening bolt", zap.Error(err)) return nil, err } svc.store = bolt.NewKVStore(log.With(zap.String("service", "kvstore-bolt")), opts.boltPath) svc.store.WithDB(svc.boltClient.DB()) svc.kvStore = svc.store // ensure migrator is run migrator, err := migration.NewMigrator( log.With(zap.String("service", "migrations")), svc.kvStore, all.Migrations[:]..., ) if err != nil { log.Error("Failed to initialize kv migrator", zap.Error(err)) return nil, err } // apply migrations to metadata store if err := migrator.Up(ctx); err != nil { log.Error("Failed to apply migrations", zap.Error(err)) return nil, err } // Create Tenant service (orgs, buckets, ) svc.tenantStore = tenant.NewStore(svc.kvStore) svc.ts = tenant.NewSystem(svc.tenantStore, log.With(zap.String("store", "new")), reg, metric.WithSuffix("new")) svc.meta = meta.NewClient(meta.NewConfig(), svc.kvStore) if err := svc.meta.Open(); err != nil { return nil, err } // DB/RP service svc.dbrpSvc = dbrp.NewService(ctx, svc.ts.BucketService, svc.kvStore) svc.bucketSvc = svc.ts.BucketService engine := storage.NewEngine( opts.enginePath, storage.NewConfig(), storage.WithMetaClient(svc.meta), ) svc.ts.BucketService = storage.NewBucketService(log, svc.ts.BucketService, engine) authStoreV2, err := authorization.NewStore(svc.store) if err != nil { return nil, err } svc.authSvcV2 = authorization.NewService(authStoreV2, svc.ts) // on-boarding service (influx setup) svc.onboardSvc = tenant.NewOnboardService(svc.ts, svc.authSvcV2) // v1 auth service authStoreV1, err := authv1.NewStore(svc.kvStore) if err != nil { return nil, err } svc.authSvc = authv1.NewService(authStoreV1, svc.ts) return svc, nil } func openV1Meta(dir string) (*meta.Client, error) { cfg := meta.NewConfig() cfg.Dir = dir store := filestore.New(cfg.Dir, string(meta.BucketName), "meta.db") c := meta.NewClient(cfg, store) if err := c.Open(); err != nil { return nil, err } return c, nil } // influxDirV1 retrieves the influxdb directory. func influxDirV1() (string, error) { var dir string // By default, store meta and data files in current users home directory u, err := user.Current() if err == nil { dir = u.HomeDir } else if home := os.Getenv("HOME"); home != "" { dir = home } else { wd, err := os.Getwd() if err != nil { return "", err } dir = wd } dir = filepath.Join(dir, ".influxdb") return dir, nil } // influxConfigPathV1 returns default 1.x config file path or empty path if not found. func influxConfigPathV1() string { if envVar := os.Getenv("INFLUXDB_CONFIG_PATH"); envVar != "" { return envVar } for _, path := range []string{ os.ExpandEnv("${HOME}/.influxdb/influxdb.conf"), "/etc/influxdb/influxdb.conf", } { if _, err := os.Stat(path); err == nil { return path } } return "" } // homeOrAnyDir retrieves user's home directory, current working one or just none. func homeOrAnyDir() string { var dir string u, err := user.Current() if err == nil { dir = u.HomeDir } else if home := os.Getenv("HOME"); home != "" { dir = home } else if home := os.Getenv("USERPROFILE"); home != "" { dir = home } else { wd, err := os.Getwd() if err != nil { dir = "" } else { dir = wd } } return dir }
[ "\"HOME\"", "\"INFLUXDB_CONFIG_PATH\"", "\"HOME\"", "\"USERPROFILE\"" ]
[]
[ "INFLUXDB_CONFIG_PATH", "HOME", "USERPROFILE" ]
[]
["INFLUXDB_CONFIG_PATH", "HOME", "USERPROFILE"]
go
3
0
flaskblog/config.py
import os from dotenv import load_dotenv load_dotenv() class Config: SECRET_KEY = os.getenv('SECRET_KEY') SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI') MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USERNAME = os.getenv('MAIL_USERNAME') MAIL_PASSWORD = os.getenv('MAIL_PASSWORD') MAIL_DEFAULT_SENDER = os.getenv('MAIL_DEFAULT_SENDER')
[]
[]
[ "MAIL_PASSWORD", "MAIL_DEFAULT_SENDER", "SECRET_KEY", "MAIL_USERNAME", "SQLALCHEMY_DATABASE_URI" ]
[]
["MAIL_PASSWORD", "MAIL_DEFAULT_SENDER", "SECRET_KEY", "MAIL_USERNAME", "SQLALCHEMY_DATABASE_URI"]
python
5
0
go/vt/servenv/servenv.go
// Copyright 2012, Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package servenv contains functionality that is common for all // Vitess server programs. It defines and initializes command line // flags that control the runtime environment. // // After a server program has called flag.Parse, it needs to call // env.Init to make env use the command line variables to initialize // the environment. It also needs to call env.Close before exiting. // // Note: If you need to plug in any custom initialization/cleanup for // a vitess distribution, register them using onInit and onClose. A // clean way of achieving that is adding to this package a file with // an init() function that registers the hooks. package servenv import ( "crypto/md5" "encoding/hex" "flag" "fmt" "io" "net/url" "os" "runtime" "sync" "syscall" "time" _ "net/http/pprof" log "github.com/golang/glog" "github.com/youtube/vitess/go/event" "github.com/youtube/vitess/go/netutil" "github.com/youtube/vitess/go/stats" _ "github.com/youtube/vitess/go/vt/logutil" ) var ( // The flags used when calling RegisterDefaultFlags. Port *int // Flags to alter the behavior of the library. lameduckPeriod = flag.Duration("lameduck-period", 50*time.Millisecond, "keep running at least this long after SIGTERM before stopping") onTermTimeout = flag.Duration("onterm_timeout", 10*time.Second, "wait no more than this for OnTermSync handlers before stopping") memProfileRate = flag.Int("mem-profile-rate", 512*1024, "profile every n bytes allocated") // mutex used to protect the Init function mu sync.Mutex onInitHooks event.Hooks onTermHooks event.Hooks onTermSyncHooks event.Hooks onRunHooks event.Hooks inited bool // filled in when calling Run ListeningURL url.URL ) func Init() { mu.Lock() defer mu.Unlock() if inited { log.Fatal("servenv.Init called second time") } inited = true // Once you run as root, you pretty much destroy the chances of a // non-privileged user starting the program correctly. if uid := os.Getuid(); uid == 0 { log.Fatalf("servenv.Init: running this as root makes no sense") } runtime.MemProfileRate = *memProfileRate gomaxprocs := os.Getenv("GOMAXPROCS") if gomaxprocs == "" { gomaxprocs = "1" } // We used to set this limit directly, but you pretty much have to // use a root account to allow increasing a limit reliably. Dropping // privileges is also tricky. The best strategy is to make a shell // script set up the limits as root and switch users before starting // the server. fdLimit := &syscall.Rlimit{} if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, fdLimit); err != nil { log.Errorf("max-open-fds failed: %v", err) } fdl := stats.NewInt("MaxFds") fdl.Set(int64(fdLimit.Cur)) if err := exportBinaryVersion(); err != nil { log.Fatalf("servenv.Init: exportBinaryVersion: %v", err) } onInitHooks.Fire() } func exportBinaryVersion() error { hasher := md5.New() exeFile, err := os.Open("/proc/self/exe") if err != nil { return err } if _, err = io.Copy(hasher, exeFile); err != nil { return err } md5sum := hex.EncodeToString(hasher.Sum(nil)) fileInfo, err := exeFile.Stat() if err != nil { return err } mtime := fileInfo.ModTime().Format(time.RFC3339) version := mtime + " " + md5sum stats.NewString("BinaryVersion").Set(version) return nil } func populateListeningURL() { host, err := netutil.FullyQualifiedHostname() if err != nil { host, err = os.Hostname() if err != nil { log.Fatalf("os.Hostname() failed: %v", err) } } ListeningURL = url.URL{ Scheme: "http", Host: fmt.Sprintf("%v:%v", host, *Port), Path: "/", } } // onInit registers f to be run at the beginning of the app // lifecycle. It should be called in an init() function. func onInit(f func()) { onInitHooks.Add(f) } // OnTerm registers a function to be run when the process receives a SIGTERM. // This allows the program to change its behavior during the lameduck period. // // All hooks are run in parallel, and there is no guarantee that the process // will wait for them to finish before dying when the lameduck period expires. // // See also: OnTermSync func OnTerm(f func()) { onTermHooks.Add(f) } // OnTermSync registers a function to be run when the process receives SIGTERM. // This allows the program to change its behavior during the lameduck period. // // All hooks are run in parallel, and the process will do its best to wait // (up to -onterm_timeout) for all of them to finish before dying. // // See also: OnTerm func OnTermSync(f func()) { onTermSyncHooks.Add(f) } // fireOnTermSyncHooks returns true iff all the hooks finish before the timeout. func fireOnTermSyncHooks(timeout time.Duration) bool { log.Infof("Firing synchronous OnTermSync hooks and waiting up to %v for them", timeout) timer := time.NewTimer(timeout) defer timer.Stop() done := make(chan struct{}) go func() { onTermSyncHooks.Fire() close(done) }() select { case <-done: log.Infof("OnTermSync hooks finished") return true case <-timer.C: log.Infof("OnTermSync hooks timed out") return false } } // OnRun registers f to be run right at the beginning of Run. All // hooks are run in parallel. func OnRun(f func()) { onRunHooks.Add(f) } // RegisterDefaultFlags registers the default flags for // listening to a given port for standard connections. // If calling this, then call RunDefault() func RegisterDefaultFlags() { Port = flag.Int("port", 0, "port for the server") } // RunDefault calls Run() with the parameters from the flags. func RunDefault() { Run(*Port) }
[ "\"GOMAXPROCS\"" ]
[]
[ "GOMAXPROCS" ]
[]
["GOMAXPROCS"]
go
1
0
BaseTools/Source/Python/Workspace/MetaFileTable.py
## @file # This file is used to create/update/query/erase a meta file table # # Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR> # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## # Import Modules # from __future__ import absolute_import import uuid import Common.EdkLogger as EdkLogger from Common.BuildToolError import FORMAT_INVALID from CommonDataClass.DataClass import MODEL_FILE_DSC, MODEL_FILE_DEC, MODEL_FILE_INF, \ MODEL_FILE_OTHERS from Common.DataType import * class MetaFileTable(): # TRICK: use file ID as the part before '.' _ID_STEP_ = 0.00000001 _ID_MAX_ = 0.99999999 ## Constructor def __init__(self, DB, MetaFile, FileType, Temporary, FromItem=None): self.MetaFile = MetaFile self.TableName = "" self.DB = DB self._NumpyTab = None self.FileId = len(DB.TblFile) self.ID = self.FileId self.CurrentContent = [] DB.TblFile.append([MetaFile.Name, MetaFile.Ext, MetaFile.Dir, MetaFile.Path, FileType, MetaFile.TimeStamp, FromItem]) if Temporary: self.TableName = "_%s_%s_%s" % (FileType, len(DB.TblFile), uuid.uuid4().hex) else: self.TableName = "_%s_%s" % (FileType, len(DB.TblFile)) def IsIntegrity(self): try: TimeStamp = self.MetaFile.TimeStamp Result = int(self.CurrentContent[-1][0]) < 0 if not Result: # update the timestamp in database self.DB.SetFileTimeStamp(self.FileId, TimeStamp) return False if TimeStamp != self.DB.GetFileTimeStamp(self.FileId): # update the timestamp in database self.DB.SetFileTimeStamp(self.FileId, TimeStamp) return False except Exception as Exc: EdkLogger.debug(EdkLogger.DEBUG_5, str(Exc)) return False return True def SetEndFlag(self): self.CurrentContent.append(self._DUMMY_) def GetAll(self): return [item for item in self.CurrentContent if item[0] > 0 ] ## Python class representation of table storing module data class ModuleTable(MetaFileTable): _ID_STEP_ = 0.00000001 _ID_MAX_ = 0.99999999 _COLUMN_ = ''' ID REAL PRIMARY KEY, Model INTEGER NOT NULL, Value1 TEXT NOT NULL, Value2 TEXT, Value3 TEXT, Scope1 TEXT, Scope2 TEXT, BelongsToItem REAL NOT NULL, StartLine INTEGER NOT NULL, StartColumn INTEGER NOT NULL, EndLine INTEGER NOT NULL, EndColumn INTEGER NOT NULL, Enabled INTEGER DEFAULT 0 ''' # used as table end flag, in case the changes to database is not committed to db file _DUMMY_ = [-1, -1, '====', '====', '====', '====', '====', -1, -1, -1, -1, -1, -1] ## Constructor def __init__(self, Db, MetaFile, Temporary): MetaFileTable.__init__(self, Db, MetaFile, MODEL_FILE_INF, Temporary) ## Insert a record into table Inf # # @param Model: Model of a Inf item # @param Value1: Value1 of a Inf item # @param Value2: Value2 of a Inf item # @param Value3: Value3 of a Inf item # @param Scope1: Arch of a Inf item # @param Scope2 Platform os a Inf item # @param BelongsToItem: The item belongs to which another item # @param StartLine: StartLine of a Inf item # @param StartColumn: StartColumn of a Inf item # @param EndLine: EndLine of a Inf item # @param EndColumn: EndColumn of a Inf item # @param Enabled: If this item enabled # def Insert(self, Model, Value1, Value2, Value3, Scope1=TAB_ARCH_COMMON, Scope2=TAB_COMMON, BelongsToItem=-1, StartLine=-1, StartColumn=-1, EndLine=-1, EndColumn=-1, Enabled=0): (Value1, Value2, Value3, Scope1, Scope2) = (Value1.strip(), Value2.strip(), Value3.strip(), Scope1.strip(), Scope2.strip()) self.ID = self.ID + self._ID_STEP_ if self.ID >= (MODEL_FILE_INF + self._ID_MAX_): self.ID = MODEL_FILE_INF + self._ID_STEP_ row = [ self.ID, Model, Value1, Value2, Value3, Scope1, Scope2, BelongsToItem, StartLine, StartColumn, EndLine, EndColumn, Enabled ] self.CurrentContent.append(row) return self.ID ## Query table # # @param Model: The Model of Record # @param Arch: The Arch attribute of Record # @param Platform The Platform attribute of Record # # @retval: A recordSet of all found records # def Query(self, Model, Arch=None, Platform=None, BelongsToItem=None): QueryTab = self.CurrentContent result = [item for item in QueryTab if item[1] == Model and item[-1]>=0 ] if Arch is not None and Arch != TAB_ARCH_COMMON: ArchList = set(['COMMON']) ArchList.add(Arch) result = [item for item in result if item[5] in ArchList] if Platform is not None and Platform != TAB_COMMON: Platformlist = set( ['COMMON','DEFAULT']) Platformlist.add(Platform) result = [item for item in result if item[6] in Platformlist] if BelongsToItem is not None: result = [item for item in result if item[7] == BelongsToItem] result = [ [r[2],r[3],r[4],r[5],r[6],r[0],r[9]] for r in result ] return result ## Python class representation of table storing package data class PackageTable(MetaFileTable): _COLUMN_ = ''' ID REAL PRIMARY KEY, Model INTEGER NOT NULL, Value1 TEXT NOT NULL, Value2 TEXT, Value3 TEXT, Scope1 TEXT, Scope2 TEXT, BelongsToItem REAL NOT NULL, StartLine INTEGER NOT NULL, StartColumn INTEGER NOT NULL, EndLine INTEGER NOT NULL, EndColumn INTEGER NOT NULL, Enabled INTEGER DEFAULT 0 ''' # used as table end flag, in case the changes to database is not committed to db file _DUMMY_ = [-1, -1, '====', '====', '====', '====', '====', -1, -1, -1, -1, -1, -1] ## Constructor def __init__(self, Cursor, MetaFile, Temporary): MetaFileTable.__init__(self, Cursor, MetaFile, MODEL_FILE_DEC, Temporary) ## Insert table # # Insert a record into table Dec # # @param Model: Model of a Dec item # @param Value1: Value1 of a Dec item # @param Value2: Value2 of a Dec item # @param Value3: Value3 of a Dec item # @param Scope1: Arch of a Dec item # @param Scope2: Module type of a Dec item # @param BelongsToItem: The item belongs to which another item # @param StartLine: StartLine of a Dec item # @param StartColumn: StartColumn of a Dec item # @param EndLine: EndLine of a Dec item # @param EndColumn: EndColumn of a Dec item # @param Enabled: If this item enabled # def Insert(self, Model, Value1, Value2, Value3, Scope1=TAB_ARCH_COMMON, Scope2=TAB_COMMON, BelongsToItem=-1, StartLine=-1, StartColumn=-1, EndLine=-1, EndColumn=-1, Enabled=0): (Value1, Value2, Value3, Scope1, Scope2) = (Value1.strip(), Value2.strip(), Value3.strip(), Scope1.strip(), Scope2.strip()) self.ID = self.ID + self._ID_STEP_ if self.ID >= (MODEL_FILE_INF + self._ID_MAX_): self.ID = MODEL_FILE_INF + self._ID_STEP_ row = [ self.ID, Model, Value1, Value2, Value3, Scope1, Scope2, BelongsToItem, StartLine, StartColumn, EndLine, EndColumn, Enabled ] self.CurrentContent.append(row) return self.ID ## Query table # # @param Model: The Model of Record # @param Arch: The Arch attribute of Record # # @retval: A recordSet of all found records # def Query(self, Model, Arch=None): QueryTab = self.CurrentContent result = [item for item in QueryTab if item[1] == Model and item[-1]>=0 ] if Arch is not None and Arch != TAB_ARCH_COMMON: ArchList = set(['COMMON']) ArchList.add(Arch) result = [item for item in result if item[5] in ArchList] return [[r[2], r[3], r[4], r[5], r[6], r[0], r[8]] for r in result] def GetValidExpression(self, TokenSpaceGuid, PcdCName): QueryTab = self.CurrentContent result = [[item[2], item[8]] for item in QueryTab if item[3] == TokenSpaceGuid and item[4] == PcdCName] validateranges = [] validlists = [] expressions = [] try: for row in result: comment = row[0] LineNum = row[1] comment = comment.strip("#") comment = comment.strip() oricomment = comment if comment.startswith("@ValidRange"): comment = comment.replace("@ValidRange", "", 1) validateranges.append(comment.split("|")[1].strip()) if comment.startswith("@ValidList"): comment = comment.replace("@ValidList", "", 1) validlists.append(comment.split("|")[1].strip()) if comment.startswith("@Expression"): comment = comment.replace("@Expression", "", 1) expressions.append(comment.split("|")[1].strip()) except Exception as Exc: ValidType = "" if oricomment.startswith("@ValidRange"): ValidType = "@ValidRange" if oricomment.startswith("@ValidList"): ValidType = "@ValidList" if oricomment.startswith("@Expression"): ValidType = "@Expression" EdkLogger.error('Parser', FORMAT_INVALID, "The syntax for %s of PCD %s.%s is incorrect" % (ValidType, TokenSpaceGuid, PcdCName), ExtraData=oricomment, File=self.MetaFile, Line=LineNum) return set(), set(), set() return set(validateranges), set(validlists), set(expressions) ## Python class representation of table storing platform data class PlatformTable(MetaFileTable): _COLUMN_ = ''' ID REAL PRIMARY KEY, Model INTEGER NOT NULL, Value1 TEXT NOT NULL, Value2 TEXT, Value3 TEXT, Scope1 TEXT, Scope2 TEXT, Scope3 TEXT, BelongsToItem REAL NOT NULL, FromItem REAL NOT NULL, StartLine INTEGER NOT NULL, StartColumn INTEGER NOT NULL, EndLine INTEGER NOT NULL, EndColumn INTEGER NOT NULL, Enabled INTEGER DEFAULT 0 ''' # used as table end flag, in case the changes to database is not committed to db file _DUMMY_ = [-1, -1, '====', '====', '====', '====', '====','====', -1, -1, -1, -1, -1, -1, -1] ## Constructor def __init__(self, Cursor, MetaFile, Temporary, FromItem=0): MetaFileTable.__init__(self, Cursor, MetaFile, MODEL_FILE_DSC, Temporary, FromItem) ## Insert table # # Insert a record into table Dsc # # @param Model: Model of a Dsc item # @param Value1: Value1 of a Dsc item # @param Value2: Value2 of a Dsc item # @param Value3: Value3 of a Dsc item # @param Scope1: Arch of a Dsc item # @param Scope2: Module type of a Dsc item # @param BelongsToItem: The item belongs to which another item # @param FromItem: The item belongs to which dsc file # @param StartLine: StartLine of a Dsc item # @param StartColumn: StartColumn of a Dsc item # @param EndLine: EndLine of a Dsc item # @param EndColumn: EndColumn of a Dsc item # @param Enabled: If this item enabled # def Insert(self, Model, Value1, Value2, Value3, Scope1=TAB_ARCH_COMMON, Scope2=TAB_COMMON, Scope3=TAB_DEFAULT_STORES_DEFAULT,BelongsToItem=-1, FromItem=-1, StartLine=-1, StartColumn=-1, EndLine=-1, EndColumn=-1, Enabled=1): (Value1, Value2, Value3, Scope1, Scope2, Scope3) = (Value1.strip(), Value2.strip(), Value3.strip(), Scope1.strip(), Scope2.strip(), Scope3.strip()) self.ID = self.ID + self._ID_STEP_ if self.ID >= (MODEL_FILE_INF + self._ID_MAX_): self.ID = MODEL_FILE_INF + self._ID_STEP_ row = [ self.ID, Model, Value1, Value2, Value3, Scope1, Scope2, Scope3, BelongsToItem, FromItem, StartLine, StartColumn, EndLine, EndColumn, Enabled ] self.CurrentContent.append(row) return self.ID ## Query table # # @param Model: The Model of Record # @param Scope1: Arch of a Dsc item # @param Scope2: Module type of a Dsc item # @param BelongsToItem: The item belongs to which another item # @param FromItem: The item belongs to which dsc file # # @retval: A recordSet of all found records # def Query(self, Model, Scope1=None, Scope2=None, BelongsToItem=None, FromItem=None): QueryTab = self.CurrentContent result = [item for item in QueryTab if item[1] == Model and item[-1]>0 ] if Scope1 is not None and Scope1 != TAB_ARCH_COMMON: Sc1 = set(['COMMON']) Sc1.add(Scope1) result = [item for item in result if item[5] in Sc1] Sc2 = set( ['COMMON','DEFAULT']) if Scope2 and Scope2 != TAB_COMMON: if '.' in Scope2: Index = Scope2.index('.') NewScope = TAB_COMMON + Scope2[Index:] Sc2.add(NewScope) Sc2.add(Scope2) result = [item for item in result if item[6] in Sc2] if BelongsToItem is not None: result = [item for item in result if item[8] == BelongsToItem] else: result = [item for item in result if item[8] < 0] if FromItem is not None: result = [item for item in result if item[9] == FromItem] result = [ [r[2],r[3],r[4],r[5],r[6],r[7],r[0],r[9]] for r in result ] return result ## Factory class to produce different storage for different type of meta-file class MetaFileStorage(object): _FILE_TABLE_ = { MODEL_FILE_INF : ModuleTable, MODEL_FILE_DEC : PackageTable, MODEL_FILE_DSC : PlatformTable, MODEL_FILE_OTHERS : MetaFileTable, } _FILE_TYPE_ = { ".inf" : MODEL_FILE_INF, ".dec" : MODEL_FILE_DEC, ".dsc" : MODEL_FILE_DSC, } ## Constructor def __new__(Class, Cursor, MetaFile, FileType=None, Temporary=False, FromItem=None): # no type given, try to find one if not FileType: if MetaFile.Type in self._FILE_TYPE_: FileType = Class._FILE_TYPE_[MetaFile.Type] else: FileType = MODEL_FILE_OTHERS # don't pass the type around if it's well known if FileType == MODEL_FILE_OTHERS: Args = (Cursor, MetaFile, FileType, Temporary) else: Args = (Cursor, MetaFile, Temporary) if FromItem: Args = Args + (FromItem,) # create the storage object and return it to caller return Class._FILE_TABLE_[FileType](*Args)
[]
[]
[]
[]
[]
python
null
null
null
src/firmware/lib/zircon_boot/test/test_data/generate_test_data.py
#!/usr/bin/env python3.8 # Copyright 2020 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """The code is to provide a reference of how test_images.h is generated""" import os import tempfile from typing import List import subprocess FUCHSIA_DIR = os.environ.get('FUCHSIA_DIR') AVB_REPO = os.path.join( f'{FUCHSIA_DIR}', 'third_party', 'android', 'platform', 'external', 'avb') AVB_TOOL = os.path.join(f'{AVB_REPO}', 'avbtool.py') ZBI_TOOL = os.path.join(f'{FUCHSIA_DIR}', 'out', 'default', 'host_x64', 'zbi') PSK = os.path.join(f'{AVB_REPO}', 'test', 'data', 'testkey_atx_psk.pem') ATX_METADATA = os.path.join(f'{AVB_REPO}', 'test', 'data', 'atx_metadata.bin') ATX_PERMANENT_ATTRIBUTES = os.path.join( f'{AVB_REPO}', 'test', 'data', 'atx_permanent_attributes.bin') KERNEL_IMG_SIZE = 1024 def GetCArrayDeclaration(data: bytes, var_name: str) -> str: """Generates a C array declaration for a byte array""" decl = f'const unsigned char {var_name}[] =' + '{ ' decl += " ".join([f'0x{b:x},' for b in data]) decl += "};" return decl def GenerateTestImageCArrayDeclaration( ab_suffix: str, rollback_index: int = 0, rollback_index_location: int = 0) -> List[str]: """Generates kernel/vbmeta image for a slot and their C array declarations """ decls = [] with tempfile.TemporaryDirectory() as temp_dir: kernel = f'{temp_dir}/test_zircon_{ab_suffix}.bin' kernel_zbi = f'{temp_dir}/test_zircon_{ab_suffix}.zbi' # Generate random kernel image with open(kernel, 'wb') as f: f.write(bytes(os.urandom(KERNEL_IMG_SIZE))) # Put image in a zbi container. subprocess.run( [ ZBI_TOOL, '--output', kernel_zbi, '--type=KERNEL_ARM64', kernel, ]) # Generate C array declaration with open(kernel_zbi, 'rb') as zbi: data = zbi.read() decls.append( GetCArrayDeclaration( data, f'kTestZircon{ab_suffix.upper()}Image')) # Generate vbmeta descriptor. vbmeta_desc = f'{temp_dir}/test_vbmeta_{ab_suffix}.desc' subprocess.run( [ AVB_TOOL, 'add_hash_footer', '--image', kernel_zbi, '--partition_name', 'zircon', '--do_not_append_vbmeta_image', '--output_vbmeta_image', vbmeta_desc, '--partition_size', '209715200', ]) # Generate two cmdline ZBI items to add as property descriptors to vbmeta # image for test. vbmeta_prop_zbi_1 = f'{temp_dir}/test_vbmeta_prop_{ab_suffix}_1.img' subprocess.run( [ ZBI_TOOL, '--output', vbmeta_prop_zbi_1, '--type=CMDLINE', f'--entry=vb_arg_1=foo_{ab_suffix}', ]) vbmeta_prop_zbi_2 = f'{temp_dir}/test_vbmeta_prop_{ab_suffix}_2.img' subprocess.run( [ ZBI_TOOL, '--output', vbmeta_prop_zbi_2, '--type=CMDLINE', f'--entry=vb_arg_2=bar_{ab_suffix}', ]) # Generate vbmeta image vbmeta_img = f'{temp_dir}/test_vbmeta_{ab_suffix}.img' subprocess.run( [ AVB_TOOL, 'make_vbmeta_image', '--output', vbmeta_img, '--key', PSK, '--algorithm', 'SHA512_RSA4096', '--public_key_metadata', ATX_METADATA, '--include_descriptors_from_image', vbmeta_desc, '--prop_from_file', f'zbi_vbmeta_arg_1:{vbmeta_prop_zbi_1}', '--prop_from_file', f'zbi_vbmeta_arg_2:{vbmeta_prop_zbi_2}', # The following should not be recognized as vbmeta zbi item, as # the value is not a zbi item. '--prop', f'zbi_vbmeta_arg_3:abc', '--rollback_index', f'{rollback_index}', '--rollback_index_location', f'{rollback_index_location}', ]) # Generate C array declaration with open(vbmeta_img, 'rb') as vbmeta: data = vbmeta.read() decls.append( GetCArrayDeclaration( data, f'kTestVbmeta{ab_suffix.upper()}Image')) return decls def GeneratePermanentAttributesDeclaration(file_name: str) -> str: with open(file_name, 'rb') as perm_attr: data = perm_attr.read() return GetCArrayDeclaration(data, 'kPermanentAttributes') def GenerateVariableDeclarationHeader(decls: List[str], out_file: str): """Writes a header file that contains all C array declarations""" with open(out_file, 'w') as f: f.write( """// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. """) # This will trigger 'fx format-code' to fix inclusion macro. f.write('#pragma once\n\n') for decl in decls: f.write(f'{decl}\n\n') subprocess.run(['fx', 'format-code', f'--files={out_file}']) if __name__ == '__main__': decls = [] # slot images decls.extend(GenerateTestImageCArrayDeclaration('a', rollback_index=5)) decls.extend(GenerateTestImageCArrayDeclaration('b', rollback_index=10)) decls.extend(GenerateTestImageCArrayDeclaration('r')) # permanent attributes decls.append( GeneratePermanentAttributesDeclaration(ATX_PERMANENT_ATTRIBUTES)) GenerateVariableDeclarationHeader(decls, 'test_images.h')
[]
[]
[ "FUCHSIA_DIR" ]
[]
["FUCHSIA_DIR"]
python
1
0
guild/op.py
# Copyright 2017-2020 TensorHub, 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. from __future__ import absolute_import from __future__ import division import logging import os import subprocess import sys import time from guild import config from guild import exit_code from guild import op_dep from guild import op_util from guild import run as runlib from guild import util log = logging.getLogger("guild") OP_RUNFILE_PATHS = [ ["org_click"], ["org_psutil"], ["guild", "external"], ] PROC_TERM_TIMEOUT_SECONDS = 30 ################################################################### # Exception classes ################################################################### class InvalidOpDef(ValueError): def __init__(self, opdef, msg): super(InvalidOpDef, self).__init__(opdef, msg) self.opdef = opdef self.msg = msg def __str__(self): return self.msg class OpInitError(Exception): pass class ProcessError(Exception): pass ################################################################### # State ################################################################### class Operation(object): def __init__(self): self.opref = None self.cmd_args = [] self.cmd_env = {} self.sourcecode_paths = [] self.run_dir = None self.run_attrs = {} self.deps = [] self.callbacks = None class OperationCallbacks(object): def __init__(self, init_output_summary=None, run_initialized=None): self.init_output_summary = init_output_summary self.run_initialized = run_initialized def _callback(name, op, *rest_args): if op.callbacks: cb = getattr(op.callbacks, name, None) if cb: cb(op, *rest_args) ################################################################### # Init run ################################################################### def init_run(op, run_dir=None): run = _op_init_pending_run(op, run_dir) _op_init_run_attrs(op, run) _callback("run_initialized", op, run) return run def _op_init_pending_run(op, run_dir): run_dir = run_dir or op.run_dir run = op_util.init_run(run_dir) log.debug("initializing run in %s", run.dir) run.init_skel() op_util.set_run_pending(run) return run def _op_init_run_attrs(op, run): run.write_opref(op.opref) run.write_attr("cmd", op.cmd_args) for name, val in (op.run_attrs or {}).items(): run.write_attr(name, val) ################################################################### # Stage ################################################################### def stage(op): run = init_run(op) try: _stage_run_proc_env(op, run) _resolve_deps(op, run, for_stage=True) op_util.set_run_staged(run) finally: op_util.clear_run_pending(run) return run def _stage_run_proc_env(op, run): env = _op_proc_env(op, run) skip_env = ("PWD", "_") with open(run.guild_path("ENV"), "w") as out: for name in sorted(env): if name in skip_env: continue out.write("export %s=%s\n" % (name, util.env_var_quote(env[name]))) ################################################################### # Run ################################################################### def run(op, quiet=False, pidfile=None, stop_after=None, extra_env=None): run = init_run(op) if pidfile: _start_in_background(run, op, pidfile, quiet, stop_after, extra_env) return run, 0 else: exit_status = _run(run, op, quiet, stop_after, extra_env) return run, exit_status def _start_in_background(run, op, pidfile, quiet, stop_after, extra_env): import daemonize action = lambda: _run(run, op, quiet, stop_after, extra_env) daemon = daemonize.Daemonize( app="guild_op", action=action, pid=pidfile, chdir=config.cwd() ) # Need to log before starting daemon, otherwise output isn't # visible. if not quiet: log.info( "%s started in background as %s (pidfile %s)", run.opref.to_opspec(config.cwd()), run.id, pidfile, ) try: daemon.start() except SystemExit: op_util.clear_run_pending(run) raise def _run(run, op, quiet, stop_after, extra_env): try: _resolve_deps(op, run) finally: op_util.clear_run_pending(run) op_util.set_run_started(run) op_util.clear_run_marker(run, "STAGED") proc = _op_start_proc(op, run, extra_env) exit_status = _op_wait_for_proc(op, proc, run, quiet, stop_after) _op_finalize_run_attrs(run, exit_status) return exit_status def _op_start_proc(op, run, extra_env=None): env = _op_proc_env(op, run) if extra_env: env.update(extra_env) run.write_attr("env", env) log.debug("starting run %s in %s", run.id, run.dir) log.debug("operation command: %s", op.cmd_args) log.debug("operation env: %s", env) try: proc = subprocess.Popen( op.cmd_args, env=env, cwd=run.dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, ) except OSError as e: raise ProcessError(e) else: _write_proc_lock(proc, run) return proc def _write_proc_lock(proc, run): with open(run.guild_path("LOCK"), "w") as f: f.write(str(proc.pid)) def _op_wait_for_proc(op, proc, run, quiet, stop_after): try: return _op_watch_proc(op, proc, run, quiet, stop_after) except KeyboardInterrupt: return _handle_proc_interrupt(proc) def _op_watch_proc(op, proc, run, quiet, stop_after): output_summary = _output_summary_for_run(run, op) with _RunOutput(run, proc, quiet, output_summary): return _proc_wait(proc, stop_after) def _output_summary_for_run(run, op): if not op.callbacks or not op.callbacks.init_output_summary: return None return op.callbacks.init_output_summary(op, run) class _RunOutput(object): def __init__(self, run, *args): self._output = None self._run = run self._rest_init_args = args def __enter__(self): if os.getenv("NO_RUN_OUTPUT_CAPTURE") != "1": self._output = op_util.RunOutput(self._run, *self._rest_init_args) def __exit__(self, *_exc): if self._output: self._output.wait_and_close() self._output = None def _proc_wait(proc, stop_after): if stop_after is None: return proc.wait() else: return op_util.wait_for_proc(proc, stop_after) def _handle_proc_interrupt(proc): log.info("Operation interrupted - waiting for process to exit") kill_after = time.time() + PROC_TERM_TIMEOUT_SECONDS while time.time() < kill_after: if proc.poll() is not None: break time.sleep(1) if proc.poll() is None: log.warning("Operation process did not exit - stopping forcefully") util.kill_process_tree(proc.pid, force=True) return exit_code.SIGTERM def _op_exit_status(proc_exit_status, opdef): if proc_exit_status == exit_code.SIGTERM and opdef.stoppable: return 0 return proc_exit_status def _op_finalize_run_attrs(run, exit_status): if not os.path.exists(run.dir): log.warning("run directory has been deleted, unable to finalize") return if not os.path.exists(run.guild_path()): log.warning("run Guild directory has been deleted, unable to finalize") return stopped = runlib.timestamp() run.write_attr("exit_status", exit_status) run.write_attr("stopped", stopped) _delete_proc_lock(run) def _delete_proc_lock(run): try: os.remove(run.guild_path("LOCK")) except OSError: pass # ================================================================= # Proc env # ================================================================= def _op_proc_env(op, run): env = dict(op.cmd_env) env.update(_op_proc_env_system(op)) env.update(_op_proc_env_run(run)) return env def _op_proc_env_system(op): env = util.safe_osenv() env["GUILD_HOME"] = config.guild_home() env["LOG_LEVEL"] = _log_level() env["PYTHONPATH"] = _python_path(op) env["CMD_DIR"] = os.getcwd() return env def _op_proc_env_run(run): return { "RUN_DIR": run.dir, "RUN_ID": run.id, } def _log_level(): try: return os.environ["LOG_LEVEL"] except KeyError: return str(logging.getLogger().getEffectiveLevel()) def _python_path(op): paths = op.sourcecode_paths + _guild_paths() + _env_paths() return os.path.pathsep.join(paths) def _guild_paths(): guild_path = os.path.dirname(os.path.dirname(__file__)) abs_guild_path = os.path.abspath(guild_path) return _runfile_paths() + [abs_guild_path] def _runfile_paths(): return [os.path.abspath(path) for path in sys.path if _is_runfile_pkg(path)] def _is_runfile_pkg(path): for runfile_path in OP_RUNFILE_PATHS: split_path = path.split(os.path.sep) if split_path[-len(runfile_path) :] == runfile_path: return True return False def _env_paths(): env = os.getenv("PYTHONPATH") return env.split(os.path.pathsep) if env else [] # ================================================================= # Resolve deps # ================================================================= def _resolve_deps(op, run, for_stage=False): resolved = run.get("resolved_deps") or {} for dep in op.deps or []: log.info("Resolving %s dependency", dep.resdef.name) resolved_sources = resolved.setdefault(dep.resdef.name, {}) for source in dep.resdef.sources: if source.name in resolved_sources: log.info("Skipping %s because it's already resolved", source.name) continue if for_stage and _is_operation_source(source): log.info("Skipping operation dependency %s for stage", source.name) continue paths = op_dep.resolve_source(source, dep, run.dir) rel_paths = [os.path.relpath(path, run.dir) for path in paths] resolved_sources[source.name] = rel_paths run.write_attr("resolved_deps", resolved) def _is_operation_source(source): return source.uri.startswith("operation:")
[]
[]
[ "NO_RUN_OUTPUT_CAPTURE", "PYTHONPATH", "LOG_LEVEL" ]
[]
["NO_RUN_OUTPUT_CAPTURE", "PYTHONPATH", "LOG_LEVEL"]
python
3
0
drb/commands/genspec.py
from __future__ import unicode_literals import os from filecmp import cmp import glob import shutil import logging import click from drb.configure_logging import configure_root_logger from drb.docker import Docker from drb.spectemplate import SpecTemplate from drb.path import getpath from drb.downloadsources import downloadsources from drb.parse_ownership import parse_ownership from drb.mkdir_p import mkdir_p from drb.functional import one from drb.exception_transformer import UserExceptionTransformer _HELP = """Generates a spec file from a spectemplate. If the target specfile already exists and is identical, the target is untouched. docker-rpm-builder genspec SPECTEMPLATE TARGETSPEC SPECTEMPLATE should be a readable spectemplate path TARGETSPEC should be a non-existing or writeable path Examples: docker-rpm-builder genspec tmux.spectemplate build-image/tmux.spec """ _logger = logging.getLogger("drb.commands.genspec") @click.command(help=_HELP) @click.argument("spectemplate", nargs=1, type=click.Path(exists=True, dir_okay=False, resolve_path=True)) @click.argument("targetspec", nargs=1, type=click.Path(dir_okay=False, resolve_path=True)) @click.option('--verbose', is_flag=True, default=False) def genspec(spectemplate, targetspec, verbose): configure_root_logger(verbose) rendered_filename = SpecTemplate.from_path(spectemplate).render(os.environ) mkdir_p(os.path.dirname(targetspec)) if not os.path.exists(targetspec) or not cmp(rendered_filename, targetspec): shutil.copy(rendered_filename, targetspec) _logger.info("Spectemplate was rendered successfully. Your compiled spec is in %s", targetspec)
[]
[]
[]
[]
[]
python
0
0
cli/cmd/send_event_approvalFinished.go
package cmd import ( "bufio" "encoding/json" "errors" "fmt" keptnv2 "github.com/keptn/go-utils/pkg/lib/v0_2_0" "github.com/keptn/keptn/cli/pkg/common" "net/url" "os" "strconv" "strings" "text/tabwriter" cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/google/uuid" apimodels "github.com/keptn/go-utils/pkg/api/models" apiutils "github.com/keptn/go-utils/pkg/api/utils" "github.com/keptn/keptn/cli/pkg/credentialmanager" "github.com/keptn/keptn/cli/pkg/logging" "github.com/mitchellh/mapstructure" "github.com/spf13/cobra" ) type sendApprovalFinishedStruct struct { Project *string `json:"project"` Stage *string `json:"stage"` Service *string `json:"service"` ID *string `json:"id"` } var sendApprovalFinishedOptions sendApprovalFinishedStruct var approvalFinishedCmd = &cobra.Command{ Use: "approval.finished", Short: "Sends an approval.finished event to Keptn in order to confirm an open approval " + "with the specified ID in the provided project and stage", Long: `Sends an approval.finished event to Keptn in order to confirm an open approval with the specified ID in the provided project and stage. * This command takes the project (*--project*) and stage (*--stage*). * It is optional to specify the ID (*--id*) of the corresponding approval.triggered event. If the ID is not provided, the command asks the user which open approval should be accepted or declined. * The open approval.triggered events and their ID can be retrieved using the "keptn get event approval.triggered --project=<project> --stage=<stage>" command. `, Example: `keptn send event approval.finished --project=sockshop --stage=hardening --id=1234-5678-9123`, RunE: func(cmd *cobra.Command, args []string) error { if err := deSendEventApprovalFinishedPreRunCheck(); err != nil { return err } return sendApprovalFinishedEvent(sendApprovalFinishedOptions) }, SilenceUsage: true, } func deSendEventApprovalFinishedPreRunCheck() error { if *sendApprovalFinishedOptions.ID == "" && *sendApprovalFinishedOptions.Service == "" { logging.PrintLog("Either ID or service must be provided", logging.InfoLevel) return errors.New("either ID or service must be provided") } else if *sendApprovalFinishedOptions.ID != "" && *sendApprovalFinishedOptions.Service != "" { logging.PrintLog("Either ID or service must be provided", logging.InfoLevel) return errors.New("either ID or service must be provided") } return nil } func sendApprovalFinishedEvent(sendApprovalFinishedOptions sendApprovalFinishedStruct) error { var endPoint url.URL var apiToken string var err error if !mocking { endPoint, apiToken, err = credentialmanager.NewCredentialManager(false).GetCreds(namespace) } else { endPointPtr, _ := url.Parse(os.Getenv("MOCK_SERVER")) endPoint = *endPointPtr apiToken = "" } if err != nil { return errors.New(authErrorMsg) } logging.PrintLog("Starting to send approval.finished event", logging.InfoLevel) if endPointErr := checkEndPointStatus(endPoint.String()); endPointErr != nil { return fmt.Errorf("Error connecting to server: %s"+endPointErrorReasons, endPointErr) } apiHandler := apiutils.NewAuthenticatedAPIHandler(endPoint.String(), apiToken, "x-token", nil, endPoint.Scheme) eventHandler := apiutils.NewAuthenticatedEventHandler(endPoint.String(), apiToken, "x-token", nil, endPoint.Scheme) logging.PrintLog(fmt.Sprintf("Connecting to server %s", endPoint.String()), logging.VerboseLevel) var keptnContext string var triggeredID string var approvalFinishedEvent *keptnv2.ApprovalFinishedEventData if *sendApprovalFinishedOptions.ID != "" { keptnContext, triggeredID, approvalFinishedEvent, err = getApprovalFinishedForID(eventHandler, sendApprovalFinishedOptions) } else if *sendApprovalFinishedOptions.Service != "" { scHandler := apiutils.NewAuthenticatedShipyardControllerHandler(endPoint.String(), apiToken, "x-token", nil, endPoint.Scheme) keptnContext, triggeredID, approvalFinishedEvent, err = getApprovalFinishedForService(eventHandler, scHandler, sendApprovalFinishedOptions) } if err != nil { return err } if approvalFinishedEvent == nil { return nil } startedEvent := getApprovalStartedEvent(approvalFinishedEvent.EventData) if _, err := sendEvent(keptnContext, triggeredID, keptnv2.GetStartedEventType(keptnv2.ApprovalTaskName), startedEvent, apiHandler); err != nil { return err } responseEvent, err := sendEvent(keptnContext, triggeredID, keptnv2.GetFinishedEventType(keptnv2.ApprovalTaskName), approvalFinishedEvent, apiHandler) if err != nil { return err } if responseEvent == nil { logging.PrintLog("No event returned", logging.QuietLevel) return nil } return nil } func sendEvent(keptnContext, triggeredID, eventType string, approvalFinishedEvent interface{}, apiHandler *apiutils.APIHandler) (*apimodels.EventContext, error) { ID := uuid.New().String() source, _ := url.Parse("https://github.com/keptn/keptn/cli#" + eventType) sdkEvent := cloudevents.NewEvent() sdkEvent.SetID(ID) sdkEvent.SetType(eventType) sdkEvent.SetSource(source.String()) sdkEvent.SetDataContentType(cloudevents.ApplicationJSON) sdkEvent.SetExtension("shkeptncontext", keptnContext) sdkEvent.SetExtension("triggeredid", triggeredID) sdkEvent.SetData(cloudevents.ApplicationJSON, approvalFinishedEvent) eventByte, err := json.Marshal(sdkEvent) if err != nil { return nil, fmt.Errorf("Failed to marshal cloud event. %s", err.Error()) } apiEvent := apimodels.KeptnContextExtendedCE{} err = json.Unmarshal(eventByte, &apiEvent) if err != nil { return nil, fmt.Errorf("Failed to map cloud event to API event model. %s", err.Error()) } responseEvent, errorObj := apiHandler.SendEvent(apiEvent) if errorObj != nil { logging.PrintLog("Send "+eventType+" was unsuccessful", logging.QuietLevel) return nil, fmt.Errorf("Send %s was unsuccessful. %s", eventType, *errorObj.Message) } return responseEvent, nil } func getApprovalStartedEvent(inputEvent keptnv2.EventData) *keptnv2.ApprovalStartedEventData { startedEvent := &keptnv2.ApprovalStartedEventData{ EventData: keptnv2.EventData{ Project: inputEvent.Project, Stage: inputEvent.Stage, Service: inputEvent.Service, Labels: inputEvent.Labels, Status: inputEvent.Status, }, } return startedEvent } func getApprovalFinishedForService(eventHandler *apiutils.EventHandler, scHandler *apiutils.ShipyardControllerHandler, approvalFinishedOptions sendApprovalFinishedStruct) (string, string, *keptnv2.ApprovalFinishedEventData, error) { allEvents, err := scHandler.GetOpenTriggeredEvents(apiutils.EventFilter{ Project: *approvalFinishedOptions.Project, Stage: *approvalFinishedOptions.Stage, Service: *approvalFinishedOptions.Service, EventType: keptnv2.GetTriggeredEventType(keptnv2.ApprovalTaskName), }) if err != nil { logging.PrintLog("Open approval.triggered event for service "+*approvalFinishedOptions.Service+" could not be retrieved: "+err.Error(), logging.InfoLevel) return "", "", nil, err } if len(allEvents) == 0 { logging.PrintLog("No open approval.triggered event for service "+*approvalFinishedOptions.Service+" has been found", logging.InfoLevel) return "", "", nil, nil } // print all available options printApprovalOptions(allEvents, eventHandler, approvalFinishedOptions) // select option nrOfOptions := len(allEvents) selectedOption, err := selectApprovalOption(nrOfOptions) if err != nil { return "", "", nil, err } index := selectedOption - 1 eventToBeApproved := allEvents[index] // approve or decline? approve := approveOrDecline() approvalTriggeredEvent := &keptnv2.ApprovalTriggeredEventData{} err = mapstructure.Decode(eventToBeApproved.Data, approvalTriggeredEvent) if err != nil { logging.PrintLog("Cannot decode approval.triggered event: "+err.Error(), logging.InfoLevel) return "", "", nil, err } var approvalResult keptnv2.ResultType if approve { approvalResult = keptnv2.ResultPass } else { approvalResult = keptnv2.ResultFailed } approvalFinishedEvent := &keptnv2.ApprovalFinishedEventData{ EventData: keptnv2.EventData{ Project: approvalTriggeredEvent.Project, Stage: approvalTriggeredEvent.Stage, Service: approvalTriggeredEvent.Service, Labels: approvalTriggeredEvent.Labels, Status: keptnv2.StatusSucceeded, Result: approvalResult, Message: "", }, } return eventToBeApproved.Shkeptncontext, eventToBeApproved.ID, approvalFinishedEvent, nil } func approveOrDecline() bool { var approve bool keepAsking := true for keepAsking { logging.PrintLog("Do you want to (a)pprove or (d)ecline: ", logging.InfoLevel) reader := bufio.NewReader(os.Stdin) in, err := reader.ReadString('\n') if err != nil { logging.PrintLog("Invalid option. Please enter either 'a' to approve, or 'd' to decline", logging.InfoLevel) } in = strings.TrimSpace(in) if in != "a" && in != "d" { logging.PrintLog("Invalid option. Please enter either 'a' to approve, or 'd' to decline", logging.InfoLevel) } else { keepAsking = false } if in == "a" { approve = true } else if in == "d" { approve = false } } return approve } func selectApprovalOption(nrOfOptions int) (int, error) { var selectedOption int keepAsking := true for keepAsking { logging.PrintLog("Select the option to approve or decline: ", logging.InfoLevel) reader := bufio.NewReader(os.Stdin) in, err := reader.ReadString('\n') if err != nil { logging.PrintLog(fmt.Sprintf("Invalid option. Please enter a value between 1 and %d", nrOfOptions), logging.InfoLevel) } in = strings.TrimSpace(in) selectedOption, err = strconv.Atoi(in) if err != nil || selectedOption < 1 || selectedOption > nrOfOptions { logging.PrintLog(fmt.Sprintf("Invalid option. Please enter a value between 1 and %d", nrOfOptions), logging.InfoLevel) } else { keepAsking = false } } return selectedOption, nil } func printApprovalOptions(approvals []*apimodels.KeptnContextExtendedCE, eventHandler *apiutils.EventHandler, approvalFinishedOptions sendApprovalFinishedStruct) { // initialize tabwriter w := new(tabwriter.Writer) // minwidth, tabwidth, padding, padchar, flags w.Init(os.Stdout, 8, 8, 2, '\t', 0) defer w.Flush() fmt.Fprintf(w, "\n %s\t%s\t%s\t", "OPTION", "GIT COMMIT", "EVALUATION") for index, approval := range approvals { score := getScoreForApprovalTriggeredEvent(eventHandler, approvalFinishedOptions, approval) commitID := getCommitIDOfConfigurationChangeEvent(eventHandler, approvalFinishedOptions, approval) appendOptionToWriter(w, index, commitID, score) } fmt.Fprintf(w, "\n") } func appendOptionToWriter(w *tabwriter.Writer, index int, commitID, score string) { fmt.Fprintf(w, "\n (%d)\t%s\t%s\t", index+1, commitID, score) } func getScoreForApprovalTriggeredEvent(eventHandler *apiutils.EventHandler, approvalFinishedOptions sendApprovalFinishedStruct, approval *apimodels.KeptnContextExtendedCE) string { score := "n/a" evaluationDoneEvents, errorObj := eventHandler.GetEvents(&apiutils.EventFilter{ Project: *approvalFinishedOptions.Project, Stage: *approvalFinishedOptions.Stage, Service: *approvalFinishedOptions.Service, EventType: keptnv2.GetFinishedEventType(keptnv2.EvaluationTaskName), KeptnContext: approval.Shkeptncontext, }) if errorObj != nil { return score } if len(evaluationDoneEvents) == 0 { return score } evaluationDoneData := &keptnv2.EvaluationFinishedEventData{} err := mapstructure.Decode(evaluationDoneEvents[0].Data, evaluationDoneData) if err != nil { return score } score = fmt.Sprintf("%f", evaluationDoneData.Evaluation.Score) return score } func getCommitIDOfConfigurationChangeEvent(eventHandler *apiutils.EventHandler, approvalFinishedOptions sendApprovalFinishedStruct, approval *apimodels.KeptnContextExtendedCE) string { unknownCommitID := "n/a" deploymentFinishedEvents, errorObj := eventHandler.GetEvents(&apiutils.EventFilter{ Project: *approvalFinishedOptions.Project, Stage: *approvalFinishedOptions.Stage, Service: *approvalFinishedOptions.Service, EventType: keptnv2.GetFinishedEventType(keptnv2.DeploymentTaskName), KeptnContext: approval.Shkeptncontext, }) if errorObj != nil { return unknownCommitID } if len(deploymentFinishedEvents) == 0 { return unknownCommitID } deploymentFinishedData := &keptnv2.DeploymentFinishedEventData{} err := common.DecodeKeptnEventData(deploymentFinishedEvents[0].Data, deploymentFinishedData) if err != nil { return unknownCommitID } if deploymentFinishedData.Deployment.GitCommit == "" { return unknownCommitID } return deploymentFinishedData.Deployment.GitCommit } func getApprovalFinishedForID(eventHandler *apiutils.EventHandler, sendApprovalFinishedOptions sendApprovalFinishedStruct) (string, string, *keptnv2.ApprovalFinishedEventData, error) { events, errorObj := eventHandler.GetEvents(&apiutils.EventFilter{ Project: *sendApprovalFinishedOptions.Project, Stage: *sendApprovalFinishedOptions.Stage, EventType: keptnv2.GetTriggeredEventType(keptnv2.ApprovalTaskName), EventID: *sendApprovalFinishedOptions.ID, }) if errorObj != nil { logging.PrintLog("Cannot retrieve approval.triggered event with ID "+*sendApprovalFinishedOptions.ID+": "+*errorObj.Message, logging.InfoLevel) return "", "", nil, errors.New(*errorObj.Message) } if len(events) == 0 { logging.PrintLog("No open approval.triggered event with the ID "+*sendApprovalFinishedOptions.ID+" has been found", logging.InfoLevel) return "", "", nil, nil } approvalTriggeredEvent := &keptnv2.ApprovalTriggeredEventData{} if err := common.DecodeKeptnEventData(events[0].Data, approvalTriggeredEvent); err != nil { logging.PrintLog("Cannot decode approval.triggered event: "+err.Error(), logging.InfoLevel) return "", "", nil, err } approvalFinishedEvent := &keptnv2.ApprovalFinishedEventData{ EventData: keptnv2.EventData{ Project: approvalTriggeredEvent.Project, Stage: approvalTriggeredEvent.Stage, Service: approvalTriggeredEvent.Service, Labels: approvalTriggeredEvent.Labels, Status: keptnv2.StatusSucceeded, Result: keptnv2.ResultPass, Message: "", }, } return events[0].Shkeptncontext, events[0].ID, approvalFinishedEvent, nil } func init() { sendEventCmd.AddCommand(approvalFinishedCmd) sendApprovalFinishedOptions.Project = approvalFinishedCmd.Flags().StringP("project", "", "", "The project containing the service to be approved") approvalFinishedCmd.MarkFlagRequired("project") sendApprovalFinishedOptions.Stage = approvalFinishedCmd.Flags().StringP("stage", "", "", "The stage containing the service to be approved") approvalFinishedCmd.MarkFlagRequired("stage") sendApprovalFinishedOptions.Service = approvalFinishedCmd.Flags().StringP("service", "", "", "The service to be approved") sendApprovalFinishedOptions.ID = approvalFinishedCmd.Flags().StringP("id", "", "", "The ID of the approval.triggered event to be approved") // approvalFinishedCmd.MarkFlagRequired("id") }
[ "\"MOCK_SERVER\"" ]
[]
[ "MOCK_SERVER" ]
[]
["MOCK_SERVER"]
go
1
0
funcx_sdk/funcx/sdk/client.py
import json import os import logging from inspect import getsource from packaging.version import parse from globus_sdk import AuthClient from fair_research_login import NativeClient, JSONTokenStorage from funcx.sdk.search import SearchHelper, FunctionSearchResults from funcx.serialize import FuncXSerializer # from funcx.sdk.utils.futures import FuncXFuture from funcx.sdk.error_handling_client import FuncXErrorHandlingClient from funcx.sdk.utils.batch import Batch from funcx.utils.errors import FailureResponse, VersionMismatch, SerializationError, TaskPending from funcx.utils.handle_service_response import handle_response_errors try: from funcx_endpoint.version import VERSION as ENDPOINT_VERSION except ModuleNotFoundError: ENDPOINT_VERSION = None from funcx.sdk import VERSION as SDK_VERSION logger = logging.getLogger(__name__) class FuncXClient(FuncXErrorHandlingClient): """Main class for interacting with the funcX service Holds helper operations for performing common tasks with the funcX service. """ TOKEN_DIR = os.path.expanduser("~/.funcx/credentials") TOKEN_FILENAME = "funcx_sdk_tokens.json" FUNCX_SDK_CLIENT_ID = os.environ.get( "FUNCX_SDK_CLIENT_ID", "4cf29807-cf21-49ec-9443-ff9a3fb9f81c" ) FUNCX_SCOPE = os.environ.get( "FUNCX_SCOPE", "https://auth.globus.org/scopes/facd7ccc-c5f4-42aa-916b-a0e270e2c2a9/all", ) def __init__(self, http_timeout=None, funcx_home=os.path.join('~', '.funcx'), force_login=False, fx_authorizer=None, search_authorizer=None, openid_authorizer=None, funcx_service_address='https://api2.funcx.org/v2', check_endpoint_version=False, use_offprocess_checker=True, **kwargs): """ Initialize the client Parameters ---------- http_timeout: int Timeout for any call to service in seconds. Default is no timeout force_login: bool Whether to force a login to get new credentials. fx_authorizer:class:`GlobusAuthorizer <globus_sdk.authorizers.base.GlobusAuthorizer>`: A custom authorizer instance to communicate with funcX. Default: ``None``, will be created. search_authorizer:class:`GlobusAuthorizer <globus_sdk.authorizers.base.GlobusAuthorizer>`: A custom authorizer instance to communicate with Globus Search. Default: ``None``, will be created. openid_authorizer:class:`GlobusAuthorizer <globus_sdk.authorizers.base.GlobusAuthorizer>`: A custom authorizer instance to communicate with OpenID. Default: ``None``, will be created. funcx_service_address: str The address of the funcX web service to communicate with. Default: https://api.funcx.org/v2 use_offprocess_checker: Bool, Use this option to disable the offprocess_checker in the FuncXSerializer used by the client. Default: True Keyword arguments are the same as for BaseClient. """ self.func_table = {} self.use_offprocess_checker = use_offprocess_checker self.funcx_home = os.path.expanduser(funcx_home) if not os.path.exists(self.TOKEN_DIR): os.makedirs(self.TOKEN_DIR) tokens_filename = os.path.join(self.TOKEN_DIR, self.TOKEN_FILENAME) self.native_client = NativeClient(client_id=self.FUNCX_SDK_CLIENT_ID, app_name="FuncX SDK", token_storage=JSONTokenStorage(tokens_filename)) # TODO: if fx_authorizer is given, we still need to get an authorizer for Search search_scope = "urn:globus:auth:scope:search.api.globus.org:all" scopes = [self.FUNCX_SCOPE, search_scope, "openid"] if not fx_authorizer or not search_authorizer or not openid_authorizer: self.native_client.login(requested_scopes=scopes, no_local_server=kwargs.get("no_local_server", True), no_browser=kwargs.get("no_browser", True), refresh_tokens=kwargs.get("refresh_tokens", True), force=force_login) all_authorizers = self.native_client.get_authorizers_by_scope(requested_scopes=scopes) fx_authorizer = all_authorizers[self.FUNCX_SCOPE] search_authorizer = all_authorizers[search_scope] openid_authorizer = all_authorizers["openid"] super(FuncXClient, self).__init__("funcX", environment='funcx', authorizer=fx_authorizer, http_timeout=http_timeout, base_url=funcx_service_address, **kwargs) self.fx_serializer = FuncXSerializer(use_offprocess_checker=self.use_offprocess_checker) authclient = AuthClient(authorizer=openid_authorizer) user_info = authclient.oauth2_userinfo() self.searcher = SearchHelper(authorizer=search_authorizer, owner_uuid=user_info['sub']) self.funcx_service_address = funcx_service_address self.check_endpoint_version = check_endpoint_version self.version_check() def version_check(self): """Check this client version meets the service's minimum supported version. """ resp = self.get("version", params={"service": "all"}) versions = resp.data if "min_ep_version" not in versions: raise VersionMismatch("Failed to retrieve version information from funcX service.") min_ep_version = versions['min_ep_version'] min_sdk_version = versions['min_sdk_version'] if self.check_endpoint_version: if ENDPOINT_VERSION is None: raise VersionMismatch("You do not have the funcx endpoint installed. You can use 'pip install funcx-endpoint'.") if parse(ENDPOINT_VERSION) < parse(min_ep_version): raise VersionMismatch(f"Your version={ENDPOINT_VERSION} is lower than the " f"minimum version for an endpoint: {min_ep_version}. Please update. " f"pip install funcx-endpoint>={min_ep_version}") else: if parse(SDK_VERSION) < parse(min_sdk_version): raise VersionMismatch(f"Your version={SDK_VERSION} is lower than the " f"minimum version for funcx SDK: {min_sdk_version}. Please update. " f"pip install funcx>={min_sdk_version}") def logout(self): """Remove credentials from your local system """ self.native_client.logout() def update_table(self, return_msg, task_id): """ Parses the return message from the service and updates the internal func_table Parameters ---------- return_msg : str Return message received from the funcx service task_id : str task id string """ if isinstance(return_msg, str): r_dict = json.loads(return_msg) else: r_dict = return_msg r_status = r_dict.get('status', 'unknown') status = {'pending': True, 'status': r_status} if 'result' in r_dict: try: r_obj = self.fx_serializer.deserialize(r_dict['result']) completion_t = r_dict['completion_t'] except Exception: raise SerializationError("Result Object Deserialization") else: status.update({'pending': False, 'result': r_obj, 'completion_t': completion_t}) self.func_table[task_id] = status elif 'exception' in r_dict: try: r_exception = self.fx_serializer.deserialize(r_dict['exception']) completion_t = r_dict['completion_t'] logger.info(f"Exception : {r_exception}") except Exception: raise SerializationError("Task's exception object deserialization") else: status.update({'pending': False, 'exception': r_exception, 'completion_t': completion_t}) self.func_table[task_id] = status return status def get_task(self, task_id): """Get a funcX task. Parameters ---------- task_id : str UUID of the task Returns ------- dict Task block containing "status" key. """ if task_id in self.func_table: return self.func_table[task_id] r = self.get("tasks/{task_id}".format(task_id=task_id)) logger.debug("Response string : {}".format(r)) try: rets = self.update_table(r.text, task_id) except Exception as e: raise e return rets def get_result(self, task_id): """ Get the result of a funcX task Parameters ---------- task_id: str UUID of the task Returns ------- Result obj: If task completed Raises ------ Exception obj: Exception due to which the task failed """ task = self.get_task(task_id) if task['pending'] is True: raise TaskPending(task['status']) else: if 'result' in task: return task['result'] else: logger.warning("We have an exception : {}".format(task['exception'])) task['exception'].reraise() def get_batch_result(self, task_id_list): """ Request status for a batch of task_ids """ assert isinstance(task_id_list, list), "get_batch_result expects a list of task ids" pending_task_ids = [t for t in task_id_list if t not in self.func_table] results = {} if pending_task_ids: payload = {'task_ids': pending_task_ids} r = self.post("/batch_status", json_body=payload) logger.debug("Response string : {}".format(r)) pending_task_ids = set(pending_task_ids) for task_id in task_id_list: if task_id in pending_task_ids: try: data = r['results'][task_id] rets = self.update_table(data, task_id) results[task_id] = rets except KeyError: logger.debug("Task {} info was not available in the batch status") except Exception: logger.exception("Failure while unpacking results fom get_batch_result") else: results[task_id] = self.func_table[task_id] return results def run(self, *args, endpoint_id=None, function_id=None, **kwargs): """Initiate an invocation Parameters ---------- *args : Any Args as specified by the function signature endpoint_id : uuid str Endpoint UUID string. Required function_id : uuid str Function UUID string. Required asynchronous : bool Whether or not to run the function asynchronously Returns ------- task_id : str UUID string that identifies the task """ assert endpoint_id is not None, "endpoint_id key-word argument must be set" assert function_id is not None, "function_id key-word argument must be set" batch = self.create_batch() batch.add(*args, endpoint_id=endpoint_id, function_id=function_id, **kwargs) r = self.batch_run(batch) """ Create a future to deal with the result funcx_future = FuncXFuture(self, task_id, async_poll) if not asynchronous: return funcx_future.result() # Return the result return funcx_future """ return r[0] def create_batch(self): """ Create a Batch instance to handle batch submission in funcX Parameters ---------- Returns ------- Batch instance Status block containing "status" key. """ batch = Batch() return batch def batch_run(self, batch): """Initiate a batch of tasks to funcX Parameters ---------- batch: a Batch object Returns ------- task_ids : a list of UUID strings that identify the tasks """ servable_path = 'submit' assert isinstance(batch, Batch), "Requires a Batch object as input" assert len(batch.tasks) > 0, "Requires a non-empty batch" data = batch.prepare() # Send the data to funcX r = self.post(servable_path, json_body=data) task_uuids = [] for result in r['results']: task_id = result['task_uuid'] task_uuids.append(task_id) if result['http_status_code'] != 200: # this method of handling errors for a batch response is not # ideal, as it will raise any error in the multi-response, # but it will do until batch_run is deprecated in favor of Executer handle_response_errors(result) return task_uuids def map_run(self, *args, endpoint_id=None, function_id=None, asynchronous=False, **kwargs): """Initiate an invocation Parameters ---------- *args : Any Args as specified by the function signature endpoint_id : uuid str Endpoint UUID string. Required function_id : uuid str Function UUID string. Required asynchronous : bool Whether or not to run the function asynchronously Returns ------- task_id : str UUID string that identifies the task """ servable_path = 'submit_batch' assert endpoint_id is not None, "endpoint_id key-word argument must be set" assert function_id is not None, "function_id key-word argument must be set" ser_kwargs = self.fx_serializer.serialize(kwargs) batch_payload = [] iterator = args[0] for arg in iterator: ser_args = self.fx_serializer.serialize((arg,)) payload = self.fx_serializer.pack_buffers([ser_args, ser_kwargs]) batch_payload.append(payload) data = {'endpoints': [endpoint_id], 'func': function_id, 'payload': batch_payload, 'is_async': asynchronous} # Send the data to funcX r = self.post(servable_path, json_body=data) return r['task_uuids'] def register_endpoint(self, name, endpoint_uuid, metadata=None, endpoint_version=None): """Register an endpoint with the funcX service. Parameters ---------- name : str Name of the endpoint endpoint_uuid : str The uuid of the endpoint metadata : dict endpoint metadata, see default_config example endpoint_version: str Version string to be passed to the webService as a compatibility check Returns ------- A dict {'endpoint_id' : <>, 'address' : <>, 'client_ports': <>} """ self.version_check() data = { "endpoint_name": name, "endpoint_uuid": endpoint_uuid, "version": endpoint_version } if metadata: data['meta'] = metadata r = self.post("/endpoints", json_body=data) # Return the result return r.data def get_containers(self, name, description=None): """Register a DLHub endpoint with the funcX service and get the containers to launch. Parameters ---------- name : str Name of the endpoint description : str Description of the endpoint Returns ------- int The port to connect to and a list of containers """ registration_path = 'get_containers' data = {"endpoint_name": name, "description": description} r = self.post(registration_path, json_body=data) # Return the result return r.data['endpoint_uuid'], r.data['endpoint_containers'] def get_container(self, container_uuid, container_type): """Get the details of a container for staging it locally. Parameters ---------- container_uuid : str UUID of the container in question container_type : str The type of containers that will be used (Singularity, Shifter, Docker) Returns ------- dict The details of the containers to deploy """ self.version_check() container_path = f'containers/{container_uuid}/{container_type}' r = self.get(container_path) # Return the result return r.data['container'] def get_endpoint_status(self, endpoint_uuid): """Get the status reports for an endpoint. Parameters ---------- endpoint_uuid : str UUID of the endpoint in question Returns ------- dict The details of the endpoint's stats """ stats_path = f'endpoints/{endpoint_uuid}/status' r = self.get(stats_path) # Return the result return r.data def register_function(self, function, function_name=None, container_uuid=None, description=None, public=False, group=None, searchable=True): """Register a function code with the funcX service. Parameters ---------- function : Python Function The function to be registered for remote execution function_name : str The entry point (function name) of the function. Default: None container_uuid : str Container UUID from registration with funcX description : str Description of the file public : bool Whether or not the function is publicly accessible. Default = False group : str A globus group uuid to share this function with searchable : bool If true, the function will be indexed into globus search with the appropriate permissions Returns ------- function uuid : str UUID identifier for the registered function """ source_code = "" try: source_code = getsource(function) except OSError: logger.error("Failed to find source code during function registration.") serialized_fn = self.fx_serializer.serialize(function) packed_code = self.fx_serializer.pack_buffers([serialized_fn]) data = {"function_name": function.__name__, "function_code": packed_code, "function_source": source_code, "container_uuid": container_uuid, "entry_point": function_name if function_name else function.__name__, "description": description, "public": public, "group": group, "searchable": searchable} logger.info("Registering function : {}".format(data)) r = self.post("/functions", json_body=data) func_uuid = r.data['function_uuid'] # Return the result return func_uuid def update_function(self, func_uuid, function): pass def search_function(self, q, offset=0, limit=10, advanced=False): """Search for function via the funcX service Parameters ---------- q : str free-form query string offset : int offset into total results limit : int max number of results to return advanced : bool allows elastic-search like syntax in query string Returns ------- FunctionSearchResults """ return self.searcher.search_function(q, offset=offset, limit=limit, advanced=advanced) def search_endpoint(self, q, scope='all', owner_id=None): """ Parameters ---------- q scope : str Can be one of {'all', 'my-endpoints', 'shared-with-me'} owner_id should be urn like f"urn:globus:auth:identity:{owner_uuid}" Returns ------- """ return self.searcher.search_endpoint(q, scope=scope, owner_id=owner_id) def register_container(self, location, container_type, name='', description=''): """Register a container with the funcX service. Parameters ---------- location : str The location of the container (e.g., its docker url). Required container_type : str The type of containers that will be used (Singularity, Shifter, Docker). Required name : str A name for the container. Default = '' description : str A description to associate with the container. Default = '' Returns ------- str The id of the container """ container_path = 'containers' payload = {'name': name, 'location': location, 'description': description, 'type': container_type} r = self.post(container_path, json_body=payload) # Return the result return r.data['container_id'] def add_to_whitelist(self, endpoint_id, function_ids): """Adds the function to the endpoint's whitelist Parameters ---------- endpoint_id : str The uuid of the endpoint function_ids : list A list of function id's to be whitelisted Returns ------- json The response of the request """ req_path = f'endpoints/{endpoint_id}/whitelist' if not isinstance(function_ids, list): function_ids = [function_ids] payload = {'func': function_ids} r = self.post(req_path, json_body=payload) # Return the result return r def get_whitelist(self, endpoint_id): """List the endpoint's whitelist Parameters ---------- endpoint_id : str The uuid of the endpoint Returns ------- json The response of the request """ req_path = f'endpoints/{endpoint_id}/whitelist' r = self.get(req_path) # Return the result return r def delete_from_whitelist(self, endpoint_id, function_ids): """List the endpoint's whitelist Parameters ---------- endpoint_id : str The uuid of the endpoint function_ids : list A list of function id's to be whitelisted Returns ------- json The response of the request """ if not isinstance(function_ids, list): function_ids = [function_ids] res = [] for fid in function_ids: req_path = f'endpoints/{endpoint_id}/whitelist/{fid}' r = self.delete(req_path) res.append(r) # Return the result return res
[]
[]
[ "FUNCX_SDK_CLIENT_ID", "FUNCX_SCOPE" ]
[]
["FUNCX_SDK_CLIENT_ID", "FUNCX_SCOPE"]
python
2
0
reana_commons/utils.py
# -*- coding: utf-8 -*- # # This file is part of REANA. # Copyright (C) 2018, 2019, 2020, 2021, 2022 CERN. # # REANA is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """REANA-Commons utils.""" import datetime import json import logging import os import platform import shutil import subprocess import sys import time import uuid from hashlib import md5 from pathlib import Path from typing import Dict, Tuple, Optional import click import requests from reana_commons.config import ( CVMFS_REPOSITORIES, REANA_COMPONENT_NAMING_SCHEME, REANA_COMPONENT_PREFIX, REANA_COMPONENT_TYPES, REANA_CVMFS_PVC_TEMPLATE, REANA_CVMFS_SC_TEMPLATE, REANA_JOB_CONTROLLER_CONNECTION_CHECK_SLEEP, ) from reana_commons.errors import REANAMissingWorkspaceError def click_table_printer(headers, _filter, data, colours=None): """Generate space separated output for click commands.""" _filter = [h.lower() for h in _filter] + [h.upper() for h in _filter] header_indexes = [i for i, item in enumerate(headers)] if _filter: header_indexes = [ i for i, item in enumerate(headers) if item.upper() in _filter ] headers = [h for h in headers if not _filter or h in _filter] # Maximum header width header_widths = [len(h) for h in headers] for row in data: for i, idx in enumerate(header_indexes): # If a row contains an element which is wider update maximum width if header_widths[i] < len(str(row[idx])): header_widths[i] = len(str(row[idx])) # Prepare the format string with the maximum widths formatted_output_parts = ["{{:<{0}}}".format(hw) for hw in header_widths] formatted_output = " ".join(formatted_output_parts) # Print the table with the headers capitalized click.echo(formatted_output.format(*[h.upper() for h in headers])) colours = colours if len(colours or []) == len(data) else None for i, row in enumerate(data): if header_indexes: row = [row[i] for i in header_indexes] click.secho( formatted_output.format(*row), fg=colours[i] if colours else None, ) def calculate_hash_of_dir(directory, file_list=None): """Calculate hash of directory.""" md5_hash = md5() if not os.path.exists(directory): return -1 sorted_by_dirs = sorted(list(os.walk(directory)), key=lambda x: x[2]) try: for subdir, dirs, files in sorted_by_dirs: for _file in files: file_path = os.path.join(subdir, _file) if file_list is not None and file_path not in file_list: continue try: _file_object = open(file_path, "rb") except Exception: # You can't open the file for some reason _file_object.close() # We return -1 since we cannot ensure that the file that # can not be read, will not change from one execution to # another. return -1 while 1: # Read file in little chunks buf = _file_object.read(4096) if not buf: break md5_hash.update(md5(buf).hexdigest().encode()) _file_object.close() except Exception: return -1 return md5_hash.hexdigest() def calculate_job_input_hash(job_spec, workflow_json): """Calculate md5 hash of job specification and workflow json.""" if "workflow_workspace" in job_spec: del job_spec["workflow_workspace"] job_md5_buffer = md5() job_md5_buffer.update(json.dumps(job_spec).encode("utf-8")) job_md5_buffer.update(json.dumps(workflow_json).encode("utf-8")) return job_md5_buffer.hexdigest() def calculate_file_access_time(workflow_workspace): """Calculate access times of files in workspace.""" access_times = {} for subdir, dirs, files in os.walk(workflow_workspace): for file in files: file_path = os.path.join(subdir, file) # skip symlinks if os.path.islink(file_path): continue access_times[file_path] = os.stat(file_path).st_atime return access_times def copy_openapi_specs(output_path, component): """Copy generated and validated openapi specs to reana-commons module.""" if component == "reana-server": file = "reana_server.json" elif component == "reana-workflow-controller": file = "reana_workflow_controller.json" elif component == "reana-job-controller": file = "reana_job_controller.json" if os.environ.get("REANA_SRCDIR"): reana_srcdir = os.environ.get("REANA_SRCDIR") else: reana_srcdir = os.path.join("..") try: reana_commons_specs_path = os.path.join( reana_srcdir, "reana-commons", "reana_commons", "openapi_specifications" ) if os.path.exists(reana_commons_specs_path): if os.path.isfile(output_path): shutil.copy(output_path, os.path.join(reana_commons_specs_path, file)) # copy openapi specs file as well to docs shutil.copy(output_path, os.path.join("docs", "openapi.json")) except Exception as e: click.echo( "Something went wrong, could not copy openapi " "specifications to reana-commons \n{0}".format(e) ) def get_workflow_status_change_verb(status): """Give the correct verb conjugation depending on status tense. :param status: String which represents the status the workflow changed to. """ verb = "" if status.endswith("ing"): verb = "is" elif status.endswith("ed"): verb = "has been" else: raise ValueError("Unrecognised status {}".format(status)) return verb def build_progress_message( total=None, running=None, finished=None, failed=None, cached=None ): """Build the progress message with correct formatting.""" progress_message = {} if total: progress_message["total"] = total if running: progress_message["running"] = running if finished: progress_message["finished"] = finished if failed: progress_message["failed"] = failed if cached: progress_message["cached"] = cached return progress_message def build_caching_info_message( job_spec, job_id, workflow_workspace, workflow_json, result_path ): """Build the caching info message with correct formatting.""" caching_info_message = { "job_spec": job_spec, "job_id": job_id, "workflow_workspace": workflow_workspace, "workflow_json": workflow_json, "result_path": result_path, } return caching_info_message def run_command(cmd, display=True, return_output=False, stderr_output=False): """Run given command on shell in the current directory. Exit in case of troubles. :param cmd: shell command to run :param display: should we display command to run? :param return_output: shall the output of the command be returned? :type cmd: str :type display: bool :type return_output: bool """ now = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") if display: click.secho("[{0}] ".format(now), bold=True, nl=False, fg="green") click.secho("{0}".format(cmd), bold=True) try: if return_output: stderr_flag_val = subprocess.STDOUT if stderr_output else None result = subprocess.check_output(cmd, stderr=stderr_flag_val, shell=True) return result.decode().rstrip("\r\n") else: subprocess.check_call(cmd, shell=True) except subprocess.CalledProcessError as err: if display: click.secho("[{0}] ".format(now), bold=True, nl=False, fg="green") click.secho("{0}".format(err), bold=True, fg="red") if stderr_output: sys.exit(err.output.decode()) sys.exit(err.returncode) def remove_upper_level_references(path): """Remove upper than `./` references. Collapse separators/up-level references avoiding references to paths outside working directory. :param path: User provided path to a file or directory. :return: Returns the corresponding sanitized path. """ return os.path.normpath("/" + path).lstrip("/") def is_directory(directory_path, path): """Whether the given path matches a directory or not. :param directory_path: Directory to check files from. :param path: Optional wildcard pattern to use for the check. :return: Full path if it is a directory, False if not. """ secure_path = remove_upper_level_references(path) full_path = Path(directory_path, secure_path) if full_path.is_dir(): return full_path return False def get_files_recursive_wildcard(directory_path, path): """Get file(s) fitting the wildcard from the workspace. :param directory_path: Directory to get files from. :param path: Wildcard pattern to use for the extraction. :return: list of paths sorted by length. """ secure_path = remove_upper_level_references(path) # if `secure_path` is a directory, append `/*` to get all the files inside if is_directory(directory_path, secure_path): _rstrip_path = secure_path.rstrip("/") secure_path = "{}/*".format(_rstrip_path) posix_dir_prefix = Path(directory_path) paths = list(posix_dir_prefix.glob(secure_path)) # sort paths by length to start with the leaves of the directory tree paths.sort(key=lambda path: len(str(path)), reverse=True) return paths, posix_dir_prefix def get_disk_usage_info_paths(absolute_path, command, name_filter): """Retrieve the path for disk usage information. :param absolute_path: System path to reana filesystem. :param command: Command to get the disk usage from reana filesystem. :param name_filter: Name filter parameters if any. :return: List of disk usage info containing the file path and size. """ if name_filter: path_list = [] for _path in name_filter: paths, _ = get_files_recursive_wildcard(absolute_path, _path) if paths: path_list += paths if path_list: for path in path_list: command.append(path) disk_usage_info = subprocess.check_output(command).decode().split() else: disk_usage_info = [] else: command.append(absolute_path) disk_usage_info = subprocess.check_output(command).decode().split() return disk_usage_info def get_disk_usage( directory, summarize=False, search=None, to_human_readable_units=None ): """Retrieve directory disk usage information. :param directory: Disk usage directory. :param summarize: Displays a total size of a directory. :param search: Filter parameters to show only files that match certain filtering. :param to_human_readable_units: Callback to transform bytes to human readable units. :return: List of dicts with file name and size. """ if not os.path.exists(directory): raise REANAMissingWorkspaceError("Directory does not exist.") command = ["du"] if summarize: command.append("-s") else: command.append("-a") if "Darwin" not in platform.system(): command.append("--block-size=1") name_filter = None size_filter = None if search: search = json.loads(search) name_filter = search.get("name") size_filter = search.get("size") disk_usage_info = get_disk_usage_info_paths(directory, command, name_filter) if disk_usage_info: filesize_pairs = list(zip(disk_usage_info[::2], disk_usage_info[1::2])) filesizes = [] for filesize_pair in filesize_pairs: size, name = filesize_pair size = int(size) # trim workspace path in every file name, and transform bytes if necessary file_data = { "name": name[len(directory) :], "size": {"raw": size}, } if to_human_readable_units: file_data["size"]["human_readable"] = to_human_readable_units(size) if size_filter: if str(size) in size_filter: filesizes.append(file_data) else: filesizes.append(file_data) return filesizes return disk_usage_info def render_cvmfs_pvc(cvmfs_volume): """Render REANA_CVMFS_PVC_TEMPLATE.""" name = CVMFS_REPOSITORIES[cvmfs_volume] rendered_template = dict(REANA_CVMFS_PVC_TEMPLATE) rendered_template["metadata"]["name"] = "csi-cvmfs-{}-pvc".format(name) rendered_template["spec"]["storageClassName"] = "csi-cvmfs-{}".format(name) return rendered_template def render_cvmfs_sc(cvmfs_volume): """Render REANA_CVMFS_SC_TEMPLATE.""" name = CVMFS_REPOSITORIES[cvmfs_volume] rendered_template = dict(REANA_CVMFS_SC_TEMPLATE) rendered_template["metadata"]["name"] = "csi-cvmfs-{}".format(name) rendered_template["parameters"]["repository"] = cvmfs_volume return rendered_template def create_cvmfs_storage_class(cvmfs_volume): """Create CVMFS storage class.""" from kubernetes.client.rest import ApiException from reana_commons.k8s.api_client import current_k8s_storagev1_api_client try: current_k8s_storagev1_api_client.create_storage_class( render_cvmfs_sc(cvmfs_volume) ) except ApiException as e: if e.status != 409: raise e def create_cvmfs_persistent_volume_claim(cvmfs_volume): """Create CVMFS persistent volume claim.""" from kubernetes.client.rest import ApiException from reana_commons.k8s.api_client import current_k8s_corev1_api_client try: current_k8s_corev1_api_client.create_namespaced_persistent_volume_claim( "default", render_cvmfs_pvc(cvmfs_volume) ) except ApiException as e: if e.status != 409: raise e def format_cmd(cmd): """Return command in a valid format.""" if isinstance(cmd, str): cmd = [cmd] elif not isinstance(cmd, list): raise ValueError( "Command should be a list or a string and not {}".format(type(cmd)) ) return cmd def check_connection_to_job_controller(port=5000): """Check connection from workflow engine to job controller.""" url = "http://localhost:{}/jobs".format(port) retry_counter = 0 while retry_counter < 5: try: response = requests.get(url, timeout=10) if response.status_code == 200: break except Exception: pass time.sleep(REANA_JOB_CONTROLLER_CONNECTION_CHECK_SLEEP) retry_counter += 1 else: logging.error("Job controller is not reachable.", exc_info=True) def build_unique_component_name(component_type, id=None): """Use REANA component type and id build a human readable component name. :param component_type: One of ``reana_commons.config.REANA_COMPONENT_TYPES``. :param id: Unique identifier, if not specified a new UUID4 is created. :return: String representing the component name, i.e. reana-run-job-123456. """ if component_type not in REANA_COMPONENT_TYPES: raise ValueError( "{} not valid component type.\nChoose one of: {}".format( component_type, REANA_COMPONENT_TYPES ) ) return REANA_COMPONENT_NAMING_SCHEME.format( prefix=REANA_COMPONENT_PREFIX, component_type=component_type, id=id or str(uuid.uuid4()), ) def get_usage_percentage(usage: int, limit: int) -> str: """Usage percentage.""" if limit == 0: return "" return "{:.0%}".format(usage / limit) def get_quota_resource_usage( resource: Dict, human_readable_or_raw: str ) -> Tuple[str, Optional[str]]: """Return quota resource usage and health. :param resource: Dict representing quota resource obtained from get_quota_usage() :param human_readable_or_raw: One of ("human_readable", "raw") :return: Tuple containing quota resource usage string and resource health. i.e. ("1 MiB out of 10 MiB used (10%)", "healthy") """ usage = resource.get("usage") limit = resource.get("limit") limit_str = "" health = None if limit and limit.get("raw", 0) > 0: health = resource.get("health") percentage = get_usage_percentage(usage.get("raw"), limit.get("raw")) limit_str = f"out of {limit.get(human_readable_or_raw)} used ({percentage})" else: limit_str = "used" return f"{usage[human_readable_or_raw]} {limit_str}", health
[]
[]
[ "REANA_SRCDIR" ]
[]
["REANA_SRCDIR"]
python
1
0
internal/pipe/docker/docker_test.go
package docker import ( "flag" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "strings" "syscall" "testing" "github.com/amane3/goreleaser/internal/artifact" "github.com/amane3/goreleaser/internal/pipe" "github.com/amane3/goreleaser/internal/testlib" "github.com/amane3/goreleaser/pkg/config" "github.com/amane3/goreleaser/pkg/context" "github.com/stretchr/testify/require" ) var it = flag.Bool("it", false, "push images to docker hub") var registry = "localhost:5000/" var altRegistry = "localhost:5050/" func TestMain(m *testing.M) { flag.Parse() if *it { registry = "docker.io/" } os.Exit(m.Run()) } func start(t *testing.T) { if *it { return } if out, err := exec.Command( "docker", "run", "-d", "-p", "5000:5000", "--name", "registry", "registry:2", ).CombinedOutput(); err != nil { t.Log("failed to start docker registry", string(out), err) t.FailNow() } if out, err := exec.Command( "docker", "run", "-d", "-p", "5050:5000", "--name", "alt_registry", "registry:2", ).CombinedOutput(); err != nil { t.Log("failed to start alternate docker registry", string(out), err) t.FailNow() } } func killAndRm(t *testing.T) { if *it { return } t.Log("killing registry") _ = exec.Command("docker", "kill", "registry").Run() _ = exec.Command("docker", "rm", "registry").Run() _ = exec.Command("docker", "kill", "alt_registry").Run() _ = exec.Command("docker", "rm", "alt_registry").Run() } // TODO: this test is too big... split in smaller tests? Mainly the manifest ones... func TestRunPipe(t *testing.T) { type errChecker func(*testing.T, error) var shouldErr = func(msg string) errChecker { return func(t *testing.T, err error) { require.Error(t, err) require.Contains(t, err.Error(), msg) } } var shouldNotErr = func(t *testing.T, err error) { require.NoError(t, err) } type imageLabelFinder func(*testing.T, int) var shouldFindImagesWithLabels = func(image string, filters ...string) func(*testing.T, int) { return func(t *testing.T, count int) { for _, filter := range filters { output, err := exec.Command( "docker", "images", "-q", "*/"+image, "--filter", filter, ).CombinedOutput() require.NoError(t, err) lines := strings.Split(strings.TrimSpace(string(output)), "\n") require.Equal(t, count, len(lines)) } } } var noLabels = func(t *testing.T, count int) {} var table = map[string]struct { dockers []config.Docker manifests []config.DockerManifest env map[string]string expect []string assertImageLabels imageLabelFinder assertError errChecker pubAssertError errChecker manifestAssertError errChecker }{ "multiarch": { dockers: []config.Docker{ { ImageTemplates: []string{registry + "goreleaser/test_multiarch:test-amd64"}, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile.arch", Binaries: []string{"mybin"}, BuildFlagTemplates: []string{"--build-arg", "ARCH=amd64"}, }, { ImageTemplates: []string{registry + "goreleaser/test_multiarch:test-arm64v8"}, Goos: "linux", Goarch: "arm64", Dockerfile: "testdata/Dockerfile.arch", Binaries: []string{"mybin"}, BuildFlagTemplates: []string{"--build-arg", "ARCH=arm64v8"}, }, }, manifests: []config.DockerManifest{ { // XXX: fails if :latest https://github.com/docker/distribution/issues/3100 NameTemplate: registry + "goreleaser/test_multiarch:test", ImageTemplates: []string{ registry + "goreleaser/test_multiarch:test-amd64", registry + "goreleaser/test_multiarch:test-arm64v8", }, CreateFlags: []string{"--insecure"}, PushFlags: []string{"--insecure"}, }, }, expect: []string{ registry + "goreleaser/test_multiarch:test-amd64", registry + "goreleaser/test_multiarch:test-arm64v8", }, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldNotErr, assertImageLabels: noLabels, }, "multiarch image not found": { dockers: []config.Docker{ { ImageTemplates: []string{registry + "goreleaser/test_multiarch_fail:latest-arm64v8"}, Goos: "linux", Goarch: "arm64", Dockerfile: "testdata/Dockerfile.arch", Binaries: []string{"mybin"}, BuildFlagTemplates: []string{"--build-arg", "ARCH=arm64v8"}, }, }, manifests: []config.DockerManifest{ { NameTemplate: registry + "goreleaser/test_multiarch_fail:test", ImageTemplates: []string{registry + "goreleaser/test_multiarch_fail:latest-amd64"}, CreateFlags: []string{"--insecure"}, PushFlags: []string{"--insecure"}, }, }, expect: []string{registry + "goreleaser/test_multiarch_fail:latest-arm64v8"}, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldErr("failed to create docker manifest: localhost:5000/goreleaser/test_multiarch_fail:test"), assertImageLabels: noLabels, }, "multiarch manifest template error": { dockers: []config.Docker{ { ImageTemplates: []string{registry + "goreleaser/test_multiarch_manifest_tmpl_error"}, Goos: "linux", Goarch: "arm64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, }, }, manifests: []config.DockerManifest{ { NameTemplate: registry + "goreleaser/test_multiarch_manifest_tmpl_error:{{ .Goos }", ImageTemplates: []string{registry + "goreleaser/test_multiarch_manifest_tmpl_error"}, }, }, expect: []string{registry + "goreleaser/test_multiarch_manifest_tmpl_error"}, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldErr(`template: tmpl:1: unexpected "}" in operand`), assertImageLabels: noLabels, }, "multiarch image template error": { dockers: []config.Docker{ { ImageTemplates: []string{registry + "goreleaser/test_multiarch_img_tmpl_error"}, Goos: "linux", Goarch: "arm64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, }, }, manifests: []config.DockerManifest{ { NameTemplate: registry + "goreleaser/test_multiarch_img_tmpl_error", ImageTemplates: []string{registry + "goreleaser/test_multiarch_img_tmpl_error:{{ .Goos }"}, }, }, expect: []string{registry + "goreleaser/test_multiarch_img_tmpl_error"}, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldErr(`template: tmpl:1: unexpected "}" in operand`), assertImageLabels: noLabels, }, "multiarch missing manifest name": { dockers: []config.Docker{ { ImageTemplates: []string{registry + "goreleaser/test_multiarch_no_mainifest_name"}, Goos: "linux", Goarch: "arm64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, }, }, manifests: []config.DockerManifest{ { NameTemplate: " ", ImageTemplates: []string{registry + "goreleaser/test_multiarch_no_mainifest_name"}, }, }, expect: []string{registry + "goreleaser/test_multiarch_no_mainifest_name"}, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: testlib.AssertSkipped, assertImageLabels: noLabels, }, "multiarch missing images": { dockers: []config.Docker{ { ImageTemplates: []string{registry + "goreleaser/test_multiarch_no_mainifest_images"}, Dockerfile: "testdata/Dockerfile", Goos: "linux", Goarch: "arm64", Binaries: []string{"mybin"}, }, }, manifests: []config.DockerManifest{ { NameTemplate: "ignored", ImageTemplates: []string{" ", " ", ""}, }, }, expect: []string{registry + "goreleaser/test_multiarch_no_mainifest_images"}, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: testlib.AssertSkipped, assertImageLabels: noLabels, }, "valid": { env: map[string]string{ "FOO": "123", }, dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/test_run_pipe:{{.Tag}}-{{.Env.FOO}}", registry + "goreleaser/test_run_pipe:v{{.Major}}", registry + "goreleaser/test_run_pipe:v{{.Major}}.{{.Minor}}", registry + "goreleaser/test_run_pipe:commit-{{.Commit}}", registry + "goreleaser/test_run_pipe:latest", altRegistry + "goreleaser/test_run_pipe:{{.Tag}}-{{.Env.FOO}}", altRegistry + "goreleaser/test_run_pipe:v{{.Major}}", altRegistry + "goreleaser/test_run_pipe:v{{.Major}}.{{.Minor}}", altRegistry + "goreleaser/test_run_pipe:commit-{{.Commit}}", altRegistry + "goreleaser/test_run_pipe:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, BuildFlagTemplates: []string{ "--label=org.label-schema.schema-version=1.0", "--label=org.label-schema.version={{.Version}}", "--label=org.label-schema.vcs-ref={{.Commit}}", "--label=org.label-schema.name={{.ProjectName}}", "--build-arg=FRED={{.Tag}}", }, Files: []string{ "testdata/extra_file.txt", }, }, }, expect: []string{ registry + "goreleaser/test_run_pipe:v1.0.0-123", registry + "goreleaser/test_run_pipe:v1", registry + "goreleaser/test_run_pipe:v1.0", registry + "goreleaser/test_run_pipe:commit-a1b2c3d4", registry + "goreleaser/test_run_pipe:latest", altRegistry + "goreleaser/test_run_pipe:v1.0.0-123", altRegistry + "goreleaser/test_run_pipe:v1", altRegistry + "goreleaser/test_run_pipe:v1.0", altRegistry + "goreleaser/test_run_pipe:commit-a1b2c3d4", altRegistry + "goreleaser/test_run_pipe:latest", }, assertImageLabels: shouldFindImagesWithLabels( "goreleaser/test_run_pipe", "label=org.label-schema.schema-version=1.0", "label=org.label-schema.version=1.0.0", "label=org.label-schema.vcs-ref=a1b2c3d4", "label=org.label-schema.name=mybin", ), assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldNotErr, }, "valid-with-builds": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/test_run_pipe_build:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, Builds: []string{"mybin"}, }, }, expect: []string{ registry + "goreleaser/test_run_pipe_build:latest", }, assertImageLabels: noLabels, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldNotErr, }, "multiple images with same extra file": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/multiplefiles1:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, Files: []string{"testdata/extra_file.txt"}, }, { ImageTemplates: []string{ registry + "goreleaser/multiplefiles2:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, Files: []string{"testdata/extra_file.txt"}, }, }, expect: []string{ registry + "goreleaser/multiplefiles1:latest", registry + "goreleaser/multiplefiles2:latest", }, assertImageLabels: noLabels, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldNotErr, }, "multiple images with same dockerfile": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/test_run_pipe:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, }, { ImageTemplates: []string{ registry + "goreleaser/test_run_pipe2:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, }, }, assertImageLabels: noLabels, expect: []string{ registry + "goreleaser/test_run_pipe:latest", registry + "goreleaser/test_run_pipe2:latest", }, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldNotErr, }, "valid_skip_push": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/test_run_pipe:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, SkipPush: "true", }, }, expect: []string{ registry + "goreleaser/test_run_pipe:latest", }, assertImageLabels: noLabels, assertError: testlib.AssertSkipped, }, "one_img_error_with_skip_push": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/one_img_error_with_skip_push:true", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile.true", Binaries: []string{"mybin"}, SkipPush: "true", }, { ImageTemplates: []string{ registry + "goreleaser/one_img_error_with_skip_push:false", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile.false", Binaries: []string{"mybin"}, SkipPush: "true", }, }, expect: []string{ registry + "goreleaser/one_img_error_with_skip_push:true", }, assertImageLabels: noLabels, assertError: shouldErr("failed to build docker image"), }, "valid_no_latest": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/test_run_pipe:{{.Version}}", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, }, }, expect: []string{ registry + "goreleaser/test_run_pipe:1.0.0", }, assertImageLabels: noLabels, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldNotErr, }, "valid build args": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/test_build_args:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, BuildFlagTemplates: []string{ "--label=foo=bar", }, }, }, expect: []string{ registry + "goreleaser/test_build_args:latest", }, assertImageLabels: noLabels, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldNotErr, }, "bad build args": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/test_build_args:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, BuildFlagTemplates: []string{ "--bad-flag", }, }, }, assertImageLabels: noLabels, assertError: shouldErr("unknown flag: --bad-flag"), }, "bad_dockerfile": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/bad_dockerfile:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile.bad", Binaries: []string{"mybin"}, }, }, assertImageLabels: noLabels, assertError: shouldErr("pull access denied for nope, repository does not exist"), }, "tag_template_error": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/test_run_pipe:{{.Tag}", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, }, }, assertImageLabels: noLabels, assertError: shouldErr(`template: tmpl:1: unexpected "}" in operand`), }, "build_flag_template_error": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/test_run_pipe:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, BuildFlagTemplates: []string{ "--label=tag={{.Tag}", }, }, }, assertImageLabels: noLabels, assertError: shouldErr(`template: tmpl:1: unexpected "}" in operand`), }, "missing_env_on_tag_template": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/test_run_pipe:{{.Env.NOPE}}", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, }, }, assertImageLabels: noLabels, assertError: shouldErr(`template: tmpl:1:46: executing "tmpl" at <.Env.NOPE>: map has no entry for key "NOPE"`), }, "missing_env_on_build_flag_template": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/test_run_pipe:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, BuildFlagTemplates: []string{ "--label=nope={{.Env.NOPE}}", }, }, }, assertImageLabels: noLabels, assertError: shouldErr(`template: tmpl:1:19: executing "tmpl" at <.Env.NOPE>: map has no entry for key "NOPE"`), }, "image_has_projectname_template_variable": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/{{.ProjectName}}:{{.Tag}}-{{.Env.FOO}}", registry + "goreleaser/{{.ProjectName}}:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"mybin"}, SkipPush: "true", }, }, env: map[string]string{ "FOO": "123", }, expect: []string{ registry + "goreleaser/mybin:v1.0.0-123", registry + "goreleaser/mybin:latest", }, assertImageLabels: noLabels, assertError: testlib.AssertSkipped, }, "no_permissions": { dockers: []config.Docker{ { ImageTemplates: []string{"docker.io/nope:latest"}, Goos: "linux", Goarch: "amd64", Binaries: []string{"mybin"}, Dockerfile: "testdata/Dockerfile", }, }, expect: []string{ "docker.io/nope:latest", }, assertImageLabels: noLabels, assertError: shouldNotErr, pubAssertError: shouldErr(`requested access to the resource is denied`), manifestAssertError: shouldNotErr, }, "dockerfile_doesnt_exist": { dockers: []config.Docker{ { ImageTemplates: []string{"whatever:latest"}, Goos: "linux", Goarch: "amd64", Binaries: []string{"mybin"}, Dockerfile: "testdata/Dockerfilezzz", }, }, assertImageLabels: noLabels, assertError: shouldErr(`failed to link dockerfile`), }, "extra_file_doesnt_exist": { dockers: []config.Docker{ { ImageTemplates: []string{"whatever:latest"}, Goos: "linux", Goarch: "amd64", Binaries: []string{"mybin"}, Dockerfile: "testdata/Dockerfile", Files: []string{ "testdata/nope.txt", }, }, }, assertImageLabels: noLabels, assertError: shouldErr(`failed to link extra file 'testdata/nope.txt'`), }, "no_matching_binaries": { dockers: []config.Docker{ { ImageTemplates: []string{"whatever:latest"}, Goos: "darwin", Goarch: "amd64", Binaries: []string{"mybinnnn"}, Dockerfile: "testdata/Dockerfile", }, }, assertImageLabels: noLabels, assertError: shouldErr(`0 binaries match docker definition: [mybinnnn]: darwin_amd64_, should be 1`), }, "multiple_binaries": { dockers: []config.Docker{ { ImageTemplates: []string{registry + "goreleaser/multiple:latest"}, Goos: "darwin", Goarch: "amd64", Binaries: []string{"mybin", "anotherbin"}, Dockerfile: "testdata/Dockerfile.multiple", }, }, assertImageLabels: noLabels, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldNotErr, expect: []string{ registry + "goreleaser/multiple:latest", }, }, // TODO: add a test case for multiple matching binaries for the same name "templated_binaries": { env: map[string]string{ "BIN_NAME": "mybin", }, dockers: []config.Docker{ { ImageTemplates: []string{registry + "goreleaser/templatedbins:latest"}, Goos: "darwin", Goarch: "amd64", Binaries: []string{"{{.Env.BIN_NAME}}"}, Dockerfile: "testdata/Dockerfile", }, }, assertImageLabels: noLabels, assertError: shouldNotErr, pubAssertError: shouldNotErr, manifestAssertError: shouldNotErr, expect: []string{ registry + "goreleaser/templatedbins:latest", }, }, "binaries_template_error": { dockers: []config.Docker{ { ImageTemplates: []string{ registry + "goreleaser/binaries_template_error:latest", }, Goos: "linux", Goarch: "amd64", Dockerfile: "testdata/Dockerfile", Binaries: []string{"{{.Env.BAR}"}, }, }, assertImageLabels: noLabels, assertError: shouldErr(`template: tmpl:1: unexpected "}" in operand`), }, } killAndRm(t) start(t) defer killAndRm(t) for name, docker := range table { t.Run(name, func(tt *testing.T) { var folder = t.TempDir() var dist = filepath.Join(folder, "dist") require.NoError(tt, os.Mkdir(dist, 0755)) require.NoError(tt, os.Mkdir(filepath.Join(dist, "mybin"), 0755)) _, err := os.Create(filepath.Join(dist, "mybin", "mybin")) require.NoError(tt, err) _, err = os.Create(filepath.Join(dist, "mybin", "anotherbin")) require.NoError(tt, err) var ctx = context.New(config.Project{ ProjectName: "mybin", Dist: dist, Dockers: docker.dockers, DockerManifests: docker.manifests, }) ctx.Parallelism = 1 ctx.Env = docker.env ctx.Version = "1.0.0" ctx.Git = context.GitInfo{ CurrentTag: "v1.0.0", Commit: "a1b2c3d4", } ctx.Semver = context.Semver{ Major: 1, Minor: 0, Patch: 0, } for _, os := range []string{"linux", "darwin"} { for _, arch := range []string{"amd64", "386", "arm64"} { for _, bin := range []string{"mybin", "anotherbin"} { ctx.Artifacts.Add(&artifact.Artifact{ Name: bin, Path: filepath.Join(dist, "mybin", bin), Goarch: arch, Goos: os, Type: artifact.Binary, Extra: map[string]interface{}{ "Binary": bin, "ID": bin, }, }) } } } // this might fail as the image doesnt exist yet, so lets ignore the error for _, img := range docker.expect { _ = exec.Command("docker", "rmi", img).Run() } err = Pipe{}.Run(ctx) docker.assertError(tt, err) if err == nil { docker.pubAssertError(tt, Pipe{}.Publish(ctx)) docker.manifestAssertError(tt, ManifestPipe{}.Publish(ctx)) } for _, d := range docker.dockers { docker.assertImageLabels(tt, len(d.ImageTemplates)) } // this might should not fail as the image should have been created when // the step ran for _, img := range docker.expect { tt.Log("removing docker image", img) require.NoError(tt, exec.Command("docker", "rmi", img).Run(), "could not delete image %s", img) } }) } } func TestBuildCommand(t *testing.T) { images := []string{"goreleaser/test_build_flag", "goreleaser/test_multiple_tags"} tests := []struct { name string flags []string expect []string }{ { name: "no flags", flags: []string{}, expect: []string{"build", ".", "-t", images[0], "-t", images[1]}, }, { name: "single flag", flags: []string{"--label=foo"}, expect: []string{"build", ".", "-t", images[0], "-t", images[1], "--label=foo"}, }, { name: "multiple flags", flags: []string{"--label=foo", "--build-arg=bar=baz"}, expect: []string{"build", ".", "-t", images[0], "-t", images[1], "--label=foo", "--build-arg=bar=baz"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { command := buildCommand(images, tt.flags) require.Equal(t, tt.expect, command) }) } } func TestDescription(t *testing.T) { require.NotEmpty(t, Pipe{}.String()) } func TestNoDockers(t *testing.T) { require.True(t, pipe.IsSkip(Pipe{}.Run(context.New(config.Project{})))) } func TestNoDockerWithoutImageName(t *testing.T) { require.True(t, pipe.IsSkip(Pipe{}.Run(context.New(config.Project{ Dockers: []config.Docker{ { Goos: "linux", }, }, })))) } func TestDockerNotInPath(t *testing.T) { var path = os.Getenv("PATH") defer func() { require.NoError(t, os.Setenv("PATH", path)) }() require.NoError(t, os.Setenv("PATH", "")) var ctx = &context.Context{ Version: "1.0.0", Config: config.Project{ Dockers: []config.Docker{ { ImageTemplates: []string{"a/b"}, }, }, }, } require.EqualError(t, Pipe{}.Run(ctx), ErrNoDocker.Error()) } func TestDefault(t *testing.T) { var ctx = &context.Context{ Config: config.Project{ Builds: []config.Build{ { Binary: "foo", }, }, Dockers: []config.Docker{ {}, }, }, } require.NoError(t, Pipe{}.Default(ctx)) require.Len(t, ctx.Config.Dockers, 1) var docker = ctx.Config.Dockers[0] require.Equal(t, "linux", docker.Goos) require.Equal(t, "amd64", docker.Goarch) require.Equal(t, []string{ctx.Config.Builds[0].Binary}, docker.Binaries) require.Empty(t, docker.Builds) } func TestDefaultDockerfile(t *testing.T) { var ctx = &context.Context{ Config: config.Project{ Builds: []config.Build{ {}, }, Dockers: []config.Docker{ {}, {}, }, }, } require.NoError(t, Pipe{}.Default(ctx)) require.Len(t, ctx.Config.Dockers, 2) require.Equal(t, "Dockerfile", ctx.Config.Dockers[0].Dockerfile) require.Equal(t, "Dockerfile", ctx.Config.Dockers[1].Dockerfile) } func TestDefaultBinaries(t *testing.T) { var ctx = &context.Context{ Config: config.Project{ Builds: []config.Build{ { ID: "foo", }, }, Dockers: []config.Docker{ { Binaries: []string{"foo"}, }, }, }, } require.NoError(t, Pipe{}.Default(ctx)) require.Len(t, ctx.Config.Dockers, 1) var docker = ctx.Config.Dockers[0] require.Equal(t, "linux", docker.Goos) require.Equal(t, "amd64", docker.Goarch) require.Equal(t, []string{"foo"}, docker.Binaries) } func TestDefaultNoDockers(t *testing.T) { var ctx = &context.Context{ Config: config.Project{ Dockers: []config.Docker{}, }, } require.NoError(t, Pipe{}.Default(ctx)) require.Empty(t, ctx.Config.Dockers) } func TestDefaultFilesDot(t *testing.T) { var ctx = &context.Context{ Config: config.Project{ Dist: "/tmp/distt", Dockers: []config.Docker{ { Files: []string{"./lala", "./lolsob", "."}, }, }, }, } require.EqualError(t, Pipe{}.Default(ctx), `invalid docker.files: can't be . or inside dist folder: .`) } func TestDefaultFilesDis(t *testing.T) { var ctx = &context.Context{ Config: config.Project{ Dist: "/tmp/dist", Dockers: []config.Docker{ { Files: []string{"./fooo", "/tmp/dist/asdasd/asd", "./bar"}, }, }, }, } require.EqualError(t, Pipe{}.Default(ctx), `invalid docker.files: can't be . or inside dist folder: /tmp/dist/asdasd/asd`) } func TestDefaultSet(t *testing.T) { var ctx = &context.Context{ Config: config.Project{ Dockers: []config.Docker{ { Builds: []string{"foo"}, Goos: "windows", Goarch: "i386", Binaries: []string{"bar"}, Dockerfile: "Dockerfile.foo", }, }, }, } require.NoError(t, Pipe{}.Default(ctx)) require.Len(t, ctx.Config.Dockers, 1) var docker = ctx.Config.Dockers[0] require.Equal(t, "windows", docker.Goos) require.Equal(t, "i386", docker.Goarch) require.Equal(t, "bar", docker.Binaries[0]) require.Equal(t, "foo", docker.Builds[0]) require.Equal(t, "Dockerfile.foo", docker.Dockerfile) } func Test_processImageTemplates(t *testing.T) { var ctx = &context.Context{ Config: config.Project{ Builds: []config.Build{ { ID: "default", }, }, Dockers: []config.Docker{ { Binaries: []string{"foo"}, Dockerfile: "Dockerfile.foo", ImageTemplates: []string{ "user/image:{{.Tag}}", "gcr.io/image:{{.Tag}}-{{.Env.FOO}}", "gcr.io/image:v{{.Major}}.{{.Minor}}", }, SkipPush: "true", }, }, }, } ctx.SkipPublish = true ctx.Env = map[string]string{ "FOO": "123", } ctx.Version = "1.0.0" ctx.Git = context.GitInfo{ CurrentTag: "v1.0.0", Commit: "a1b2c3d4", } ctx.Semver = context.Semver{ Major: 1, Minor: 0, Patch: 0, } require.NoError(t, Pipe{}.Default(ctx)) require.Len(t, ctx.Config.Dockers, 1) docker := ctx.Config.Dockers[0] require.Equal(t, "Dockerfile.foo", docker.Dockerfile) images, err := processImageTemplates(ctx, docker) require.NoError(t, err) require.Equal(t, []string{ "user/image:v1.0.0", "gcr.io/image:v1.0.0-123", "gcr.io/image:v1.0", }, images) } func TestLinkFile(t *testing.T) { src, err := ioutil.TempFile(t.TempDir(), "src") require.NoError(t, err) require.NoError(t, src.Close()) dst := filepath.Join(filepath.Dir(src.Name()), "dst") t.Cleanup(func() { os.Remove(src.Name()) os.Remove(dst) }) fmt.Println("src:", src.Name()) fmt.Println("dst:", dst) require.NoError(t, ioutil.WriteFile(src.Name(), []byte("foo"), 0644)) require.NoError(t, link(src.Name(), dst)) require.Equal(t, inode(src.Name()), inode(dst)) } func TestLinkDirectory(t *testing.T) { var srcDir = t.TempDir() var dstDir = t.TempDir() const testFile = "test" require.NoError(t, ioutil.WriteFile(filepath.Join(srcDir, testFile), []byte("foo"), 0644)) require.NoError(t, link(srcDir, dstDir)) require.Equal(t, inode(filepath.Join(srcDir, testFile)), inode(filepath.Join(dstDir, testFile))) } func TestLinkTwoLevelDirectory(t *testing.T) { var srcDir = t.TempDir() var dstDir = t.TempDir() var srcLevel2 = filepath.Join(srcDir, "level2") const testFile = "test" require.NoError(t, os.Mkdir(srcLevel2, 0755)) require.NoError(t, ioutil.WriteFile(filepath.Join(srcDir, testFile), []byte("foo"), 0644)) require.NoError(t, ioutil.WriteFile(filepath.Join(srcLevel2, testFile), []byte("foo"), 0644)) require.NoError(t, link(srcDir, dstDir)) require.Equal(t, inode(filepath.Join(srcDir, testFile)), inode(filepath.Join(dstDir, testFile))) require.Equal(t, inode(filepath.Join(srcLevel2, testFile)), inode(filepath.Join(dstDir, "level2", testFile))) } func inode(file string) uint64 { fileInfo, err := os.Stat(file) if err != nil { return 0 } stat := fileInfo.Sys().(*syscall.Stat_t) return stat.Ino }
[ "\"PATH\"" ]
[]
[ "PATH" ]
[]
["PATH"]
go
1
0
test_app/settings.py
# The most basic of settings to get the app to run as an example, should *never* be used in a # production environment. import os import dj_database_url DATABASES = {} db_url = os.environ.get('DATABASE_URL', '') if db_url: DATABASES['default'] = dj_database_url.parse(db_url, conn_max_age=600, ssl_require=True) else: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dr.sqlite3', } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.messages', 'keybase_proofs', 'test_app', ) DEBUG = True ALLOWED_HOSTS = ['*'] SECRET_KEY = '_' SITE_ID = 1 ROOT_URLCONF = 'test_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], 'loaders': [ 'django.template.loaders.app_directories.Loader', ], }, }, ] MIDDLEWARE = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Must match the `domain` set in the config. KEYBASE_PROOFS_DOMAIN = '<your-domain.com>'
[]
[]
[ "DATABASE_URL" ]
[]
["DATABASE_URL"]
python
1
0
app/utils/seedCrashes.py
from werkzeug.security import generate_password_hash from pymongo import MongoClient from pymongo.errors import DuplicateKeyError import os data =[ {"impactAngle":-341.54339233899367,"_id":20175, "user": "Robert", "date": "10/03/2019", "car": "Volvo S90"}, {"impactAngle":-32.74137379765352,"_id":1171, "user": "Robert", "date": "27/05/2018", "car": "Volvo V40"}, {"impactAngle":-308.3000606298933,"_id":20387, "user": "Michelle", "date": "04/11/2017", "car": "Volvo XC40"}, {"impactAngle":-84.77214151730084,"_id":20209, "user": "John", "date": "31/07/2017", "car": "Volvo XC90"}, {"impactAngle":-159.1955345095375,"_id":1690, "user": "Johnny", "date": "1/02/2016", "car": "Volvo V90"}, {"impactAngle":-8.4255066323192,"_id":5558, "user": "Robert", "date": "30/10/2015", "car": "Volvo S90"}, {"impactAngle":294.56235398164944,"_id":20358, "user": "Johnny", "date": "15/10/2015", "car": "Volvo XC60"}, {"impactAngle":-260.5895797216587,"_id":5512, "user": "Michelle", "date": "23/08/2015", "car": "Volvo S60"} ] def main(isOwner): # Connect to the DB mongo_uri = os.environ.get("MONGODB_URI", "mongodb://heroku_xv3vfwld:[email protected]:19380/heroku_xv3vfwld") client = MongoClient(mongo_uri) db = client['heroku_xv3vfwld'] collection = db['crashes'] # Ask for data to store pass_hash = generate_password_hash(password, method='pbkdf2:sha256') # Insert the user in the DB try: collection.insert({"_id": user, "password": pass_hash, "owner": isOwner}) print ("User created.") except DuplicateKeyError: print ("User already present in DB.") if __name__ == '__main__': ans = input('Introduce owners? y|n').lower() isOwner = ans == 'y' or ans == 'yes' while True: main(isOwner)
[]
[]
[ "MONGODB_URI" ]
[]
["MONGODB_URI"]
python
1
0
torch/testing/_internal/common_utils.py
r"""Importing this file must **not** initialize CUDA context. test_distributed relies on this assumption to properly run. This means that when this is imported no CUDA calls shall be made, including torch.cuda.device_count(), etc. torch.testing._internal.common_cuda.py can freely initialize CUDA context when imported. """ import sys import os import platform import re import gc import types from functools import partial import inspect import io import argparse import unittest import warnings import random import contextlib import socket import subprocess import time from collections import OrderedDict from contextlib import contextmanager from functools import wraps from itertools import product from copy import deepcopy from numbers import Number import tempfile import json from urllib.request import urlopen import __main__ import errno from typing import cast, Any, Iterable, Optional from torch.testing._internal import expecttest from torch.testing import _compare_tensors_internal, _compare_scalars_internal, _compare_return_type import torch import torch.cuda from torch._utils_internal import get_writable_path from torch._six import string_classes import torch.backends.cudnn import torch.backends.mkl from enum import Enum from torch.autograd import gradcheck from torch.autograd.gradcheck import gradgradcheck torch.backends.disable_global_flags() IS_SANDCASTLE = os.getenv('SANDCASTLE') == '1' or os.getenv('TW_JOB_USER') == 'sandcastle' class ProfilingMode(Enum): LEGACY = 1 SIMPLE = 2 PROFILING = 3 def cppProfilingFlagsToProfilingMode(): old_prof_exec_state = torch._C._jit_set_profiling_executor(True) old_prof_mode_state = torch._C._jit_set_profiling_mode(True) torch._C._jit_set_profiling_executor(old_prof_exec_state) torch._C._jit_set_profiling_mode(old_prof_mode_state) if old_prof_exec_state: if old_prof_mode_state: return ProfilingMode.PROFILING else: return ProfilingMode.SIMPLE else: return ProfilingMode.LEGACY @contextmanager def enable_profiling_mode_for_profiling_tests(): if GRAPH_EXECUTOR == ProfilingMode.PROFILING: old_prof_exec_state = torch._C._jit_set_profiling_executor(True) old_prof_mode_state = torch._C._jit_set_profiling_mode(True) try: yield finally: if GRAPH_EXECUTOR == ProfilingMode.PROFILING: torch._C._jit_set_profiling_executor(old_prof_exec_state) torch._C._jit_set_profiling_mode(old_prof_mode_state) @contextmanager def enable_profiling_mode(): old_prof_exec_state = torch._C._jit_set_profiling_executor(True) old_prof_mode_state = torch._C._jit_set_profiling_mode(True) try: yield finally: torch._C._jit_set_profiling_executor(old_prof_exec_state) torch._C._jit_set_profiling_mode(old_prof_mode_state) @contextmanager def num_profiled_runs(num_runs): old_num_runs = torch._C._jit_set_num_profiled_runs(num_runs) try: yield finally: torch._C._jit_set_num_profiled_runs(old_num_runs) func_call = torch._C.ScriptFunction.__call__ meth_call = torch._C.ScriptMethod.__call__ def prof_callable(callable, *args, **kwargs): if 'profile_and_replay' in kwargs: del kwargs['profile_and_replay'] if GRAPH_EXECUTOR == ProfilingMode.PROFILING: with enable_profiling_mode_for_profiling_tests(): callable(*args, **kwargs) return callable(*args, **kwargs) return callable(*args, **kwargs) def prof_func_call(*args, **kwargs): return prof_callable(func_call, *args, **kwargs) def prof_meth_call(*args, **kwargs): return prof_callable(meth_call, *args, **kwargs) torch._C.ScriptFunction.__call__ = prof_func_call torch._C.ScriptMethod.__call__ = prof_meth_call def _get_test_report_path(): # allow users to override the test file location. We need this # because the distributed tests run the same test file multiple # times with different configurations. override = os.environ.get('TEST_REPORT_SOURCE_OVERRIDE') test_source = override if override is not None else 'python-unittest' return os.path.join('test-reports', test_source) parser = argparse.ArgumentParser(add_help=False) parser.add_argument('--subprocess', action='store_true', help='whether to run each test in a subprocess') parser.add_argument('--seed', type=int, default=1234) parser.add_argument('--accept', action='store_true') parser.add_argument('--ge_config', type=str) parser.add_argument('--repeat', type=int, default=1) parser.add_argument('--test_bailouts', action='store_true') parser.add_argument('--save-xml', nargs='?', type=str, const=_get_test_report_path(), default=_get_test_report_path() if bool(os.environ.get('IN_CIRCLECI')) else None) parser.add_argument('--discover-tests', action='store_true') parser.add_argument('--log-suffix', type=str, default="") parser.add_argument('--run-parallel', type=int, default=1) args, remaining = parser.parse_known_args() if args.ge_config == 'legacy': GRAPH_EXECUTOR = ProfilingMode.LEGACY elif args.ge_config == 'profiling': GRAPH_EXECUTOR = ProfilingMode.PROFILING elif args.ge_config == 'simple': GRAPH_EXECUTOR = ProfilingMode.SIMPLE else: # infer flags based on the default settings GRAPH_EXECUTOR = cppProfilingFlagsToProfilingMode() LOG_SUFFIX = args.log_suffix RUN_PARALLEL = args.run_parallel TEST_BAILOUTS = args.test_bailouts TEST_DISCOVER = args.discover_tests TEST_IN_SUBPROCESS = args.subprocess TEST_SAVE_XML = args.save_xml REPEAT_COUNT = args.repeat SEED = args.seed if not expecttest.ACCEPT: expecttest.ACCEPT = args.accept UNITTEST_ARGS = [sys.argv[0]] + remaining torch.manual_seed(SEED) def wait_for_process(p): try: return p.wait() except KeyboardInterrupt: # Give `p` a chance to handle KeyboardInterrupt. Without this, # `pytest` can't print errors it collected so far upon KeyboardInterrupt. exit_status = p.wait(timeout=5) if exit_status is not None: return exit_status else: p.kill() raise except: # noqa E722, copied from python core library p.kill() raise finally: # Always call p.wait() to ensure exit p.wait() def shell(command, cwd=None, env=None): sys.stdout.flush() sys.stderr.flush() # The following cool snippet is copied from Py3 core library subprocess.call # only the with # 1. `except KeyboardInterrupt` block added for SIGINT handling. # 2. In Py2, subprocess.Popen doesn't return a context manager, so we do # `p.wait()` in a `final` block for the code to be portable. # # https://github.com/python/cpython/blob/71b6c1af727fbe13525fb734568057d78cea33f3/Lib/subprocess.py#L309-L323 assert not isinstance(command, torch._six.string_classes), "Command to shell should be a list or tuple of tokens" p = subprocess.Popen(command, universal_newlines=True, cwd=cwd, env=env) return wait_for_process(p) # Used to run the same test with different tensor types def repeat_test_for_types(dtypes): def repeat_helper(f): @wraps(f) def call_helper(self, *args): for dtype in dtypes: with TestCase.subTest(self, dtype=dtype): f(self, *args, dtype=dtype) return call_helper return repeat_helper # Environment variable `IS_PYTORCH_CI` is set in `.jenkins/common.sh`. IS_PYTORCH_CI = bool(os.environ.get('IS_PYTORCH_CI')) def discover_test_cases_recursively(suite_or_case): if isinstance(suite_or_case, unittest.TestCase): return [suite_or_case] rc = [] for element in suite_or_case: rc.extend(discover_test_cases_recursively(element)) return rc def get_test_names(test_cases): return ['.'.join(case.id().split('.')[-2:]) for case in test_cases] def chunk_list(lst, nchunks): return [lst[i::nchunks] for i in range(nchunks)] def run_tests(argv=UNITTEST_ARGS): if TEST_DISCOVER: suite = unittest.TestLoader().loadTestsFromModule(__main__) test_cases = discover_test_cases_recursively(suite) for name in get_test_names(test_cases): print(name) elif TEST_IN_SUBPROCESS: suite = unittest.TestLoader().loadTestsFromModule(__main__) test_cases = discover_test_cases_recursively(suite) failed_tests = [] for case in test_cases: test_case_full_name = case.id().split('.', 1)[1] exitcode = shell([sys.executable] + argv + [test_case_full_name]) if exitcode != 0: failed_tests.append(test_case_full_name) assert len(failed_tests) == 0, "{} unit test(s) failed:\n\t{}".format( len(failed_tests), '\n\t'.join(failed_tests)) elif RUN_PARALLEL > 1: suite = unittest.TestLoader().loadTestsFromModule(__main__) test_cases = discover_test_cases_recursively(suite) test_batches = chunk_list(get_test_names(test_cases), RUN_PARALLEL) processes = [] for i in range(RUN_PARALLEL): command = [sys.executable] + argv + ['--log-suffix=-shard-{}'.format(i + 1)] + test_batches[i] processes.append(subprocess.Popen(command, universal_newlines=True)) failed = False for p in processes: failed |= wait_for_process(p) != 0 assert not failed, "Some test shards have failed" elif TEST_SAVE_XML is not None: # import here so that non-CI doesn't need xmlrunner installed import xmlrunner test_report_path = TEST_SAVE_XML + LOG_SUFFIX os.makedirs(test_report_path, exist_ok=True) verbose = '--verbose' in argv or '-v' in argv if verbose: print('Test results will be stored in {}'.format(test_report_path)) unittest.main(argv=argv, testRunner=xmlrunner.XMLTestRunner(output=test_report_path, verbosity=2 if verbose else 1)) elif REPEAT_COUNT > 1: for _ in range(REPEAT_COUNT): if not unittest.main(exit=False, argv=argv).result.wasSuccessful(): sys.exit(-1) else: unittest.main(argv=argv) IS_WINDOWS = sys.platform == "win32" IS_MACOS = sys.platform == "darwin" IS_PPC = platform.machine() == "ppc64le" if IS_WINDOWS: @contextmanager def TemporaryFileName(): # Ideally we would like to not have to manually delete the file, but NamedTemporaryFile # opens the file, and it cannot be opened multiple times in Windows. To support Windows, # close the file after creation and try to remove it manually f = tempfile.NamedTemporaryFile(delete=False) try: f.close() yield f.name finally: os.unlink(f.name) else: @contextmanager # noqa: T484 def TemporaryFileName(): with tempfile.NamedTemporaryFile() as f: yield f.name def _check_module_exists(name): r"""Returns if a top-level module with :attr:`name` exists *without** importing it. This is generally safer than try-catch block around a `import X`. It avoids third party libraries breaking assumptions of some of our tests, e.g., setting multiprocessing start method when imported (see librosa/#747, torchvision/#544). """ import importlib import importlib.util spec = importlib.util.find_spec(name) return spec is not None TEST_NUMPY = _check_module_exists('numpy') TEST_SCIPY = _check_module_exists('scipy') TEST_MKL = torch.backends.mkl.is_available() TEST_NUMBA = _check_module_exists('numba') TEST_DILL = _check_module_exists('dill') TEST_LIBROSA = _check_module_exists('librosa') # Python 2.7 doesn't have spawn NO_MULTIPROCESSING_SPAWN = os.environ.get('NO_MULTIPROCESSING_SPAWN', '0') == '1' TEST_WITH_ASAN = os.getenv('PYTORCH_TEST_WITH_ASAN', '0') == '1' TEST_WITH_TSAN = os.getenv('PYTORCH_TEST_WITH_TSAN', '0') == '1' TEST_WITH_UBSAN = os.getenv('PYTORCH_TEST_WITH_UBSAN', '0') == '1' TEST_WITH_ROCM = os.getenv('PYTORCH_TEST_WITH_ROCM', '0') == '1' # Enables tests that are slow to run (disabled by default) TEST_WITH_SLOW = os.getenv('PYTORCH_TEST_WITH_SLOW', '0') == '1' # Disables non-slow tests (these tests enabled by default) # This is usually used in conjunction with TEST_WITH_SLOW to # run *only* slow tests. (I could have done an enum, but # it felt a little awkward. TEST_SKIP_FAST = os.getenv('PYTORCH_TEST_SKIP_FAST', '0') == '1' if TEST_NUMPY: import numpy as np # Dict of NumPy dtype -> torch dtype (when the correspondence exists) numpy_to_torch_dtype_dict = { np.bool : torch.bool, np.uint8 : torch.uint8, np.int8 : torch.int8, np.int16 : torch.int16, np.int32 : torch.int32, np.int64 : torch.int64, np.float16 : torch.float16, np.float32 : torch.float32, np.float64 : torch.float64, np.complex64 : torch.complex64, np.complex128 : torch.complex128 } # Dict of torch dtype -> NumPy dtype torch_to_numpy_dtype_dict = {value : key for (key, value) in numpy_to_torch_dtype_dict.items()} ALL_TENSORTYPES = [torch.float, torch.double, torch.half] # bfloat16 bringup is currently only available on ROCm # ALL_TENSORTYPES2 will eventually be unified with ALL_TENSORTYPES # when bfloat16 bringup is complete on all platforms if TEST_WITH_ROCM: ALL_TENSORTYPES2 = [torch.float, torch.double, torch.half, torch.bfloat16] else: ALL_TENSORTYPES2 = ALL_TENSORTYPES def skipIfRocm(fn): @wraps(fn) def wrapper(*args, **kwargs): if TEST_WITH_ROCM: raise unittest.SkipTest("test doesn't currently work on the ROCm stack") else: fn(*args, **kwargs) return wrapper def skipIfCompiledWithoutNumpy(fn): # Even if the numpy module is present, if `USE_NUMPY=0` is used during the # build, numpy tests will fail numpy_support = TEST_NUMPY if numpy_support: try: # The numpy module is present, verify that PyTorch is compiled with # numpy support torch.from_numpy(np.array([2, 2])) except RuntimeError: numpy_support = False @wraps(fn) def wrapper(*args, **kwargs): if not numpy_support: raise unittest.SkipTest("PyTorch was compiled without numpy support") else: fn(*args, **kwargs) return wrapper def _test_function(fn, device): def run_test_function(self): return fn(self, device) return run_test_function def skipIfNoLapack(fn): @wraps(fn) def wrapper(*args, **kwargs): if not torch._C.has_lapack: raise unittest.SkipTest('PyTorch compiled without Lapack') else: fn(*args, **kwargs) return wrapper def skipIfNotRegistered(op_name, message): """Wraps the decorator to hide the import of the `core`. Args: op_name: Check if this op is registered in `core._REGISTERED_OPERATORS`. message: message to fail with. Usage: @skipIfNotRegistered('MyOp', 'MyOp is not linked!') This will check if 'MyOp' is in the caffe2.python.core """ try: from caffe2.python import core skipper = unittest.skipIf(op_name not in core._REGISTERED_OPERATORS, message) except ImportError: skipper = unittest.skip("Cannot import `caffe2.python.core`") return skipper def skipIfNoSciPy(fn): @wraps(fn) def wrapper(*args, **kwargs): if not TEST_SCIPY: raise unittest.SkipTest("test require SciPy, but SciPy not found") else: fn(*args, **kwargs) return wrapper def slowTest(fn): @wraps(fn) def wrapper(*args, **kwargs): if not TEST_WITH_SLOW: raise unittest.SkipTest("test is slow; run with PYTORCH_TEST_WITH_SLOW to enable test") else: fn(*args, **kwargs) wrapper.__dict__['slow_test'] = True return wrapper def skipCUDAMemoryLeakCheckIf(condition): def dec(fn): if getattr(fn, '_do_cuda_memory_leak_check', True): # if current True fn._do_cuda_memory_leak_check = not condition return fn return dec def skipCUDANonDefaultStreamIf(condition): def dec(fn): if getattr(fn, '_do_cuda_non_default_stream', True): # if current True fn._do_cuda_non_default_stream = not condition return fn return dec def suppress_warnings(fn): @wraps(fn) def wrapper(*args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") fn(*args, **kwargs) return wrapper def get_cpu_type(type_name): module, name = type_name.rsplit('.', 1) assert module == 'torch.cuda' return getattr(torch, name) def get_gpu_type(type_name): if isinstance(type_name, type): type_name = '{}.{}'.format(type_name.__module__, type_name.__name__) module, name = type_name.rsplit('.', 1) assert module == 'torch' return getattr(torch.cuda, name) def to_gpu(obj, type_map=None): if type_map is None: type_map = {} if isinstance(obj, torch.Tensor): assert obj.is_leaf t = type_map.get(obj.type(), get_gpu_type(obj.type())) with torch.no_grad(): res = obj.clone().type(t) res.requires_grad = obj.requires_grad return res elif torch.is_storage(obj): return obj.new().resize_(obj.size()).copy_(obj) elif isinstance(obj, list): return [to_gpu(o, type_map) for o in obj] elif isinstance(obj, tuple): return tuple(to_gpu(o, type_map) for o in obj) else: return deepcopy(obj) def get_function_arglist(func): return inspect.getfullargspec(func).args def set_rng_seed(seed): torch.manual_seed(seed) random.seed(seed) if TEST_NUMPY: np.random.seed(seed) @contextlib.contextmanager def freeze_rng_state(): rng_state = torch.get_rng_state() if torch.cuda.is_available(): cuda_rng_state = torch.cuda.get_rng_state() yield if torch.cuda.is_available(): torch.cuda.set_rng_state(cuda_rng_state) torch.set_rng_state(rng_state) @contextlib.contextmanager def set_default_dtype(dtype): saved_dtype = torch.get_default_dtype() torch.set_default_dtype(dtype) yield torch.set_default_dtype(saved_dtype) def iter_indices(tensor): if tensor.dim() == 0: return range(0) if tensor.dim() == 1: return range(tensor.size(0)) return product(*(range(s) for s in tensor.size())) def is_iterable(obj): try: iter(obj) return True except TypeError: return False class CudaNonDefaultStream(): def __enter__(self): # Before starting CUDA test save currently active streams on all # CUDA devices and set new non default streams to all CUDA devices # to ensure CUDA tests do not use default stream by mistake. beforeDevice = torch.cuda.current_device() self.beforeStreams = [] for d in range(torch.cuda.device_count()): self.beforeStreams.append(torch.cuda.current_stream(d)) deviceStream = torch.cuda.Stream(device=d) torch._C._cuda_setStream(deviceStream._cdata) torch._C._cuda_setDevice(beforeDevice) def __exit__(self, exec_type, exec_value, traceback): # After completing CUDA test load previously active streams on all # CUDA devices. beforeDevice = torch.cuda.current_device() for d in range(torch.cuda.device_count()): torch._C._cuda_setStream(self.beforeStreams[d]._cdata) torch._C._cuda_setDevice(beforeDevice) class CudaMemoryLeakCheck(): def __init__(self, testcase, name=None): self.name = testcase.id() if name is None else name self.testcase = testcase # initialize context & RNG to prevent false positive detections # when the test is the first to initialize those from torch.testing._internal.common_cuda import initialize_cuda_context_rng initialize_cuda_context_rng() @staticmethod def get_cuda_memory_usage(): # we don't need CUDA synchronize because the statistics are not tracked at # actual freeing, but at when marking the block as free. num_devices = torch.cuda.device_count() gc.collect() return tuple(torch.cuda.memory_allocated(i) for i in range(num_devices)) def __enter__(self): self.befores = self.get_cuda_memory_usage() def __exit__(self, exec_type, exec_value, traceback): # Don't check for leaks if an exception was thrown if exec_type is not None: return afters = self.get_cuda_memory_usage() for i, (before, after) in enumerate(zip(self.befores, afters)): self.testcase.assertEqual( before, after, msg='{} leaked {} bytes CUDA memory on device {}'.format( self.name, after - before, i)) # "min_satisfying_examples" setting has been deprecated in hypythesis # 3.56.0 and removed in hypothesis 4.x try: import hypothesis def settings(*args, **kwargs): if 'min_satisfying_examples' in kwargs and hypothesis.version.__version_info__ >= (3, 56, 0): kwargs.pop('min_satisfying_examples') return hypothesis.settings(*args, **kwargs) hypothesis.settings.register_profile( "pytorch_ci", settings( derandomize=True, suppress_health_check=[hypothesis.HealthCheck.too_slow], database=None, max_examples=100, verbosity=hypothesis.Verbosity.normal)) hypothesis.settings.register_profile( "dev", settings( suppress_health_check=[hypothesis.HealthCheck.too_slow], database=None, max_examples=10, verbosity=hypothesis.Verbosity.normal)) hypothesis.settings.register_profile( "debug", settings( suppress_health_check=[hypothesis.HealthCheck.too_slow], database=None, max_examples=1000, verbosity=hypothesis.Verbosity.verbose)) hypothesis.settings.load_profile( "pytorch_ci" if IS_PYTORCH_CI else os.getenv('PYTORCH_HYPOTHESIS_PROFILE', 'dev') ) except ImportError: print('Fail to import hypothesis in common_utils, tests are not derandomized') disabled_test_from_issues = None def check_disabled(test_name): global disabled_test_from_issues if disabled_test_from_issues is None: disabled_test_from_issues = {} def read_and_process(): url = 'https://raw.githubusercontent.com/zdevito/pytorch_disabled_tests/master/result.json' contents = urlopen(url, timeout=1).read().decode('utf-8') the_response = json.loads(contents) for item in the_response['items']: title = item['title'] key = 'DISABLED ' if title.startswith(key): test_name = title[len(key):].strip() disabled_test_from_issues[test_name] = item['html_url'] if not IS_SANDCASTLE and os.getenv("PYTORCH_RUN_DISABLED_TESTS", "0") != "1": try: read_and_process() except Exception: print("Couldn't download test skip set, leaving all tests enabled...") if test_name in disabled_test_from_issues: raise unittest.SkipTest( "Test is disabled because an issue exists disabling it: {}".format(disabled_test_from_issues[test_name]) + " To enable set the environment variable PYTORCH_RUN_DISABLED_TESTS=1") # Acquires the comparison dtype, required since isclose # requires both inputs have the same dtype, and isclose is not supported # for some device x dtype combinations. # NOTE: Remaps bfloat16 to float32 since neither the CPU or CUDA device types # support needed bfloat16 comparison methods. # NOTE: Remaps float16 to float32 on CPU since the CPU device type doesn't # support needed float16 comparison methods. # TODO: Update this once bfloat16 and float16 are better supported. def get_comparison_dtype(a, b): # TODO: update this when promote_types supports bfloat16 and/or # isclose supports bfloat16. a_dtype = torch.float32 if a.dtype is torch.bfloat16 else a.dtype b_dtype = torch.float32 if b.dtype is torch.bfloat16 else b.dtype compare_dtype = torch.promote_types(a_dtype, b_dtype) # non-CUDA (CPU, for example) float16 -> float32 # TODO: update this when isclose is implemented for CPU float16 if (compare_dtype is torch.float16 and (a.device != b.device or a.device.type != 'cuda' or b.device.type != 'cuda')): compare_dtype = torch.float32 return compare_dtype class TestCase(expecttest.TestCase): # NOTE: "precision" lets classes and generated tests set minimum # atol values when comparing tensors. Used by @precisionOverride, for # example. # TODO: provide a better mechanism for generated tests to set rtol/atol. _precision: float = 0 @property def precision(self) -> float: return self._precision @precision.setter def precision(self, prec: float) -> None: self._precision = prec _do_cuda_memory_leak_check = False _do_cuda_non_default_stream = False def __init__(self, method_name='runTest'): super().__init__(method_name) test_method = getattr(self, method_name, None) if test_method is not None: # Wraps the tested method if we should do CUDA memory check. self._do_cuda_memory_leak_check &= getattr(test_method, '_do_cuda_memory_leak_check', True) # FIXME: figure out the flaky -1024 anti-leaks on windows. See #8044 if self._do_cuda_memory_leak_check and not IS_WINDOWS: self.wrap_with_cuda_policy(method_name, self.assertLeaksNoCudaTensors) # Wraps the tested method if we should enforce non default CUDA stream. self._do_cuda_non_default_stream &= getattr(test_method, '_do_cuda_non_default_stream', True) if self._do_cuda_non_default_stream and not IS_WINDOWS and not TEST_WITH_ROCM: self.wrap_with_cuda_policy(method_name, self.enforceNonDefaultStream) def assertLeaksNoCudaTensors(self, name=None): name = self.id() if name is None else name return CudaMemoryLeakCheck(self, name) def enforceNonDefaultStream(self): return CudaNonDefaultStream() def wrap_with_cuda_policy(self, method_name, policy): test_method = getattr(self, method_name) # the import below may initialize CUDA context, so we do it only if # self._do_cuda_memory_leak_check or self._do_cuda_non_default_stream # is True. from torch.testing._internal.common_cuda import TEST_CUDA fullname = self.id().lower() # class_name.method_name if TEST_CUDA and ('gpu' in fullname or 'cuda' in fullname): setattr(self, method_name, self.wrap_method_with_cuda_policy(test_method, policy)) def wrap_method_with_cuda_policy(self, method, policy): # Assumes that `method` is the tested function in `self`. # NOTE: Python Exceptions (e.g., unittest.Skip) keeps objects in scope # alive, so this cannot be done in setUp and tearDown because # tearDown is run unconditionally no matter whether the test # passes or not. For the same reason, we can't wrap the `method` # call in try-finally and always do the check. @wraps(method) def wrapper(self, *args, **kwargs): with policy(): method(*args, **kwargs) return types.MethodType(wrapper, self) def wrap_with_cuda_memory_check(self, method): return self.wrap_method_with_cuda_policy(method, self.assertLeaksNoCudaTensors) def setUp(self): if TEST_SKIP_FAST: if not getattr(self, self._testMethodName).__dict__.get('slow_test', False): raise unittest.SkipTest("test is fast; we disabled it with PYTORCH_TEST_SKIP_FAST") check_disabled(str(self)) set_rng_seed(SEED) def genSparseTensor(self, size, sparse_dim, nnz, is_uncoalesced, device='cpu'): # Assert not given impossible combination, where the sparse dims have # empty numel, but nnz > 0 makes the indices containing values. assert all(size[d] > 0 for d in range(sparse_dim)) or nnz == 0, 'invalid arguments' v_size = [nnz] + list(size[sparse_dim:]) v = torch.randn(*v_size, device=device) i = torch.rand(sparse_dim, nnz, device=device) i.mul_(torch.tensor(size[:sparse_dim]).unsqueeze(1).to(i)) i = i.to(torch.long) if is_uncoalesced: v = torch.cat([v, torch.randn_like(v)], 0) i = torch.cat([i, i], 1) x = torch.sparse_coo_tensor(i, v, torch.Size(size)) if not is_uncoalesced: x = x.coalesce() else: # FIXME: `x` is a sparse view of `v`. Currently rebase_history for # sparse views is not implemented, so this workaround is # needed for inplace operations done on `x`, e.g., copy_(). # Remove after implementing something equivalent to CopySlice # for sparse views. # NOTE: We do clone() after detach() here because we need to be able to change size/storage of x afterwards x = x.detach().clone() return x, x._indices().clone(), x._values().clone() def safeToDense(self, t): r = self.safeCoalesce(t) return r.to_dense() def safeCoalesce(self, t): tc = t.coalesce() self.assertEqual(tc.to_dense(), t.to_dense()) self.assertTrue(tc.is_coalesced()) # Our code below doesn't work when nnz is 0, because # then it's a 0D tensor, not a 2D tensor. if t._nnz() == 0: self.assertEqual(t._indices(), tc._indices()) self.assertEqual(t._values(), tc._values()) return tc value_map = {} for idx, val in zip(t._indices().t(), t._values()): idx_tup = tuple(idx.tolist()) if idx_tup in value_map: value_map[idx_tup] += val else: value_map[idx_tup] = val.clone() if isinstance(val, torch.Tensor) else val new_indices = sorted(list(value_map.keys())) new_values = [value_map[idx] for idx in new_indices] if t._values().ndimension() < 2: new_values = t._values().new(new_values) else: new_values = torch.stack(new_values) new_indices = t._indices().new(new_indices).t() tg = t.new(new_indices, new_values, t.size()) self.assertEqual(tc._indices(), tg._indices()) self.assertEqual(tc._values(), tg._values()) if t.is_coalesced(): self.assertEqual(tc._indices(), t._indices()) self.assertEqual(tc._values(), t._values()) return tg # Compares the given Torch and NumPy functions on the given tensor-like object. # NOTE: both torch_fn and np_fn should be functions that take a single # tensor (array). If the torch and/or NumPy function require additional # arguments then wrap the function in a lambda or pass a partial function. # TODO: support bfloat16 comparisons # TODO: add args/kwargs for passing to assertEqual (e.g. rtol, atol) def compare_with_numpy(self, torch_fn, np_fn, tensor_like, device=None, dtype=None): assert TEST_NUMPY assert dtype is not torch.bfloat16 if isinstance(tensor_like, torch.Tensor): assert device is None assert dtype is None a = tensor_like.detach().cpu().numpy() t = tensor_like else: a = np.array(tensor_like, dtype=torch_to_numpy_dtype_dict[dtype]) t = torch.tensor(tensor_like, device=device, dtype=dtype) np_result = np_fn(a) torch_result = torch_fn(t).cpu() # Converts arrays to tensors if isinstance(np_result, np.ndarray): try: np_result = torch.from_numpy(np_result) except Exception: # NOTE: copying an array before conversion is necessary when, # for example, the array has negative strides. np_result = torch.from_numpy(np_result.copy()) self.assertEqual(np_result, torch_result) # Some analysis of tolerance by logging tests from test_torch.py can be found # in https://github.com/pytorch/pytorch/pull/32538. # dtype name : (rtol, atol) dtype_precisions = { torch.float16 : (0.001, 1e-5), torch.bfloat16 : (0.016, 1e-5), torch.float32 : (1.3e-6, 1e-5), torch.float64 : (1e-7, 1e-7), torch.complex32 : (0.001, 1e-5), torch.complex64 : (1.3e-6, 1e-5), torch.complex128 : (1e-7, 1e-7), } # Returns the "default" rtol and atol for comparing scalars or # tensors of the given dtypes. def _getDefaultRtolAndAtol(self, dtype0, dtype1): rtol = max(self.dtype_precisions.get(dtype0, (0, 0))[0], self.dtype_precisions.get(dtype1, (0, 0))[0]) atol = max(self.dtype_precisions.get(dtype0, (0, 0))[1], self.dtype_precisions.get(dtype1, (0, 0))[1]) return rtol, atol # Checks if two dense tensors are equal(-ish), returning (True, None) # when they are and (False, debug_msg) when they are not. # If exact_dtype is true both tensors must have the same dtype. # If exact_device is true both tensors must be on the same device. # See the "Test Framework Tensor 'Equality'" note for more details. # NOTE: tensors on different devices are moved to the CPU to be compared when # exact_device is False. # NOTE: this function checks the tensors' devices, sizes, and dtypes # and acquires the appropriate device, dtype, rtol and atol to compare # them with. It then calls _compare_tensors_internal. def _compareTensors(self, a, b, *, rtol: Optional[float] = None, atol=None, equal_nan=True, exact_dtype=True, exact_device=False) -> _compare_return_type: assert (atol is None) == (rtol is None) if not isinstance(a, torch.Tensor): return (False, "argument a, {0}, to _compareTensors is not a tensor!".format(a)) if not isinstance(b, torch.Tensor): return (False, "argument b, {0}, to _compareTensors is not a tensor!".format(b)) # Validates tensors are on the same device if exact_device and a.device != b.device: return (False, ("Attempted to compare equality of tensors on " "different devices! Got devices {0} and " "{1}.".format(a.device, b.device))) # Compares tensors of different devices on the CPU if a.device != b.device: a = a.cpu() b = b.cpu() # Checks size matches if a.size() != b.size(): return (False, ("Attempted to compare equality of tensors with " "different sizes. Got sizes {0} and {1}.").format(a.size(), b.size())) # Checks dtype (if exact_dtype) if exact_dtype and a.dtype is not b.dtype: return (False, ("Attempted to compare equality of tensors with " "different dtypes. Got dtypes {0} and {1}.").format(a.dtype, b.dtype)) # Acquires rtol and atol if rtol is None: rtol, atol = self._getDefaultRtolAndAtol(a.dtype, b.dtype) atol = max(atol, self.precision) # Converts to comparison dtype dtype = get_comparison_dtype(a, b) a = a.to(dtype) b = b.to(dtype) return _compare_tensors_internal(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan) # Checks if two scalars are equal(-ish), returning (True, None) # when they are and (False, debug_msg) when they are not. # NOTE: this function just acquires rtol and atol # before calling _compare_scalars_internal. def _compareScalars(self, a, b, *, rtol: Optional[float] = None, atol: Optional[float] = None, equal_nan=True) -> _compare_return_type: # Acquires rtol and atol assert (atol is None) == (rtol is None) if rtol is None: if isinstance(a, complex) or isinstance(b, complex): rtol, atol = self._getDefaultRtolAndAtol(torch.complex64, torch.complex64) elif isinstance(a, float) or isinstance(b, float): rtol, atol = self._getDefaultRtolAndAtol(torch.float32, torch.float32) else: rtol, atol = 0, 0 atol = max(atol, self.precision) return _compare_scalars_internal(a, b, rtol=cast(float, rtol), atol=cast(float, atol), equal_nan=equal_nan) def assertEqualIgnoreType(self, *args, **kwargs) -> None: # If you are seeing this function used, that means test is written wrongly # and deserves detailed investigation return self.assertEqual(*args, exact_dtype=False, **kwargs) # Compares x and y # TODO: default exact_device to True def assertEqual(self, x, y, msg: Optional[str] = None, *, atol: Optional[float] = None, rtol: Optional[float] = None, equal_nan=True, exact_dtype=True, exact_device=False) -> None: assert (atol is None) == (rtol is None), "If one of atol or rtol is specified the other must be, too" # Tensor x Number and Number x Tensor comparisons if isinstance(x, torch.Tensor) and isinstance(y, Number): self.assertEqual(x.item(), y, atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) elif isinstance(y, torch.Tensor) and isinstance(x, Number): self.assertEqual(x, y.item(), atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) # Tensor x np.bool elif isinstance(x, torch.Tensor) and isinstance(y, np.bool_): self.assertEqual(x.item(), y, atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) elif isinstance(y, torch.Tensor) and isinstance(x, np.bool_): self.assertEqual(x, y.item(), atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) # Tensor x Tensor elif isinstance(x, torch.Tensor) and isinstance(y, torch.Tensor): super().assertEqual(x.is_sparse, y.is_sparse, msg=msg) super().assertEqual(x.is_quantized, y.is_quantized, msg=msg) if x.is_sparse: x = self.safeCoalesce(x) y = self.safeCoalesce(y) indices_result, debug_msg = self._compareTensors(x._indices(), y._indices(), rtol=rtol, atol=atol, equal_nan=equal_nan, exact_dtype=exact_dtype, exact_device=exact_device) if not indices_result and msg is None: assert debug_msg is not None msg = "Sparse tensor indices failed to compare as equal! " + debug_msg self.assertTrue(indices_result, msg=msg) values_result, debug_msg = self._compareTensors(x._values(), y._values(), rtol=rtol, atol=atol, equal_nan=equal_nan, exact_dtype=exact_dtype, exact_device=exact_device) if not values_result and msg is None: assert debug_msg is not None msg = "Sparse tensor values failed to compare as equal! " + debug_msg self.assertTrue(values_result, msg=msg) elif x.is_quantized and y.is_quantized: self.assertEqual(x.qscheme(), y.qscheme(), atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) if x.qscheme() == torch.per_tensor_affine: self.assertEqual(x.q_scale(), y.q_scale(), atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) self.assertEqual(x.q_zero_point(), y.q_zero_point(), atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) elif x.qscheme() == torch.per_channel_affine: self.assertEqual(x.q_per_channel_scales(), y.q_per_channel_scales(), atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) self.assertEqual(x.q_per_channel_zero_points(), y.q_per_channel_zero_points(), atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) self.assertEqual(x.q_per_channel_axis(), y.q_per_channel_axis(), atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) result, debug_msg = self._compareTensors(x.int_repr().to(torch.int32), y.int_repr().to(torch.int32), atol=atol, rtol=rtol, exact_dtype=exact_dtype, exact_device=exact_device) if not result and msg is None: assert debug_msg is not None msg = "Quantized representations failed to compare as equal! " + debug_msg self.assertTrue(result, msg=msg) else: result, debug_msg = self._compareTensors(x, y, rtol=rtol, atol=atol, equal_nan=equal_nan, exact_dtype=exact_dtype, exact_device=exact_device) if not result and msg is None: assert debug_msg is not None msg = "Tensors failed to compare as equal! " + debug_msg self.assertTrue(result, msg=msg) elif isinstance(x, string_classes) and isinstance(y, string_classes): super().assertEqual(x, y, msg=msg) elif type(x) == set and type(y) == set: super().assertEqual(x, y, msg=msg) elif isinstance(x, dict) and isinstance(y, dict): if isinstance(x, OrderedDict) and isinstance(y, OrderedDict): self.assertEqual(x.items(), y.items(), atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) else: self.assertEqual(set(x.keys()), set(y.keys()), atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) key_list = list(x.keys()) self.assertEqual([x[k] for k in key_list], [y[k] for k in key_list], atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) elif isinstance(x, type) and isinstance(y, type): # See TestTorch.test_assert_equal_generic_meta super().assertEqual(x, y, msg=msg) elif is_iterable(x) and is_iterable(y): super().assertEqual(len(x), len(y), msg=msg) for x_, y_ in zip(x, y): self.assertEqual(x_, y_, atol=atol, rtol=rtol, msg=msg, exact_dtype=exact_dtype, exact_device=exact_device) elif isinstance(x, bool) and isinstance(y, bool): self.assertTrue(x == y, msg=msg) # Scalar x Scalar elif isinstance(x, Number) and isinstance(y, Number): result, debug_msg = self._compareScalars(x, y, rtol=rtol, atol=atol, equal_nan=equal_nan) if not result and msg is None: assert debug_msg is not None msg = "Scalars failed to compare as equal! " + debug_msg self.assertTrue(result, msg=msg) else: super().assertEqual(x, y, msg=msg) def assertAlmostEqual(self, x, y, *, places=None, msg=None, delta=None): prec = delta if places: prec = 10**(-places) rtol = None if prec is None else 0 self.assertEqual(x, y, msg=msg, atol=prec, rtol=rtol) def assertNotEqual(self, x, y, msg: Optional[str] = None, *, atol: Optional[float] = None, rtol: Optional[float] = None, **kwargs) -> None: with self.assertRaises(AssertionError, msg=msg): self.assertEqual(x, y, msg, atol=atol, rtol=rtol, **kwargs) def assertEqualTypeString(self, x, y) -> None: # This API is used simulate deprecated x.type() == y.type() self.assertEqual(x.device, y.device) self.assertEqual(x.dtype, y.dtype) self.assertEqual(x.is_sparse, y.is_sparse) def assertObjectIn(self, obj: Any, iterable: Iterable[Any]) -> None: for elem in iterable: if id(obj) == id(elem): return raise AssertionError("object not found in iterable") # TODO: Support context manager interface # NB: The kwargs forwarding to callable robs the 'subname' parameter. # If you need it, manually apply your callable in a lambda instead. def assertExpectedRaises(self, exc_type, callable, *args, **kwargs): subname = None if 'subname' in kwargs: subname = kwargs['subname'] del kwargs['subname'] try: callable(*args, **kwargs) except exc_type as e: self.assertExpected(str(e), subname) return # Don't put this in the try block; the AssertionError will catch it self.fail(msg="Did not raise when expected to") def assertNotWarn(self, callable, msg=''): r""" Test if :attr:`callable` does not raise a warning. """ with warnings.catch_warnings(record=True) as ws: warnings.simplefilter("always") # allow any warning to be raised callable() self.assertTrue(len(ws) == 0, msg) @contextmanager def maybeWarnsRegex(self, category, regex=''): """Context manager for code that *may* warn, e.g. ``TORCH_WARN_ONCE``. This filters expected warnings from the test log and fails the test if any unexpected warnings are caught. """ with warnings.catch_warnings(record=True) as ws: warnings.simplefilter("always") # allow any warning to be raised # Ignore expected warnings warnings.filterwarnings("ignore", message=regex, category=category) try: yield finally: if len(ws) != 0: msg = 'Caught unexpected warnings:\n' for w in ws: msg += warnings.formatwarning( w.message, w.category, w.filename, w.lineno, w.line) msg += '\n' self.fail(msg) def assertExpected(self, s, subname=None): r""" Test that a string matches the recorded contents of a file derived from the name of this test and subname. This file is placed in the 'expect' directory in the same directory as the test script. You can automatically update the recorded test output using --accept. If you call this multiple times in a single function, you must give a unique subname each time. """ if not isinstance(s, str): raise TypeError("assertExpected is strings only") def remove_prefix(text, prefix): if text.startswith(prefix): return text[len(prefix):] return text # NB: we take __file__ from the module that defined the test # class, so we place the expect directory where the test script # lives, NOT where test/common_utils.py lives. This doesn't matter in # PyTorch where all test scripts are in the same directory as # test/common_utils.py, but it matters in onnx-pytorch module_id = self.__class__.__module__ munged_id = remove_prefix(self.id(), module_id + ".") test_file = os.path.realpath(sys.modules[module_id].__file__) expected_file = os.path.join(os.path.dirname(test_file), "expect", munged_id) subname_output = "" if subname: expected_file += "-" + subname subname_output = " ({})".format(subname) expected_file += ".expect" expected = None def accept_output(update_type): print("Accepting {} for {}{}:\n\n{}".format(update_type, munged_id, subname_output, s)) with open(expected_file, 'w') as f: f.write(s) try: with open(expected_file) as f: expected = f.read() except IOError as e: if e.errno != errno.ENOENT: raise elif expecttest.ACCEPT: return accept_output("output") else: raise RuntimeError( ("I got this output for {}{}:\n\n{}\n\n" "No expect file exists; to accept the current output, run:\n" "python {} {} --accept").format(munged_id, subname_output, s, __main__.__file__, munged_id)) # a hack for JIT tests if IS_WINDOWS: expected = re.sub(r'CppOp\[(.+?)\]', 'CppOp[]', expected) s = re.sub(r'CppOp\[(.+?)\]', 'CppOp[]', s) # Adjust for producer_version expected = expected.replace( 'producer_version: "XXX"', 'producer_version: "{}"'.format(torch.onnx.producer_version) ) if expecttest.ACCEPT: if expected != s: return accept_output("updated output") else: if hasattr(self, "assertMultiLineEqual"): # Python 2.7 only # NB: Python considers lhs "old" and rhs "new". self.assertMultiLineEqual(expected, s) else: self.assertEqual(s, expected) def assertExpectedStripMangled(self, s, subname=None): s = re.sub(r'__torch__[^ ]+', '', s) self.assertExpected(s, subname) # returns captured stderr @staticmethod def runWithPytorchAPIUsageStderr(code): import subprocess env = os.environ.copy() env["PYTORCH_API_USAGE_STDERR"] = "1" pipes = subprocess.Popen( [sys.executable, '-c', code], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) return pipes.communicate()[1].decode('ascii') if sys.version_info < (3, 2): # assertRegexpMatches renamed to assertRegex in 3.2 assertRegex = unittest.TestCase.assertRegexpMatches # assertRaisesRegexp renamed to assertRaisesRegex in 3.2 assertRaisesRegex = unittest.TestCase.assertRaisesRegexp if sys.version_info < (3, 5): # assertNotRegexpMatches renamed to assertNotRegex in 3.5 assertNotRegex = unittest.TestCase.assertNotRegexpMatches def download_file(url, binary=True): from urllib.parse import urlsplit from urllib import request, error filename = os.path.basename(urlsplit(url)[2]) data_dir = get_writable_path(os.path.join(os.path.dirname(__file__), 'data')) path = os.path.join(data_dir, filename) if os.path.exists(path): return path try: data = request.urlopen(url, timeout=15).read() with open(path, 'wb' if binary else 'w') as f: f.write(data) return path except error.URLError: msg = "could not download test file '{}'".format(url) warnings.warn(msg, RuntimeWarning) raise unittest.SkipTest(msg) def find_free_port(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('localhost', 0)) sockname = sock.getsockname() sock.close() return sockname[1] # Errors that we can get in c10d initialization for which we should retry tests for. ADDRESS_IN_USE = "Address already in use" CONNECT_TIMEOUT = "connect() timed out." def retry_on_connect_failures(func=None, connect_errors=(ADDRESS_IN_USE)): """Reruns a test if the test returns a RuntimeError and the exception matches exactly with one of the strings in connect_errors.""" # This if block is executed when using this function as a decorator with arguments. if func is None: return partial(retry_on_connect_failures, connect_errors=connect_errors) @wraps(func) def wrapper(*args, **kwargs): tries_remaining = 10 while True: try: return func(*args, **kwargs) except RuntimeError as error: if str(error) in connect_errors: tries_remaining -= 1 if tries_remaining == 0: raise time.sleep(random.random()) continue raise return wrapper # Decorator to retry upon certain Exceptions. def retry(ExceptionToCheck, tries=3, delay=3, skip_after_retries=False): def deco_retry(f): @wraps(f) def f_retry(*args, **kwargs): mtries, mdelay = tries, delay while mtries > 1: try: return f(*args, **kwargs) except ExceptionToCheck as e: msg = "%s, Retrying in %d seconds..." % (str(e), mdelay) print(msg) time.sleep(mdelay) mtries -= 1 try: return f(*args, **kwargs) except ExceptionToCheck as e: raise unittest.SkipTest(f"Skipping after {tries} consecutive {str(e)}") from e if skip_after_retries else e return f_retry # true decorator return deco_retry # Methods for matrix generation # Used in test_autograd.py and test_torch.py def prod_single_zero(dim_size): result = torch.randn(dim_size, dim_size) result[0, 1] = 0 return result def random_square_matrix_of_rank(l, rank, dtype=torch.double, device='cpu'): assert rank <= l A = torch.randn(l, l, dtype=dtype, device=device) u, s, v = A.svd() for i in range(l): if i >= rank: s[i] = 0 elif s[i] == 0: s[i] = 1 return u.mm(torch.diag(s)).mm(v.transpose(0, 1)) def random_symmetric_matrix(l, *batches, **kwargs): dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device) A = (A + A.transpose(-2, -1)).div_(2) return A def random_symmetric_psd_matrix(l, *batches, **kwargs): dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device) return torch.matmul(A, A.transpose(-2, -1)) def random_symmetric_pd_matrix(matrix_size, *batch_dims, **kwargs): dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') A = torch.randn(*(batch_dims + (matrix_size, matrix_size)), dtype=dtype, device=device) return torch.matmul(A, A.transpose(-2, -1)) \ + torch.eye(matrix_size, dtype=dtype, device=device) * 1e-5 def make_nonzero_det(A, sign=None, min_singular_value=0.1): u, s, v = A.svd() s.clamp_(min=min_singular_value) A = torch.matmul(u, torch.matmul(torch.diag_embed(s), v.transpose(-2, -1))) det = A.det() if sign is not None: if A.dim() == 2: det = det.item() if (det < 0) ^ (sign < 0): A[0, :].neg_() else: cond = ((det < 0) ^ (sign < 0)).nonzero() if cond.size(0) > 0: for i in range(cond.size(0)): A[list(cond[i])][0, :].neg_() return A def random_fullrank_matrix_distinct_singular_value(matrix_size, *batch_dims, **kwargs): dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') silent = kwargs.get("silent", False) if silent and not torch._C.has_lapack: return torch.ones(matrix_size, matrix_size, dtype=dtype, device=device) A = torch.randn(batch_dims + (matrix_size, matrix_size), dtype=dtype, device=device) u, _, v = A.svd() s = torch.arange(1., matrix_size + 1, dtype=dtype, device=device).mul_(1.0 / (matrix_size + 1)).diag() return u.matmul(s.expand(batch_dims + (matrix_size, matrix_size)).matmul(v.transpose(-2, -1))) def random_matrix(rows, columns, *batch_dims, **kwargs): """Return rectangular matrix or batches of rectangular matrices. Parameters: dtype - the data type device - the device kind singular - when True, the output will be singular """ dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') silent = kwargs.get("silent", False) singular = kwargs.get("singular", False) if silent and not torch._C.has_lapack: return torch.ones(rows, columns, dtype=dtype, device=device) A = torch.randn(batch_dims + (rows, columns), dtype=dtype, device=device) u, _, v = A.svd(some=False) s = torch.zeros(rows, columns, dtype=dtype, device=device) k = min(rows, columns) for i in range(k): s[i, i] = float(i + 1) / (k + 1) if singular: # make matrix singular s[k - 1, k - 1] = 0 if k > 2: # increase the order of singularity so that the pivoting # in LU factorization will be non-trivial s[0, 0] = 0 return u.matmul(s.expand(batch_dims + (rows, columns)).matmul(v.transpose(-2, -1))) def random_lowrank_matrix(rank, rows, columns, *batch_dims, **kwargs): """Return rectangular matrix or batches of rectangular matrices with given rank. """ B = random_matrix(rows, rank, *batch_dims, **kwargs) C = random_matrix(rank, columns, *batch_dims, **kwargs) return B.matmul(C) def random_sparse_matrix(rows, columns, density=0.01, **kwargs): """Return rectangular random sparse matrix within given density. The density of the result approaches to given density as the size of the matrix is increased and a relatively small value of density is specified but higher than min(rows, columns)/(rows * columns) for non-singular matrices. """ dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') singular = kwargs.get("singular", False) k = min(rows, columns) nonzero_elements = max(min(rows, columns), int(rows * columns * density)) row_indices = [i % rows for i in range(nonzero_elements)] column_indices = [i % columns for i in range(nonzero_elements)] random.shuffle(column_indices) indices = [row_indices, column_indices] values = torch.randn(nonzero_elements, dtype=dtype, device=device) # ensure that the diagonal dominates values *= torch.tensor([-float(i - j)**2 for i, j in zip(*indices)], dtype=dtype, device=device).exp() A = torch.sparse_coo_tensor(indices, values, (rows, columns), device=device) return A.coalesce() def random_sparse_pd_matrix(matrix_size, density=0.01, **kwargs): """Return random sparse positive-definite matrix with given density. The eigenvalues of the matrix are defined as:: arange(1, matrix_size+1)/matrix_size Algorithm: A = diag(arange(1, matrix_size+1)/matrix_size) while <A density is smaller than required>: <choose random i, j in range(matrix_size), theta in [0, 2*pi]> R = <rotation matrix (i,j,theta)> A = R^T A R """ import math torch = kwargs.get('torch', globals()['torch']) dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') data = dict([((i, i), float(i + 1) / matrix_size) for i in range(matrix_size)]) def multiply(data, N, i, j, cs, sn, left=True): for k in range(N): if left: ik, jk = (k, i), (k, j) else: ik, jk = (i, k), (j, k) aik, ajk = data.get(ik, 0), data.get(jk, 0) aik, ajk = cs * aik + sn * ajk, -sn * aik + cs * ajk if aik: data[ik] = aik else: data.pop(ik, None) if ajk: data[jk] = ajk else: data.pop(jk, None) target_nnz = density * matrix_size * matrix_size while len(data) < target_nnz: i = random.randint(0, matrix_size - 1) j = random.randint(0, matrix_size - 1) if i != j: theta = random.uniform(0, 2 * math.pi) cs = math.cos(theta) sn = math.sin(theta) multiply(data, matrix_size, i, j, cs, sn, left=True) multiply(data, matrix_size, i, j, cs, sn, left=False) icoords, jcoords, values = [], [], [] for (i, j), v in sorted(data.items()): icoords.append(i) jcoords.append(j) values.append(v) indices = [icoords, jcoords] return torch.sparse_coo_tensor(indices, values, (matrix_size, matrix_size), dtype=dtype, device=device) def do_test_dtypes(self, dtypes, layout, device): for dtype in dtypes: if dtype != torch.float16: out = torch.zeros((2, 3), dtype=dtype, layout=layout, device=device) self.assertIs(dtype, out.dtype) self.assertIs(layout, out.layout) self.assertEqual(device, out.device) def do_test_empty_full(self, dtypes, layout, device): shape = torch.Size([2, 3]) def check_value(tensor, dtype, layout, device, value, requires_grad): self.assertEqual(shape, tensor.shape) self.assertIs(dtype, tensor.dtype) self.assertIs(layout, tensor.layout) self.assertEqual(tensor.requires_grad, requires_grad) if tensor.is_cuda and device is not None: self.assertEqual(device, tensor.device) if value is not None: fill = tensor.new(shape).fill_(value) self.assertEqual(tensor, fill) def get_int64_dtype(dtype): module = '.'.join(str(dtype).split('.')[1:-1]) if not module: return torch.int64 return operator.attrgetter(module)(torch).int64 default_dtype = torch.get_default_dtype() check_value(torch.empty(shape), default_dtype, torch.strided, -1, None, False) check_value(torch.full(shape, -5.), default_dtype, torch.strided, -1, None, False) for dtype in dtypes: for rg in {dtype.is_floating_point, False}: int64_dtype = get_int64_dtype(dtype) v = torch.empty(shape, dtype=dtype, device=device, layout=layout, requires_grad=rg) check_value(v, dtype, layout, device, None, rg) out = v.new() check_value(torch.empty(shape, out=out, device=device, layout=layout, requires_grad=rg), dtype, layout, device, None, rg) check_value(v.new_empty(shape), dtype, layout, device, None, False) check_value(v.new_empty(shape, dtype=int64_dtype, device=device, requires_grad=False), int64_dtype, layout, device, None, False) check_value(torch.empty_like(v), dtype, layout, device, None, False) check_value(torch.empty_like(v, dtype=int64_dtype, layout=layout, device=device, requires_grad=False), int64_dtype, layout, device, None, False) if dtype is not torch.float16 and layout != torch.sparse_coo: fv = 3 v = torch.full(shape, fv, dtype=dtype, layout=layout, device=device, requires_grad=rg) check_value(v, dtype, layout, device, fv, rg) check_value(v.new_full(shape, fv + 1), dtype, layout, device, fv + 1, False) out = v.new() check_value(torch.full(shape, fv + 2, out=out, device=device, layout=layout, requires_grad=rg), dtype, layout, device, fv + 2, rg) check_value(v.new_full(shape, fv + 3, dtype=int64_dtype, device=device, requires_grad=False), int64_dtype, layout, device, fv + 3, False) check_value(torch.full_like(v, fv + 4), dtype, layout, device, fv + 4, False) check_value(torch.full_like(v, fv + 5, dtype=int64_dtype, layout=layout, device=device, requires_grad=False), int64_dtype, layout, device, fv + 5, False) THESE_TAKE_WAY_TOO_LONG = { 'test_Conv3d_groups', 'test_conv_double_backward', 'test_conv_double_backward_groups', 'test_Conv3d_dilated', 'test_Conv3d_stride_padding', 'test_Conv3d_dilated_strided', 'test_Conv3d', 'test_Conv2d_dilated', 'test_ConvTranspose3d_dilated', 'test_ConvTranspose2d_dilated', 'test_snli', 'test_Conv2d', 'test_Conv2d_padding', 'test_ConvTranspose2d_no_bias', 'test_ConvTranspose2d', 'test_ConvTranspose3d', 'test_Conv2d_no_bias', 'test_matmul_4d_4d', 'test_multinomial_invalid_probs', } running_script_path = None def set_running_script_path(): global running_script_path try: running_file = os.path.abspath(os.path.realpath(sys.argv[0])) if running_file.endswith('.py'): # skip if the running file is not a script running_script_path = running_file except Exception: pass def check_test_defined_in_running_script(test_case): if running_script_path is None: return test_case_class_file = os.path.abspath(os.path.realpath(inspect.getfile(test_case.__class__))) assert test_case_class_file == running_script_path, "Class of loaded TestCase \"{}\" " \ "is not defined in the running script \"{}\", but in \"{}\". Did you " \ "accidentally import a unittest.TestCase from another file?".format( test_case.id(), running_script_path, test_case_class_file) def load_tests(loader, tests, pattern): set_running_script_path() test_suite = unittest.TestSuite() for test_group in tests: for test in test_group: check_test_defined_in_running_script(test) test_suite.addTest(test) return test_suite class BytesIOContext(io.BytesIO): def __enter__(self): return self def __exit__(self, *args): pass def _assertGradAndGradgradChecks(test_case, apply_fn, inputs): # call assert function rather than returning a bool since it's nicer # if we get whether this failed on the gradcheck or the gradgradcheck. test_case.assertTrue(gradcheck(apply_fn, inputs)) test_case.assertTrue(gradgradcheck(apply_fn, inputs)) # Using @precisionOverride specific to your test is the recommended way # of doing this. These are just some values that worked for test_nn. dtype2prec_DONTUSE = {torch.float: 1e-5, torch.double: 1e-5, torch.half: 1e-2, torch.bfloat16: 1e-1}
[]
[]
[ "TEST_REPORT_SOURCE_OVERRIDE", "NO_MULTIPROCESSING_SPAWN", "PYTORCH_TEST_WITH_ROCM", "IS_PYTORCH_CI", "IN_CIRCLECI", "PYTORCH_TEST_WITH_ASAN", "PYTORCH_HYPOTHESIS_PROFILE", "PYTORCH_TEST_WITH_SLOW", "PYTORCH_TEST_WITH_TSAN", "PYTORCH_TEST_SKIP_FAST", "PYTORCH_TEST_WITH_UBSAN", "PYTORCH_RUN_DISABLED_TESTS", "TW_JOB_USER", "SANDCASTLE" ]
[]
["TEST_REPORT_SOURCE_OVERRIDE", "NO_MULTIPROCESSING_SPAWN", "PYTORCH_TEST_WITH_ROCM", "IS_PYTORCH_CI", "IN_CIRCLECI", "PYTORCH_TEST_WITH_ASAN", "PYTORCH_HYPOTHESIS_PROFILE", "PYTORCH_TEST_WITH_SLOW", "PYTORCH_TEST_WITH_TSAN", "PYTORCH_TEST_SKIP_FAST", "PYTORCH_TEST_WITH_UBSAN", "PYTORCH_RUN_DISABLED_TESTS", "TW_JOB_USER", "SANDCASTLE"]
python
14
0
modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java
package org.openapitools.codegen.languages; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.servers.Server; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.features.*; import org.openapitools.codegen.utils.ModelUtils; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.openapitools.codegen.utils.StringUtils.*; import static org.openapitools.codegen.utils.StringUtils.camelize; public abstract class AbstractDartCodegen extends DefaultCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDartCodegen.class); public static final String PUB_LIBRARY = "pubLibrary"; public static final String PUB_NAME = "pubName"; public static final String PUB_VERSION = "pubVersion"; public static final String PUB_DESCRIPTION = "pubDescription"; public static final String PUB_AUTHOR = "pubAuthor"; public static final String PUB_AUTHOR_EMAIL = "pubAuthorEmail"; public static final String PUB_HOMEPAGE = "pubHomepage"; public static final String USE_ENUM_EXTENSION = "useEnumExtension"; protected String pubLibrary = "openapi.api"; protected String pubName = "openapi"; protected String pubVersion = "1.0.0"; protected String pubDescription = "OpenAPI API client"; protected String pubAuthor = "Author"; protected String pubAuthorEmail = "author@homepage"; protected String pubHomepage = "homepage"; protected boolean useEnumExtension = false; protected String sourceFolder = ""; protected String apiDocPath = "doc" + File.separator; protected String modelDocPath = "doc" + File.separator; protected String apiTestPath = "test" + File.separator; protected String modelTestPath = "test" + File.separator; // Names that must not be used as model names because they clash with existing // default imports (dart:io, dart:async, package:http etc.) but are not basic dataTypes. protected Set<String> additionalReservedWords; public AbstractDartCodegen() { super(); modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.of( SecurityFeature.OAuth2_Implicit, SecurityFeature.BasicAuth, SecurityFeature.ApiKey )) .excludeGlobalFeatures( GlobalFeature.XMLStructureDefinitions, GlobalFeature.Callbacks, GlobalFeature.LinkObjects, GlobalFeature.ParameterStyling ) .excludeSchemaSupportFeatures( SchemaSupportFeature.Polymorphism ) .includeParameterFeatures( ParameterFeature.Cookie ) .includeClientModificationFeatures( ClientModificationFeature.BasePath ) ); outputFolder = "generated-code/dart"; modelTemplateFiles.put("model.mustache", ".dart"); apiTemplateFiles.put("api.mustache", ".dart"); embeddedTemplateDir = templateDir = "dart2"; apiPackage = "lib.api"; modelPackage = "lib.model"; modelDocTemplateFiles.put("object_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); modelTestTemplateFiles.put("model_test.mustache", ".dart"); apiTestTemplateFiles.put("api_test.mustache", ".dart"); final List<String> reservedWordsList = new ArrayList<>(); try(BufferedReader reader = new BufferedReader( new InputStreamReader(DartClientCodegen.class.getResourceAsStream("/dart/dart-keywords.txt"), StandardCharsets.UTF_8))) { while (reader.ready()) { reservedWordsList.add(reader.readLine()); } } catch (Exception e) { LOGGER.error("Error reading dart keywords. Exception: {}", e.getMessage()); } setReservedWordsLowerCase(reservedWordsList); languageSpecificPrimitives = Sets.newHashSet( "String", "bool", "int", "num", "double", "dynamic" ); typeMapping = new HashMap<>(); typeMapping.put("Array", "List"); typeMapping.put("array", "List"); typeMapping.put("map", "Map"); typeMapping.put("List", "List"); typeMapping.put("set", "Set"); typeMapping.put("boolean", "bool"); typeMapping.put("string", "String"); typeMapping.put("char", "String"); typeMapping.put("int", "int"); typeMapping.put("long", "int"); typeMapping.put("short", "int"); typeMapping.put("number", "num"); typeMapping.put("float", "double"); typeMapping.put("double", "double"); typeMapping.put("decimal", "double"); typeMapping.put("integer", "int"); typeMapping.put("Date", "DateTime"); typeMapping.put("date", "DateTime"); typeMapping.put("DateTime", "DateTime"); typeMapping.put("file", "MultipartFile"); typeMapping.put("binary", "MultipartFile"); typeMapping.put("UUID", "String"); typeMapping.put("URI", "String"); typeMapping.put("ByteArray", "String"); typeMapping.put("object", "Object"); typeMapping.put("AnyType", "Object"); // DataTypes of the above values which are automatically imported. // They are also not allowed to be model names. defaultIncludes = Sets.newHashSet( "String", "bool", "int", "num", "double", "dynamic", "List", "Set", "Map", "DateTime", "Object", "MultipartFile" ); additionalReservedWords = Sets.newHashSet( "File", "Client", "Future", "Response" ); cliOptions.add(new CliOption(PUB_LIBRARY, "Library name in generated code")); cliOptions.add(new CliOption(PUB_NAME, "Name in generated pubspec")); cliOptions.add(new CliOption(PUB_VERSION, "Version in generated pubspec")); cliOptions.add(new CliOption(PUB_DESCRIPTION, "Description in generated pubspec")); cliOptions.add(new CliOption(PUB_AUTHOR, "Author name in generated pubspec")); cliOptions.add(new CliOption(PUB_AUTHOR_EMAIL, "Email address of the author in generated pubspec")); cliOptions.add(new CliOption(PUB_HOMEPAGE, "Homepage in generated pubspec")); cliOptions.add(new CliOption(USE_ENUM_EXTENSION, "Allow the 'x-enum-values' extension for enums")); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "Source folder for generated code")); } @Override public CodegenType getTag() { return CodegenType.CLIENT; } @Override public String getName() { return "dart"; } @Override public String getHelp() { return "Generates a Dart 2.x client library."; } @Override public void processOpts() { super.processOpts(); if (StringUtils.isEmpty(System.getenv("DART_POST_PROCESS_FILE"))) { LOGGER.info("Environment variable DART_POST_PROCESS_FILE not defined so the Dart code may not be properly formatted. To define it, try `export DART_POST_PROCESS_FILE=\"/usr/local/bin/dartfmt -w\"` (Linux/Mac)"); LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI)."); } if (additionalProperties.containsKey(PUB_NAME)) { this.setPubName((String) additionalProperties.get(PUB_NAME)); } else { //not set, use to be passed to template additionalProperties.put(PUB_NAME, pubName); } if (additionalProperties.containsKey(PUB_LIBRARY)) { this.setPubLibrary((String) additionalProperties.get(PUB_LIBRARY)); } else { //not set, use to be passed to template additionalProperties.put(PUB_LIBRARY, pubLibrary); } if (additionalProperties.containsKey(PUB_VERSION)) { this.setPubVersion((String) additionalProperties.get(PUB_VERSION)); } else { //not set, use to be passed to template additionalProperties.put(PUB_VERSION, pubVersion); } if (additionalProperties.containsKey(PUB_DESCRIPTION)) { this.setPubDescription((String) additionalProperties.get(PUB_DESCRIPTION)); } else { //not set, use to be passed to template additionalProperties.put(PUB_DESCRIPTION, pubDescription); } if (additionalProperties.containsKey(PUB_AUTHOR)) { this.setPubAuthor((String) additionalProperties.get(PUB_AUTHOR)); } else { //not set, use to be passed to template additionalProperties.put(PUB_AUTHOR, pubAuthor); } if (additionalProperties.containsKey(PUB_AUTHOR_EMAIL)) { this.setPubAuthorEmail((String) additionalProperties.get(PUB_AUTHOR_EMAIL)); } else { //not set, use to be passed to template additionalProperties.put(PUB_AUTHOR_EMAIL, pubAuthorEmail); } if (additionalProperties.containsKey(PUB_HOMEPAGE)) { this.setPubHomepage((String) additionalProperties.get(PUB_HOMEPAGE)); } else { //not set, use to be passed to template additionalProperties.put(PUB_HOMEPAGE, pubHomepage); } if (additionalProperties.containsKey(USE_ENUM_EXTENSION)) { this.setUseEnumExtension(convertPropertyToBooleanAndWriteBack(USE_ENUM_EXTENSION)); } else { // Not set, use to be passed to template. additionalProperties.put(USE_ENUM_EXTENSION, useEnumExtension); } if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } // make api and model doc path available in mustache template additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); // check to not overwrite a custom templateDir if (templateDir == null) { embeddedTemplateDir = templateDir = "dart2"; } } @Override protected boolean isReservedWord(String word) { // consider everything as reserved that is either a keyword, // a default included type, or a type include through some library return super.isReservedWord(word) || defaultIncludes().contains(word) || additionalReservedWords.contains(word); } @Override public String escapeReservedWord(String name) { return name + "_"; } @Override public String apiFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar); } @Override public String modelFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar); } @Override public String apiTestFileFolder() { return outputFolder + File.separator + apiTestPath.replace('/', File.separatorChar); } @Override public String modelTestFileFolder() { return outputFolder + File.separator + modelTestPath.replace('/', File.separatorChar); } @Override public String apiDocFileFolder() { return outputFolder + File.separator + apiDocPath.replace('/', File.separatorChar); } @Override public String modelDocFileFolder() { return outputFolder + File.separator + modelDocPath.replace('/', File.separatorChar); } @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at name = name.replace("-", "_"); // always need to replace leading underscores first name = name.replaceAll("^_", ""); // if it's all upper case, do nothing if (name.matches("^[A-Z_]*$")) { return name; } // replace all characters that have a mapping but ignore underscores // append an underscore to each replacement so that it can be camelized if (name.chars().anyMatch(character -> specialCharReplacements.containsKey("" + ((char) character)))) { name = escape(name, specialCharReplacements, Lists.newArrayList("_"), "_"); } // remove the rest name = sanitizeName(name); // camelize (lower first character) the variable name // pet_id => petId name = camelize(name, true); if (name.matches("^\\d.*")) { name = "n" + name; } if (isReservedWord(name)) { name = escapeReservedWord(name); } return name; } @Override public String toParamName(String name) { // should be the same as variable name return toVarName(name); } @Override public String toModelName(final String name) { String nameWithPrefixSuffix = sanitizeName(name); if (!StringUtils.isEmpty(modelNamePrefix)) { // add '_' so that model name can be camelized correctly nameWithPrefixSuffix = modelNamePrefix + "_" + nameWithPrefixSuffix; } if (!StringUtils.isEmpty(modelNameSuffix)) { // add '_' so that model name can be camelized correctly nameWithPrefixSuffix = nameWithPrefixSuffix + "_" + modelNameSuffix; } // camelize the model name // phone_number => PhoneNumber final String camelizedName = camelize(nameWithPrefixSuffix); // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { final String modelName = "Model" + camelizedName; LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); return modelName; } // model name starts with number if (camelizedName.matches("^\\d.*")) { final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); return modelName; } return camelizedName; } @Override public String toModelFilename(String name) { return underscore(toModelName(name)); } @Override public String toModelDocFilename(String name) { return toModelName(name); } @Override public String toApiFilename(String name) { return underscore(toApiName(name)); } @Override public String toApiTestFilename(String name) { return toApiFilename(name) + "_test"; } @Override public String toModelTestFilename(String name) { return toModelFilename(name) + "_test"; } @Override public String toDefaultValue(Schema schema) { if (ModelUtils.isMapSchema(schema) || ModelUtils.isSet(schema)) { return "const {}"; } if (ModelUtils.isArraySchema(schema)) { return "const []"; } if (schema.getDefault() != null) { if (ModelUtils.isDateSchema(schema) || ModelUtils.isDateTimeSchema(schema)) { // this is currently not supported and would create compile errors return null; } if (ModelUtils.isStringSchema(schema)) { return "'" + schema.getDefault().toString().replace("'", "\\'") + "'"; } return schema.getDefault().toString(); } return null; } @Override public String getTypeDeclaration(Schema p) { Schema<?> schema = ModelUtils.unaliasSchema(this.openAPI, p, importMapping); Schema<?> target = ModelUtils.isGenerateAliasAsModel() ? p : schema; if (ModelUtils.isArraySchema(target)) { Schema<?> items = getSchemaItems((ArraySchema) schema); return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">"; } if (ModelUtils.isMapSchema(target)) { // Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines // additionalproperties: true Schema<?> inner = getAdditionalProperties(target); if (inner == null) { LOGGER.error("`{}` (map property) does not have a proper inner type defined. Default to type:string", p.getName()); inner = new StringSchema().description("TODO default missing map inner type to string"); p.setAdditionalProperties(inner); } return getSchemaType(target) + "<String, " + getTypeDeclaration(inner) + ">"; } return super.getTypeDeclaration(p); } @Override public String getSchemaType(Schema p) { String openAPIType = super.getSchemaType(p); if (openAPIType == null) { LOGGER.error("No Type defined for Schema " + p); } if (typeMapping.containsKey(openAPIType)) { return typeMapping.get(openAPIType); } if (languageSpecificPrimitives.contains(openAPIType)) { return openAPIType; } return toModelName(openAPIType); } @Override public Map<String, Object> postProcessModels(Map<String, Object> objs) { return postProcessModelsEnum(objs); } @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); if (!model.isEnum && property.isEnum) { // These are inner enums, enums which do not exist as models, just as properties. // They are handled via the enum_inline template and and are generated in the // same file as the containing class. To prevent name clashes the inline enum classes // are prefix with the classname of the containing class in the template. // Here the datatypeWithEnum template variable gets updated to match that scheme. // Also taking into account potential collection types e.g. List<JustSymbolEnum> -> List<EnumArraysJustSymbolEnum> final String enumName = model.classname + property.enumName; if (property.items != null) { // inner items e.g. enums in collections, only works for one level // but same is the case for DefaultCodegen property.setDatatypeWithEnum(property.datatypeWithEnum.replace(property.items.datatypeWithEnum, enumName)); property.items.setDatatypeWithEnum(enumName); property.items.setEnumName(enumName); } else { // plain enum property property.setDatatypeWithEnum(property.datatypeWithEnum.replace(property.enumName, enumName)); } property.setEnumName(enumName); } } @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) { final CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); for (CodegenResponse r : op.responses) { // By default only set types are automatically added to operation imports, not sure why. // Add all container type imports here, by default 'dart:core' imports are skipped // but other sub classes may required specific container type imports. if (r.containerType != null && typeMapping().containsKey(r.containerType)) { final String value = typeMapping().get(r.containerType); if (needToImport(value)) { op.imports.add(value); } } } for (CodegenParameter p : op.allParams) { if (p.isContainer) { final String type = p.isArray ? "array" : "map"; if (typeMapping().containsKey(type)) { final String value = typeMapping().get(type); // Also add container imports for parameters. if (needToImport(value)) { op.imports.add(value); } } } } return op; } @Override protected void updateEnumVarsWithExtensions(List<Map<String, Object>> enumVars, Map<String, Object> vendorExtensions, String dataType) { if (vendorExtensions != null && useEnumExtension && vendorExtensions.containsKey("x-enum-values")) { // Use the x-enum-values extension for this enum // Existing enumVars added by the default handling need to be removed first enumVars.clear(); Object extension = vendorExtensions.get("x-enum-values"); List<Map<String, Object>> values = (List<Map<String, Object>>) extension; for (Map<String, Object> value : values) { Map<String, Object> enumVar = new HashMap<>(); enumVar.put("name", toEnumVarName((String) value.get("identifier"), dataType)); enumVar.put("value", toEnumValue(value.get("numericValue").toString(), dataType)); enumVar.put("isString", isDataTypeString(dataType)); if (value.containsKey("description")) { enumVar.put("description", value.get("description").toString()); } enumVars.add(enumVar); } } else { super.updateEnumVarsWithExtensions(enumVars, vendorExtensions, dataType); } } @Override public String toEnumVarName(String value, String datatype) { if (value.length() == 0) { return "empty"; } if (("number".equalsIgnoreCase(datatype) || "double".equalsIgnoreCase(datatype) || "int".equalsIgnoreCase(datatype)) && value.matches("^-?\\d.*")) { // Only rename numeric values when the datatype is numeric // AND the name is not changed by enum extensions (matches a numeric value). boolean isNegative = value.startsWith("-"); return toVarName("number" + (isNegative ? "_negative" : "") + value); } return toVarName(value); } @Override public String toEnumValue(String value, String datatype) { if ("number".equalsIgnoreCase(datatype) || "int".equalsIgnoreCase(datatype)) { return value; } else { return "'" + escapeText(value) + "'"; } } @Override public String toOperationId(String operationId) { operationId = super.toOperationId(operationId); operationId = camelize(sanitizeName(operationId), true); // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize("call_" + operationId, true); LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize("call_" + operationId), true); operationId = camelize("call_" + operationId, true); } return operationId; } public void setPubLibrary(String pubLibrary) { this.pubLibrary = pubLibrary; } public void setPubName(String pubName) { this.pubName = pubName; } public void setPubVersion(String pubVersion) { this.pubVersion = pubVersion; } public void setPubDescription(String pubDescription) { this.pubDescription = pubDescription; } public void setPubAuthor(String pubAuthor) { this.pubAuthor = pubAuthor; } public void setPubAuthorEmail(String pubAuthorEmail) { this.pubAuthorEmail = pubAuthorEmail; } public void setPubHomepage(String pubHomepage) { this.pubHomepage = pubHomepage; } public void setUseEnumExtension(boolean useEnumExtension) { this.useEnumExtension = useEnumExtension; } public void setSourceFolder(String sourceFolder) { this.sourceFolder = sourceFolder; } @Override public String escapeQuotationMark(String input) { // remove " to avoid code injection return input.replace("\"", ""); } @Override public String escapeUnsafeCharacters(String input) { return input.replace("*/", "*_/").replace("/*", "/_*"); } @Override public void postProcessFile(File file, String fileType) { if (file == null) { return; } String dartPostProcessFile = System.getenv("DART_POST_PROCESS_FILE"); if (StringUtils.isEmpty(dartPostProcessFile)) { return; // skip if DART_POST_PROCESS_FILE env variable is not defined } // process all files with dart extension if ("dart".equals(FilenameUtils.getExtension(file.toString()))) { // currently only support "dartfmt -w yourcode.dart" String command = dartPostProcessFile + " " + file.toString(); try { Process p = Runtime.getRuntime().exec(command); int exitValue = p.waitFor(); if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue); } else { LOGGER.info("Successfully executed: {}", command); } } catch (Exception e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); } } } }
[ "\"DART_POST_PROCESS_FILE\"", "\"DART_POST_PROCESS_FILE\"" ]
[]
[ "DART_POST_PROCESS_FILE" ]
[]
["DART_POST_PROCESS_FILE"]
java
1
0
server/db/mongo.go
package db import ( "fmt" "gopkg.in/mgo.v2" "os" ) func GetSession() (session *mgo.Session, err error) { session, err = mgo.Dial(os.Getenv("MONGO_URI")) if err != nil { fmt.Print("error connecting to db") return } return } func GetDBName() string { return "palindetect" }
[ "\"MONGO_URI\"" ]
[]
[ "MONGO_URI" ]
[]
["MONGO_URI"]
go
1
0
docs/conf.py
# -*- coding: utf-8 -*- # # django-textplusstuff documentation build configuration file, created by # sphinx-quickstart on Mon Feb 9 09:12:04 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'django-textplusstuff' copyright = u'2018, WGBH Educational Foundation' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. on_rtd = os.environ.get('READTHEDOCS', False) if not on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'django-textplusstuffdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'django-textplusstuff.tex', u'django-textplusstuff Documentation', u'Jonathan Ellenberger et al', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'django-textplusstuff', u'django-textplusstuff Documentation', [u'Jonathan Ellenberger', u'Jay Thompson'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'django-textplusstuff', u'django-textplusstuff Documentation', u'Jonathan Ellenberger et al', 'django-textplusstuff', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None}
[]
[]
[ "READTHEDOCS" ]
[]
["READTHEDOCS"]
python
1
0
docs/conf.py
# -*- coding: utf-8 -*- # # splinter documentation build configuration file, created by # sphinx-quickstart on Sat Jan 8 23:31:41 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) import os import sys from datetime import datetime sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) import splinter # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ["sphinx.ext.autodoc", "sphinx.ext.napoleon"] # Add any paths that contain templates here, relative to this directory. # templates_path = ['_templates'] # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = u"Splinter" copyright = u"{}, cobrateam".format(datetime.now().year) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = splinter.__version__ # The full version, including alpha/beta/rc tags. release = splinter.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "vs" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'nature' if not os.environ.get("READTHEDOCS", None): import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "splinterdoc" # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). # latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). # latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ("index", "splinter.tex", u"splinter Documentation", u"andrews medina", "manual") ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Additional stuff for the LaTeX preamble. # latex_preamble = '' # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [("index", "splinter", u"splinter Documentation", [u"andrews medina"], 1)]
[]
[]
[ "READTHEDOCS" ]
[]
["READTHEDOCS"]
python
1
0
credscontroller/vendor/github.com/hashicorp/vault/builtin/credential/okta/backend_test.go
package okta import ( "context" "fmt" "os" "strings" "testing" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/sdk/helper/logging" "github.com/hashicorp/vault/sdk/helper/policyutil" "time" logicaltest "github.com/hashicorp/vault/helper/testhelpers/logical" "github.com/hashicorp/vault/sdk/logical" ) func TestBackend_Config(t *testing.T) { defaultLeaseTTLVal := time.Hour * 12 maxLeaseTTLVal := time.Hour * 24 b, err := Factory(context.Background(), &logical.BackendConfig{ Logger: logging.NewVaultLogger(log.Trace), System: &logical.StaticSystemView{ DefaultLeaseTTLVal: defaultLeaseTTLVal, MaxLeaseTTLVal: maxLeaseTTLVal, }, }) if err != nil { t.Fatalf("Unable to create backend: %s", err) } username := os.Getenv("OKTA_USERNAME") password := os.Getenv("OKTA_PASSWORD") token := os.Getenv("OKTA_API_TOKEN") configData := map[string]interface{}{ "organization": os.Getenv("OKTA_ORG"), "base_url": "oktapreview.com", } updatedDuration := time.Hour * 1 configDataToken := map[string]interface{}{ "token": token, "ttl": "1h", } logicaltest.Test(t, logicaltest.TestCase{ AcceptanceTest: true, PreCheck: func() { testAccPreCheck(t) }, LogicalBackend: b, Steps: []logicaltest.TestStep{ testConfigCreate(t, configData), testLoginWrite(t, username, "wrong", "E0000004", 0, nil), testLoginWrite(t, username, password, "user is not a member of any authorized policy", 0, nil), testAccUserGroups(t, username, "local_grouP,lOcal_group2", []string{"user_policy"}), testAccGroups(t, "local_groUp", "loCal_group_policy"), testLoginWrite(t, username, password, "", defaultLeaseTTLVal, []string{"local_group_policy", "user_policy"}), testAccGroups(t, "everyoNe", "everyone_grouP_policy,eveRy_group_policy2"), testLoginWrite(t, username, password, "", defaultLeaseTTLVal, []string{"local_group_policy", "user_policy"}), testConfigUpdate(t, configDataToken), testConfigRead(t, token, configData), testLoginWrite(t, username, password, "", updatedDuration, []string{"everyone_group_policy", "every_group_policy2", "local_group_policy", "user_policy"}), testAccGroups(t, "locAl_group2", "testgroup_group_policy"), testLoginWrite(t, username, password, "", updatedDuration, []string{"everyone_group_policy", "every_group_policy2", "local_group_policy", "testgroup_group_policy", "user_policy"}), }, }) } func testLoginWrite(t *testing.T, username, password, reason string, expectedTTL time.Duration, policies []string) logicaltest.TestStep { return logicaltest.TestStep{ Operation: logical.UpdateOperation, Path: "login/" + username, ErrorOk: true, Data: map[string]interface{}{ "password": password, }, Check: func(resp *logical.Response) error { if resp.IsError() { if reason == "" || !strings.Contains(resp.Error().Error(), reason) { return resp.Error() } } if resp.Auth != nil { if !policyutil.EquivalentPolicies(resp.Auth.Policies, policies) { return fmt.Errorf("policy mismatch expected %v but got %v", policies, resp.Auth.Policies) } actualTTL := resp.Auth.LeaseOptions.TTL if actualTTL != expectedTTL { return fmt.Errorf("TTL mismatch expected %v but got %v", expectedTTL, actualTTL) } } return nil }, } } func testConfigCreate(t *testing.T, d map[string]interface{}) logicaltest.TestStep { return logicaltest.TestStep{ Operation: logical.CreateOperation, Path: "config", Data: d, } } func testConfigUpdate(t *testing.T, d map[string]interface{}) logicaltest.TestStep { return logicaltest.TestStep{ Operation: logical.UpdateOperation, Path: "config", Data: d, } } func testConfigRead(t *testing.T, token string, d map[string]interface{}) logicaltest.TestStep { return logicaltest.TestStep{ Operation: logical.ReadOperation, Path: "config", Check: func(resp *logical.Response) error { if resp.IsError() { return resp.Error() } if resp.Data["organization"] != d["organization"] { return fmt.Errorf("org mismatch expected %s but got %s", d["organization"], resp.Data["Org"]) } if resp.Data["base_url"] != d["base_url"] { return fmt.Errorf("BaseURL mismatch expected %s but got %s", d["base_url"], resp.Data["BaseURL"]) } for _, value := range resp.Data { if value == token { return fmt.Errorf("token should not be returned on a read request") } } return nil }, } } func testAccPreCheck(t *testing.T) { if v := os.Getenv("OKTA_USERNAME"); v == "" { t.Fatal("OKTA_USERNAME must be set for acceptance tests") } if v := os.Getenv("OKTA_PASSWORD"); v == "" { t.Fatal("OKTA_PASSWORD must be set for acceptance tests") } if v := os.Getenv("OKTA_ORG"); v == "" { t.Fatal("OKTA_ORG must be set for acceptance tests") } if v := os.Getenv("OKTA_API_TOKEN"); v == "" { t.Fatal("OKTA_API_TOKEN must be set for acceptance tests") } } func testAccUserGroups(t *testing.T, user string, groups interface{}, policies interface{}) logicaltest.TestStep { return logicaltest.TestStep{ Operation: logical.UpdateOperation, Path: "users/" + user, Data: map[string]interface{}{ "groups": groups, "policies": policies, }, } } func testAccGroups(t *testing.T, group string, policies interface{}) logicaltest.TestStep { t.Logf("[testAccGroups] - Registering group %s, policy %s", group, policies) return logicaltest.TestStep{ Operation: logical.UpdateOperation, Path: "groups/" + group, Data: map[string]interface{}{ "policies": policies, }, } } func testAccLogin(t *testing.T, user, password string, keys []string) logicaltest.TestStep { return logicaltest.TestStep{ Operation: logical.UpdateOperation, Path: "login/" + user, Data: map[string]interface{}{ "password": password, }, Unauthenticated: true, Check: logicaltest.TestCheckAuth(keys), } }
[ "\"OKTA_USERNAME\"", "\"OKTA_PASSWORD\"", "\"OKTA_API_TOKEN\"", "\"OKTA_ORG\"", "\"OKTA_USERNAME\"", "\"OKTA_PASSWORD\"", "\"OKTA_ORG\"", "\"OKTA_API_TOKEN\"" ]
[]
[ "OKTA_API_TOKEN", "OKTA_USERNAME", "OKTA_ORG", "OKTA_PASSWORD" ]
[]
["OKTA_API_TOKEN", "OKTA_USERNAME", "OKTA_ORG", "OKTA_PASSWORD"]
go
4
0
bindings/tests/integration/test_coverage.py
import os def which(tool): """ return the absolute path to the tool """ for path in os.environ['PATH'].split(os.pathsep): p = os.path.join(path, tool) if os.path.exists(p): return os.path.abspath(p) return None def test_tool_works(): assert which("coverage")
[]
[]
[ "PATH" ]
[]
["PATH"]
python
1
0
main.go
package main import ( "fmt" "log" "os" "path/filepath" "strconv" "github.com/roots/trellis-cli/cmd" "github.com/roots/trellis-cli/config" "github.com/roots/trellis-cli/github" "github.com/roots/trellis-cli/plugin" "github.com/roots/trellis-cli/trellis" "github.com/roots/trellis-cli/update" "github.com/fatih/color" "github.com/mitchellh/cli" ) // To be replaced by goreleaser build flags. var version = "canary" var updaterRepo = "" func main() { cacheDir, _ := config.Scope.CacheDir() updateNotifier := &update.Notifier{ CacheDir: cacheDir, Client: github.Client, Repo: updaterRepo, Version: version, } updateMessageChan := make(chan *github.Release) go func() { release, _ := updateNotifier.CheckForUpdate() updateMessageChan <- release }() c := cli.NewCLI("trellis", version) c.Args = os.Args[1:] ui := &cli.ColoredUi{ ErrorColor: cli.UiColorRed, Ui: &cli.BasicUi{ Reader: os.Stdin, Writer: os.Stdout, ErrorWriter: os.Stderr, }, } project := &trellis.Project{} trellis := trellis.NewTrellis(project) c.Commands = map[string]cli.CommandFactory{ "alias": func() (cli.Command, error) { return cmd.NewAliasCommand(ui, trellis), nil }, "check": func() (cli.Command, error) { return &cmd.CheckCommand{UI: ui, Trellis: trellis}, nil }, "db": func() (cli.Command, error) { return &cmd.NamespaceCommand{ HelpText: "Usage: trellis db <subcommand> [<args>]", SynopsisText: "Commands for database management", }, nil }, "db open": func() (cli.Command, error) { return cmd.NewDBOpenCommand(ui, trellis), nil }, "deploy": func() (cli.Command, error) { return cmd.NewDeployCommand(ui, trellis), nil }, "dotenv": func() (cli.Command, error) { return cmd.NewDotEnvCommand(ui, trellis), nil }, "down": func() (cli.Command, error) { return &cmd.DownCommand{UI: ui, Trellis: trellis}, nil }, "droplet": func() (cli.Command, error) { return &cmd.NamespaceCommand{ HelpText: "Usage: trellis droplet <subcommand> [<args>]", SynopsisText: "Commands for DigitalOcean Droplets", }, nil }, "droplet create": func() (cli.Command, error) { return cmd.NewDropletCreateCommand(ui, trellis), nil }, "exec": func() (cli.Command, error) { return &cmd.ExecCommand{UI: ui, Trellis: trellis}, nil }, "galaxy": func() (cli.Command, error) { return &cmd.NamespaceCommand{ HelpText: "Usage: trellis galaxy <subcommand> [<args>]", SynopsisText: "Commands for Ansible Galaxy", }, nil }, "galaxy install": func() (cli.Command, error) { return &cmd.GalaxyInstallCommand{UI: ui, Trellis: trellis}, nil }, "info": func() (cli.Command, error) { return &cmd.InfoCommand{UI: ui, Trellis: trellis}, nil }, "init": func() (cli.Command, error) { return &cmd.InitCommand{UI: ui, Trellis: trellis}, nil }, "new": func() (cli.Command, error) { return cmd.NewNewCommand(ui, trellis, c.Version), nil }, "provision": func() (cli.Command, error) { return cmd.NewProvisionCommand(ui, trellis), nil }, "rollback": func() (cli.Command, error) { return cmd.NewRollbackCommand(ui, trellis), nil }, "shell-init": func() (cli.Command, error) { return &cmd.ShellInitCommand{ui}, nil }, "ssh": func() (cli.Command, error) { return &cmd.SshCommand{ui, trellis}, nil }, "up": func() (cli.Command, error) { return cmd.NewUpCommand(ui, trellis), nil }, "vault": func() (cli.Command, error) { return &cmd.NamespaceCommand{ HelpText: "Usage: trellis vault <subcommand> [<args>]", SynopsisText: "Commands for Ansible Vault", }, nil }, "vault edit": func() (cli.Command, error) { return &cmd.VaultEditCommand{ui, trellis}, nil }, "vault encrypt": func() (cli.Command, error) { return cmd.NewVaultEncryptCommand(ui, trellis), nil }, "vault decrypt": func() (cli.Command, error) { return cmd.NewVaultDecryptCommand(ui, trellis), nil }, "vault view": func() (cli.Command, error) { return cmd.NewVaultViewCommand(ui, trellis), nil }, "valet": func() (cli.Command, error) { return &cmd.NamespaceCommand{ HelpText: "Usage: trellis valet <subcommand> [<args>]", SynopsisText: "Commands for Laravel Valet", }, nil }, "valet link": func() (cli.Command, error) { return &cmd.ValetLinkCommand{UI: ui, Trellis: trellis}, nil }, "venv hook": func() (cli.Command, error) { return &cmd.VenvHookCommand{UI: ui, Trellis: trellis}, nil }, } c.HiddenCommands = []string{"venv", "venv hook"} if shouldSkipPlugins, _ := strconv.ParseBool(os.Getenv("TRELLIS_NO_PLUGINS")); !shouldSkipPlugins { pluginPaths := filepath.SplitList(os.Getenv("PATH")) plugin.Register(c, pluginPaths, []string{"trellis"}) } exitStatus, err := c.Run() if err != nil { log.Println(err) } newRelease := <-updateMessageChan if newRelease != nil { msg := fmt.Sprintf( "\n%s %s → %s\n%s", color.YellowString("A new release of trellis-cli is available:"), color.CyanString(version), color.CyanString(newRelease.Version), color.YellowString(newRelease.URL), ) ui.Info(msg) } os.Exit(exitStatus) }
[ "\"TRELLIS_NO_PLUGINS\"", "\"PATH\"" ]
[]
[ "PATH", "TRELLIS_NO_PLUGINS" ]
[]
["PATH", "TRELLIS_NO_PLUGINS"]
go
2
0
Regression/prepare_file_ci.py
# Copyright 2018-2019 Andrew Myers, Luca Fedeli, Maxence Thevenet # Remi Lehe # # This file is part of WarpX. # # License: BSD-3-Clause-LBNL import os # This script modifies `WarpX-test.ini` (which is used for nightly builds) # and creates the file `ci-test.ini` (which is used for continous # integration) # The subtests that are selected are controlled by WARPX_TEST_DIM # The architecture (CPU/GPU) is selected by WARPX_TEST_ARCH import re # Get relevant environment variables arch = os.environ.get('WARPX_TEST_ARCH', 'CPU') ci_regular_cartesian_1d = os.environ.get('WARPX_CI_REGULAR_CARTESIAN_1D') == 'TRUE' ci_regular_cartesian_2d = os.environ.get('WARPX_CI_REGULAR_CARTESIAN_2D') == 'TRUE' ci_regular_cartesian_3d = os.environ.get('WARPX_CI_REGULAR_CARTESIAN_3D') == 'TRUE' ci_psatd = os.environ.get('WARPX_CI_PSATD', 'TRUE') == 'TRUE' ci_python_main = os.environ.get('WARPX_CI_PYTHON_MAIN') == 'TRUE' ci_single_precision = os.environ.get('WARPX_CI_SINGLE_PRECISION') == 'TRUE' ci_rz_or_nompi = os.environ.get('WARPX_CI_RZ_OR_NOMPI') == 'TRUE' ci_qed = os.environ.get('WARPX_CI_QED') == 'TRUE' ci_eb = os.environ.get('WARPX_CI_EB') == 'TRUE' ci_openpmd = os.environ.get('WARPX_CI_OPENPMD') == 'TRUE' ci_ccache = os.environ.get('WARPX_CI_CCACHE') == 'TRUE' ci_num_make_jobs = os.environ.get('WARPX_CI_NUM_MAKE_JOBS', None) # Find the directory in which the tests should be run current_dir = os.getcwd() test_dir = re.sub('warpx/Regression', '', current_dir ) with open('WarpX-tests.ini') as f: text = f.read() # Replace default folder name text = re.sub('/home/regtester/AMReX_RegTesting', test_dir, text) # Remove the web directory text = re.sub('[\w\-\/]*/web', '', text) # Add doComparison = 0 for each test text = re.sub( '\[(?P<name>.*)\]\nbuildDir = ', '[\g<name>]\ndoComparison = 0\nbuildDir = ', text ) # Change compile options when running on GPU if arch == 'GPU': text = re.sub( 'addToCompileString =', 'addToCompileString = USE_GPU=TRUE USE_OMP=FALSE ', text) print('Compiling for %s' %arch) # Extra dependencies if ci_openpmd: text = re.sub('addToCompileString =', 'addToCompileString = USE_OPENPMD=TRUE ', text) # always build with PSATD support (runtime controlled if used) if ci_psatd: text = re.sub('addToCompileString =', 'addToCompileString = USE_PSATD=TRUE ', text) text = re.sub('USE_PSATD=FALSE', '', text) # Ccache if ci_ccache: text = re.sub('addToCompileString =', 'addToCompileString = USE_CCACHE=TRUE ', text) # Add runtime options: # > crash for unused variables # > trap NaNs, divisions by zero, and overflows # > abort upon any warning message by default text = re.sub('runtime_params =', 'runtime_params = amrex.abort_on_unused_inputs=1 '+ 'amrex.fpe_trap_invalid=1 amrex.fpe_trap_zero=1 amrex.fpe_trap_overflow=1 '+ 'warpx.always_warn_immediately=1 warpx.abort_on_warning_threshold=low', text) # Use less/more cores for compiling, e.g. public CI only provides 2 cores if ci_num_make_jobs is not None: text = re.sub( 'numMakeJobs = \d+', 'numMakeJobs = {}'.format(ci_num_make_jobs), text ) # Prevent emails from being sent text = re.sub( 'sendEmailWhenFail = 1', 'sendEmailWhenFail = 0', text ) # Remove Python test (does not compile) text = re.sub( '\[Python_Langmuir\]\n(.+\n)*', '', text) # Remove Langmuir_x/y/z test (too long; not that useful) text = re.sub( '\[Langmuir_[xyz]\]\n(.+\n)*', '', text) # Select the tests to be run # -------------------------- # - Extract test blocks (they are identified by the fact that they contain "inputFile") select_test_regex = r'(\[(.+\n)*inputFile(.+\n)*)' test_blocks = [ match[0] for match in re.findall(select_test_regex, text) ] # - Remove the test blocks from `text` (only the selected ones will be added back) text = re.sub( select_test_regex, '', text ) def select_tests(blocks, match_string_list, do_test): """Remove or keep tests from list in WarpX-tests.ini according to do_test variable""" if do_test not in [True, False]: raise ValueError("do_test must be True or False") if (do_test == False): for match_string in match_string_list: print('Selecting tests without ' + match_string) blocks = [ block for block in blocks if not match_string in block ] else: for match_string in match_string_list: print('Selecting tests with ' + match_string) blocks = [ block for block in blocks if match_string in block ] return blocks if ci_regular_cartesian_1d: test_blocks = select_tests(test_blocks, ['dim = 1'], True) test_blocks = select_tests(test_blocks, ['USE_RZ=TRUE'], False) test_blocks = select_tests(test_blocks, ['PYTHON_MAIN=TRUE'], False) test_blocks = select_tests(test_blocks, ['PRECISION=FLOAT', 'USE_SINGLE_PRECISION_PARTICLES=TRUE'], False) test_blocks = select_tests(test_blocks, ['useMPI = 0'], False) test_blocks = select_tests(test_blocks, ['QED=TRUE'], False) test_blocks = select_tests(test_blocks, ['USE_EB=TRUE'], False) if ci_regular_cartesian_2d: test_blocks = select_tests(test_blocks, ['dim = 2'], True) test_blocks = select_tests(test_blocks, ['USE_RZ=TRUE'], False) test_blocks = select_tests(test_blocks, ['PYTHON_MAIN=TRUE'], False) test_blocks = select_tests(test_blocks, ['PRECISION=FLOAT', 'USE_SINGLE_PRECISION_PARTICLES=TRUE'], False) test_blocks = select_tests(test_blocks, ['useMPI = 0'], False) test_blocks = select_tests(test_blocks, ['QED=TRUE'], False) test_blocks = select_tests(test_blocks, ['USE_EB=TRUE'], False) if ci_regular_cartesian_3d: test_blocks = select_tests(test_blocks, ['dim = 3'], True) test_blocks = select_tests(test_blocks, ['PYTHON_MAIN=TRUE'], False) test_blocks = select_tests(test_blocks, ['PRECISION=FLOAT', 'USE_SINGLE_PRECISION_PARTICLES=TRUE'], False) test_blocks = select_tests(test_blocks, ['useMPI = 0'], False) test_blocks = select_tests(test_blocks, ['QED=TRUE'], False) test_blocks = select_tests(test_blocks, ['USE_EB=TRUE'], False) if ci_python_main: test_blocks = select_tests(test_blocks, ['PYTHON_MAIN=TRUE'], True) test_blocks = select_tests(test_blocks, ['USE_EB=TRUE'], False) if ci_single_precision: test_blocks = select_tests(test_blocks, ['PRECISION=FLOAT', 'USE_SINGLE_PRECISION_PARTICLES=TRUE'], True) if ci_rz_or_nompi: test_blocks = select_tests(test_blocks, ['PYTHON_MAIN=TRUE'], False) block1 = select_tests(test_blocks, ['USE_RZ=TRUE'], True) block2 = select_tests(test_blocks, ['useMPI = 0'], True) test_blocks = block1 + block2 if ci_qed: test_blocks = select_tests(test_blocks, ['QED=TRUE'], True) if ci_eb: test_blocks = select_tests(test_blocks, ['USE_RZ=TRUE'], False) test_blocks = select_tests(test_blocks, ['USE_EB=TRUE'], True) # - Add the selected test blocks to the text text = text + '\n' + '\n'.join(test_blocks) with open('ci-tests.ini', 'w') as f: f.write(text)
[]
[]
[ "WARPX_CI_NUM_MAKE_JOBS", "WARPX_CI_OPENPMD", "WARPX_CI_REGULAR_CARTESIAN_3D", "WARPX_CI_PSATD", "WARPX_CI_REGULAR_CARTESIAN_1D", "WARPX_CI_PYTHON_MAIN", "WARPX_CI_REGULAR_CARTESIAN_2D", "WARPX_CI_RZ_OR_NOMPI", "WARPX_CI_QED", "WARPX_CI_EB", "WARPX_CI_SINGLE_PRECISION", "WARPX_TEST_ARCH", "WARPX_CI_CCACHE" ]
[]
["WARPX_CI_NUM_MAKE_JOBS", "WARPX_CI_OPENPMD", "WARPX_CI_REGULAR_CARTESIAN_3D", "WARPX_CI_PSATD", "WARPX_CI_REGULAR_CARTESIAN_1D", "WARPX_CI_PYTHON_MAIN", "WARPX_CI_REGULAR_CARTESIAN_2D", "WARPX_CI_RZ_OR_NOMPI", "WARPX_CI_QED", "WARPX_CI_EB", "WARPX_CI_SINGLE_PRECISION", "WARPX_TEST_ARCH", "WARPX_CI_CCACHE"]
python
13
0
internal/command/command_test.go
package command import ( "bufio" "bytes" "context" "fmt" "io" "os" "os/exec" "regexp" "strings" "testing" "time" "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCommandTZEnv(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() oldTZ := os.Getenv("TZ") defer os.Setenv("TZ", oldTZ) os.Setenv("TZ", "foobar") buff := &bytes.Buffer{} cmd, err := New(ctx, exec.Command("env"), nil, buff, nil) require.NoError(t, err) require.NoError(t, cmd.Wait()) require.Contains(t, strings.Split(buff.String(), "\n"), "TZ=foobar") } func TestNewCommandExtraEnv(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() extraVar := "FOOBAR=123456" buff := &bytes.Buffer{} cmd, err := New(ctx, exec.Command("/usr/bin/env"), nil, buff, nil, extraVar) require.NoError(t, err) require.NoError(t, cmd.Wait()) require.Contains(t, strings.Split(buff.String(), "\n"), extraVar) } func TestNewCommandProxyEnv(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() testCases := []struct { key string value string }{ { key: "all_proxy", value: "http://localhost:4000", }, { key: "http_proxy", value: "http://localhost:5000", }, { key: "HTTP_PROXY", value: "http://localhost:6000", }, { key: "https_proxy", value: "https://localhost:5000", }, { key: "HTTPS_PROXY", value: "https://localhost:6000", }, { key: "no_proxy", value: "https://excluded:5000", }, { key: "NO_PROXY", value: "https://excluded:5000", }, } for _, tc := range testCases { t.Run(tc.key, func(t *testing.T) { extraVar := fmt.Sprintf("%s=%s", tc.key, tc.value) buff := &bytes.Buffer{} cmd, err := New(ctx, exec.Command("/usr/bin/env"), nil, buff, nil, extraVar) require.NoError(t, err) require.NoError(t, cmd.Wait()) require.Contains(t, strings.Split(buff.String(), "\n"), extraVar) }) } } func TestRejectEmptyContextDone(t *testing.T) { defer func() { p := recover() if p == nil { t.Error("expected panic, got none") return } if _, ok := p.(contextWithoutDonePanic); !ok { panic(p) } }() New(context.Background(), exec.Command("true"), nil, nil, nil) } func TestNewCommandTimeout(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() defer func(ch chan struct{}, t time.Duration) { spawnTokens = ch spawnConfig.Timeout = t }(spawnTokens, spawnConfig.Timeout) // This unbuffered channel will behave like a full/blocked buffered channel. spawnTokens = make(chan struct{}) // Speed up the test by lowering the timeout spawnTimeout := 200 * time.Millisecond spawnConfig.Timeout = spawnTimeout testDeadline := time.After(1 * time.Second) tick := time.After(spawnTimeout / 2) errCh := make(chan error) go func() { _, err := New(ctx, exec.Command("true"), nil, nil, nil) errCh <- err }() var err error timePassed := false wait: for { select { case err = <-errCh: break wait case <-tick: timePassed = true case <-testDeadline: t.Fatal("test timed out") } } require.True(t, timePassed, "time must have passed") require.Error(t, err) require.Contains(t, err.Error(), "process spawn timed out after") } func TestCommand_Wait_interrupts_after_context_timeout(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctx, timeout := context.WithTimeout(ctx, time.Second) defer timeout() cmd, err := New(ctx, exec.CommandContext(ctx, "sleep", "3"), nil, nil, nil) require.NoError(t, err) completed := make(chan error, 1) go func() { completed <- cmd.Wait() }() select { case err := <-completed: require.Error(t, err) s, ok := ExitStatus(err) require.True(t, ok) require.Equal(t, -1, s) case <-time.After(2 * time.Second): require.FailNow(t, "process is running too long") } } func TestNewCommandWithSetupStdin(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() value := "Test value" output := bytes.NewBuffer(nil) cmd, err := New(ctx, exec.Command("cat"), SetupStdin, nil, nil) require.NoError(t, err) _, err = fmt.Fprintf(cmd, "%s", value) require.NoError(t, err) // The output of the `cat` subprocess should exactly match its input _, err = io.CopyN(output, cmd, int64(len(value))) require.NoError(t, err) require.Equal(t, value, output.String()) require.NoError(t, cmd.Wait()) } func TestNewCommandNullInArg(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() _, err := New(ctx, exec.Command("sh", "-c", "hello\x00world"), nil, nil, nil) require.Error(t, err) require.EqualError(t, err, `detected null byte in command argument "hello\x00world"`) } func TestCommandStdErr(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() var stdout bytes.Buffer expectedMessage := `hello world\\nhello world\\nhello world\\nhello world\\nhello world\\n` r, w := io.Pipe() defer r.Close() defer w.Close() logger := logrus.New() logger.SetOutput(w) ctx = ctxlogrus.ToContext(ctx, logrus.NewEntry(logger)) cmd, err := New(ctx, exec.Command("./testdata/stderr_script.sh"), nil, &stdout, nil) require.NoError(t, err) require.Error(t, cmd.Wait()) assert.Empty(t, stdout.Bytes()) b := bufio.NewReader(r) line, err := b.ReadString('\n') require.NoError(t, err) require.Equal(t, expectedMessage, extractMessage(line)) } func TestCommandStdErrLargeOutput(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() var stdout bytes.Buffer r, w := io.Pipe() defer r.Close() defer w.Close() logger := logrus.New() logger.SetOutput(w) ctx = ctxlogrus.ToContext(ctx, logrus.NewEntry(logger)) cmd, err := New(ctx, exec.Command("./testdata/stderr_many_lines.sh"), nil, &stdout, nil) require.NoError(t, err) require.Error(t, cmd.Wait()) assert.Empty(t, stdout.Bytes()) b := bufio.NewReader(r) line, err := b.ReadString('\n') require.NoError(t, err) // the logrus printer prints with %q, so with an escaped newline it will add an extra \ escape to the // output. So for the test we can take out the extra \ since it was logrus that added it, not the command // https://github.com/sirupsen/logrus/blob/master/text_formatter.go#L324 msg := strings.Replace(extractMessage(line), `\\n`, `\n`, -1) require.LessOrEqual(t, len(msg), MaxStderrBytes) } func TestCommandStdErrBinaryNullBytes(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() var stdout bytes.Buffer r, w := io.Pipe() defer r.Close() defer w.Close() logger := logrus.New() logger.SetOutput(w) ctx = ctxlogrus.ToContext(ctx, logrus.NewEntry(logger)) cmd, err := New(ctx, exec.Command("./testdata/stderr_binary_null.sh"), nil, &stdout, nil) require.NoError(t, err) require.Error(t, cmd.Wait()) assert.Empty(t, stdout.Bytes()) b := bufio.NewReader(r) line, err := b.ReadString('\n') require.NoError(t, err) require.NotEmpty(t, extractMessage(line)) } func TestCommandStdErrLongLine(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() var stdout bytes.Buffer r, w := io.Pipe() defer r.Close() defer w.Close() logger := logrus.New() logger.SetOutput(w) ctx = ctxlogrus.ToContext(ctx, logrus.NewEntry(logger)) cmd, err := New(ctx, exec.Command("./testdata/stderr_repeat_a.sh"), nil, &stdout, nil) require.NoError(t, err) require.Error(t, cmd.Wait()) assert.Empty(t, stdout.Bytes()) b := bufio.NewReader(r) line, err := b.ReadString('\n') require.NoError(t, err) require.Contains(t, line, fmt.Sprintf(`%s\\n%s`, strings.Repeat("a", StderrBufferSize), strings.Repeat("b", StderrBufferSize))) } func TestCommandStdErrMaxBytes(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() var stdout bytes.Buffer r, w := io.Pipe() defer r.Close() defer w.Close() logger := logrus.New() logger.SetOutput(w) ctx = ctxlogrus.ToContext(ctx, logrus.NewEntry(logger)) cmd, err := New(ctx, exec.Command("./testdata/stderr_max_bytes_edge_case.sh"), nil, &stdout, nil) require.NoError(t, err) require.Error(t, cmd.Wait()) assert.Empty(t, stdout.Bytes()) b := bufio.NewReader(r) line, err := b.ReadString('\n') require.NoError(t, err) require.NotEmpty(t, extractMessage(line)) } var logMsgRegex = regexp.MustCompile(`msg="(.+)"`) func extractMessage(logMessage string) string { subMatches := logMsgRegex.FindStringSubmatch(logMessage) if len(subMatches) != 2 { return "" } return subMatches[1] } func TestUncancellableContext(t *testing.T) { t.Run("cancellation", func(t *testing.T) { parent, cancel := context.WithCancel(context.Background()) ctx := SuppressCancellation(parent) cancel() require.Equal(t, context.Canceled, parent.Err(), "sanity check: context should be cancelled") require.Nil(t, ctx.Err(), "cancellation of the parent shouldn't propagate via Err") select { case <-ctx.Done(): require.FailNow(t, "cancellation of the parent shouldn't propagate via Done") default: } }) t.Run("timeout", func(t *testing.T) { parent, cancel := context.WithTimeout(context.Background(), time.Nanosecond) defer cancel() ctx := SuppressCancellation(parent) time.Sleep(time.Millisecond) require.Equal(t, context.DeadlineExceeded, parent.Err(), "sanity check: context should be expired after awaiting") require.Nil(t, ctx.Err(), "timeout on the parent shouldn't propagate via Err") select { case <-ctx.Done(): require.FailNow(t, "timeout on the parent shouldn't propagate via Done") default: } _, ok := ctx.Deadline() require.False(t, ok, "no deadline should be set") }) t.Run("re-cancellation", func(t *testing.T) { parent, cancelParent := context.WithCancel(context.Background()) ctx := SuppressCancellation(parent) child, cancelChild := context.WithCancel(ctx) defer cancelChild() cancelParent() select { case <-child.Done(): require.FailNow(t, "uncancellable context should suppress cancellation on the parent") default: // all good } cancelChild() require.Equal(t, context.Canceled, child.Err(), "context derived from cancellable could be cancelled") select { case <-child.Done(): // all good default: require.FailNow(t, "child context should be canceled despite if parent is uncancellable") } }) t.Run("context values are preserved", func(t *testing.T) { type ctxKey string k1 := ctxKey("1") k2 := ctxKey("2") parent, cancel := context.WithCancel(context.Background()) defer cancel() parent = context.WithValue(parent, k1, 1) parent = context.WithValue(parent, k2, "two") ctx := SuppressCancellation(parent) require.Equal(t, 1, ctx.Value(k1)) require.Equal(t, "two", ctx.Value(k2)) cancel() require.Equal(t, context.Canceled, parent.Err(), "sanity check: context should be cancelled") require.Equal(t, 1, ctx.Value(k1), "should be accessible after parent context cancellation") require.Equal(t, "two", ctx.Value(k2)) }) }
[ "\"TZ\"" ]
[]
[ "TZ" ]
[]
["TZ"]
go
1
0
test/e2e/fixtures/e2e_suite.go
package fixtures import ( "context" "encoding/base64" "os" "strings" "time" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" // load authentication plugin for obtaining credentials from cloud providers. _ "k8s.io/client-go/plugin/pkg/client/auth" "github.com/stretchr/testify/suite" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "github.com/argoproj/argo/v2/config" "github.com/argoproj/argo/v2/pkg/apis/workflow" "github.com/argoproj/argo/v2/pkg/client/clientset/versioned" "github.com/argoproj/argo/v2/pkg/client/clientset/versioned/typed/workflow/v1alpha1" "github.com/argoproj/argo/v2/util/kubeconfig" "github.com/argoproj/argo/v2/workflow/hydrator" ) const Namespace = "argo" const Label = "argo-e2e" const defaultTimeout = 30 * time.Second type E2ESuite struct { suite.Suite Config *config.Config Persistence *Persistence RestConfig *rest.Config wfClient v1alpha1.WorkflowInterface wfebClient v1alpha1.WorkflowEventBindingInterface wfTemplateClient v1alpha1.WorkflowTemplateInterface cwfTemplateClient v1alpha1.ClusterWorkflowTemplateInterface cronClient v1alpha1.CronWorkflowInterface KubeClient kubernetes.Interface hydrator hydrator.Interface } func (s *E2ESuite) SetupSuite() { var err error s.RestConfig, err = kubeconfig.DefaultRestConfig() s.CheckError(err) s.KubeClient, err = kubernetes.NewForConfig(s.RestConfig) s.CheckError(err) configController := config.NewController(Namespace, "workflow-controller-configmap", s.KubeClient, config.EmptyConfigFunc) ctx := context.Background() c, err := configController.Get(ctx) s.CheckError(err) s.Config = c.(*config.Config) s.wfClient = versioned.NewForConfigOrDie(s.RestConfig).ArgoprojV1alpha1().Workflows(Namespace) s.wfebClient = versioned.NewForConfigOrDie(s.RestConfig).ArgoprojV1alpha1().WorkflowEventBindings(Namespace) s.wfTemplateClient = versioned.NewForConfigOrDie(s.RestConfig).ArgoprojV1alpha1().WorkflowTemplates(Namespace) s.cronClient = versioned.NewForConfigOrDie(s.RestConfig).ArgoprojV1alpha1().CronWorkflows(Namespace) s.Persistence = newPersistence(s.KubeClient, s.Config) s.hydrator = hydrator.New(s.Persistence.offloadNodeStatusRepo) s.cwfTemplateClient = versioned.NewForConfigOrDie(s.RestConfig).ArgoprojV1alpha1().ClusterWorkflowTemplates() } func (s *E2ESuite) TearDownSuite() { s.Persistence.Close() } func (s *E2ESuite) BeforeTest(string, string) { s.DeleteResources() } var foreground = metav1.DeletePropagationForeground var background = metav1.DeletePropagationBackground func (s *E2ESuite) DeleteResources() { hasTestLabel := metav1.ListOptions{LabelSelector: Label} resources := []schema.GroupVersionResource{ {Group: workflow.Group, Version: workflow.Version, Resource: workflow.CronWorkflowPlural}, {Group: workflow.Group, Version: workflow.Version, Resource: workflow.WorkflowPlural}, {Group: workflow.Group, Version: workflow.Version, Resource: workflow.WorkflowTemplatePlural}, {Group: workflow.Group, Version: workflow.Version, Resource: workflow.ClusterWorkflowTemplatePlural}, {Group: workflow.Group, Version: workflow.Version, Resource: workflow.WorkflowEventBindingPlural}, {Group: workflow.Group, Version: workflow.Version, Resource: "sensors"}, {Group: workflow.Group, Version: workflow.Version, Resource: "eventsources"}, {Version: "v1", Resource: "resourcequotas"}, {Version: "v1", Resource: "configmaps"}, } ctx := context.Background() for _, r := range resources { err := s.dynamicFor(r).DeleteCollection(ctx, metav1.DeleteOptions{PropagationPolicy: &background}, hasTestLabel) s.CheckError(err) } // delete archived workflows from the archive if s.Persistence.IsEnabled() { archive := s.Persistence.workflowArchive parse, err := labels.ParseToRequirements(Label) s.CheckError(err) workflows, err := archive.ListWorkflows(Namespace, time.Time{}, time.Time{}, parse, 0, 0) s.CheckError(err) for _, w := range workflows { err := archive.DeleteWorkflow(string(w.UID)) s.CheckError(err) } } for _, r := range resources { for { list, err := s.dynamicFor(r).List(ctx, hasTestLabel) s.CheckError(err) if len(list.Items) == 0 { break } time.Sleep(100 * time.Millisecond) } } } func (s *E2ESuite) NeedsCI() { if os.Getenv("CI") != "true" { s.T().Skip("test needs CI") } } func (s *E2ESuite) NeedsOffloading() { if !s.Persistence.IsEnabled() { s.T().Skip("test needs offloading, but persistence not enabled") } } func (s *E2ESuite) dynamicFor(r schema.GroupVersionResource) dynamic.ResourceInterface { resourceInterface := dynamic.NewForConfigOrDie(s.RestConfig).Resource(r) if r.Resource == workflow.ClusterWorkflowTemplatePlural { return resourceInterface } return resourceInterface.Namespace(Namespace) } func (s *E2ESuite) CheckError(err error) { s.T().Helper() if err != nil { s.T().Fatal(err) } } func (s *E2ESuite) GetBasicAuthToken() string { if s.RestConfig.Username == "" { return "" } auth := s.RestConfig.Username + ":" + s.RestConfig.Password return base64.StdEncoding.EncodeToString([]byte(auth)) } func (s *E2ESuite) GetServiceAccountToken() (string, error) { // create the clientset clientset, err := kubernetes.NewForConfig(s.RestConfig) if err != nil { return "", err } ctx := context.Background() secretList, err := clientset.CoreV1().Secrets("argo").List(ctx, metav1.ListOptions{}) if err != nil { return "", err } for _, sec := range secretList.Items { if strings.HasPrefix(sec.Name, "argo-server-token") { return string(sec.Data["token"]), nil } } return "", nil } func (s *E2ESuite) Given() *Given { return &Given{ t: s.T(), client: s.wfClient, wfebClient: s.wfebClient, wfTemplateClient: s.wfTemplateClient, cwfTemplateClient: s.cwfTemplateClient, cronClient: s.cronClient, hydrator: s.hydrator, kubeClient: s.KubeClient, } }
[ "\"CI\"" ]
[]
[ "CI" ]
[]
["CI"]
go
1
0
FakeFridgeEvents.py
from simple_salesforce import Salesforce from dotenv import load_dotenv import os import time import random BASE_DIR='./' load_dotenv(os.path.join(BASE_DIR, '.env.iotxporg')) USERNAME=os.getenv('USERNAME') PASSWORD=os.getenv('PASSWORD') SECURITY_TOKEN=os.getenv('SECURITY_TOKEN') print("uname %s pw %s token %s" % (USERNAME, PASSWORD, SECURITY_TOKEN)) sf = Salesforce(username=USERNAME, password=PASSWORD, security_token=SECURITY_TOKEN) print(sf); def read_temp(): temp_c = 27.0 + (25*random.random()) temp_f = temp_c * 9.0 / 5.0 + 32.0 return temp_c while True: print(read_temp()) data = [{'serial_no__c': '1001','door_open__c': 'false','temp__c':read_temp()}] print("Data sent: ") for x in data: print("data item: ", x) sf.Refrigerator_Event__e.create(data[0]) time.sleep(15) print("Platform Event Sent: " )
[]
[]
[ "USERNAME", "PASSWORD", "SECURITY_TOKEN" ]
[]
["USERNAME", "PASSWORD", "SECURITY_TOKEN"]
python
3
0
tasks/teardown_stack.py
''' Clean-up deployed aws resources ''' import os import sys import traceback import cloudformation as cfn import keypair from cloudformation import load_yaml_file # pylint: disable=no-name-in-module print('Loading teardown function ....') def main(configs): ''' clean-up deployed stacks ''' setup_data = load_yaml_file(configs) print('Listing configuration to delete Stacks in specified regions ...') try: for single_setup_data in setup_data: # Extract region and environemnt to deploy stack stack_region = single_setup_data['region'] environment = single_setup_data['parameters']['Environment'] print(f'Region to delete resource = {stack_region}') print(f'Environment to delete resource = {environment}') # Extract resource name and region resource_name = single_setup_data['resource_name'] stack_name = environment+'-'+resource_name print(f'Stack name to be deleted = {stack_name}') # Delete non-empty bucket objects if stack_name == 'DEMO-ANCHORE-CLI-PIPELINE': bucket_name = single_setup_data['parameters']['BucketName'] print(f'Bucket to delete objects = {bucket_name}') os.system(f"aws s3 rm s3://{bucket_name} --recursive") print(f'Bucket - {bucket_name} object removed') # Delete Stacks stacks = cfn.DeploymentManager(single_setup_data) # pylint: disable=no-member stacks.delete_stack(stack_name) print(f'Tearing down deployed stack {stack_name} ...') print('Teardown Complete!!!') except Exception as exc: # pylint: disable=broad-except print(f'Function failed due to exception. {exc}') traceback.print_exc() print('Stack Teardown Failed!!!') # Delete keypair keypair.delete_keypair(os.environ.get('AWS_DEFAULT_REGION'), 'anchore_demo') return "Teardown Complete!!!" if __name__ == "__main__": main(f'{sys.argv[1]}')
[]
[]
[ "AWS_DEFAULT_REGION" ]
[]
["AWS_DEFAULT_REGION"]
python
1
0
palantr/wsgi.py
""" WSGI config for palantr 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', 'palantr.settings') application = get_wsgi_application()
[]
[]
[]
[]
[]
python
0
0
google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerOptionsTest.java
/* * Copyright 2017 Google LLC * * 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 com.google.cloud.spanner; import static com.google.common.truth.Truth.assertThat; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; import com.google.api.gax.grpc.GrpcCallContext; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ServerStreamingCallSettings; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.cloud.NoCredentials; import com.google.cloud.ServiceOptions; import com.google.cloud.TransportOptions; import com.google.cloud.spanner.SpannerOptions.SpannerCallContextTimeoutConfigurator; import com.google.cloud.spanner.admin.database.v1.stub.DatabaseAdminStubSettings; import com.google.cloud.spanner.admin.instance.v1.stub.InstanceAdminStubSettings; import com.google.cloud.spanner.v1.stub.SpannerStubSettings; import com.google.common.base.Strings; import com.google.spanner.v1.BatchCreateSessionsRequest; import com.google.spanner.v1.BeginTransactionRequest; import com.google.spanner.v1.CommitRequest; import com.google.spanner.v1.CreateSessionRequest; import com.google.spanner.v1.DeleteSessionRequest; import com.google.spanner.v1.ExecuteBatchDmlRequest; import com.google.spanner.v1.ExecuteSqlRequest; import com.google.spanner.v1.ExecuteSqlRequest.QueryOptions; import com.google.spanner.v1.GetSessionRequest; import com.google.spanner.v1.ListSessionsRequest; import com.google.spanner.v1.PartitionQueryRequest; import com.google.spanner.v1.PartitionReadRequest; import com.google.spanner.v1.ReadRequest; import com.google.spanner.v1.RollbackRequest; import com.google.spanner.v1.SpannerGrpc; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; import org.threeten.bp.Duration; /** Unit tests for {@link com.google.cloud.spanner.SpannerOptions}. */ @RunWith(JUnit4.class) public class SpannerOptionsTest { @Test public void defaultBuilder() { // We need to set the project id since in test environment we cannot obtain a default project // id. SpannerOptions options = SpannerOptions.newBuilder().setProjectId("test-project").build(); if (Strings.isNullOrEmpty(System.getenv("SPANNER_EMULATOR_HOST"))) { assertThat(options.getHost()).isEqualTo("https://spanner.googleapis.com"); } else { assertThat(options.getHost()).isEqualTo("http://" + System.getenv("SPANNER_EMULATOR_HOST")); } assertThat(options.getPrefetchChunks()).isEqualTo(4); assertThat(options.getSessionLabels()).isNull(); } @Test public void builder() { String host = "http://localhost:8000/"; String projectId = "test-project"; Map<String, String> labels = new HashMap<>(); labels.put("env", "dev"); SpannerOptions options = SpannerOptions.newBuilder() .setHost(host) .setProjectId(projectId) .setPrefetchChunks(2) .setSessionLabels(labels) .build(); assertThat(options.getHost()).isEqualTo(host); assertThat(options.getProjectId()).isEqualTo(projectId); assertThat(options.getPrefetchChunks()).isEqualTo(2); assertThat(options.getSessionLabels()).containsExactlyEntriesIn(labels); } @Test public void testSpannerDefaultRetrySettings() { RetrySettings witRetryPolicy1 = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(250L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(32000L)) .setInitialRpcTimeout(Duration.ofMillis(3600000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(3600000L)) .setTotalTimeout(Duration.ofMillis(3600000L)) .build(); RetrySettings witRetryPolicy2 = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(250L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(32000L)) .setInitialRpcTimeout(Duration.ofMillis(60000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(60000L)) .setTotalTimeout(Duration.ofMillis(60000L)) .build(); RetrySettings witRetryPolicy3 = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(250L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(32000L)) .setInitialRpcTimeout(Duration.ofMillis(30000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(30000L)) .setTotalTimeout(Duration.ofMillis(30000L)) .build(); RetrySettings noRetry1 = RetrySettings.newBuilder() .setInitialRpcTimeout(Duration.ofMillis(3600000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(3600000L)) .setTotalTimeout(Duration.ofMillis(3600000L)) .build(); SpannerOptions options = SpannerOptions.newBuilder().setProjectId("test-project").build(); SpannerStubSettings stubSettings = options.getSpannerStubSettings(); List<? extends UnaryCallSettings<?, ?>> callsWithRetry1 = Arrays.asList(stubSettings.listSessionsSettings(), stubSettings.commitSettings()); List<? extends UnaryCallSettings<?, ?>> callsWithRetry2 = Arrays.asList(stubSettings.batchCreateSessionsSettings()); List<? extends UnaryCallSettings<?, ?>> callsWithRetry3 = Arrays.asList( stubSettings.createSessionSettings(), stubSettings.getSessionSettings(), stubSettings.deleteSessionSettings(), stubSettings.executeSqlSettings(), stubSettings.executeBatchDmlSettings(), stubSettings.readSettings(), stubSettings.beginTransactionSettings(), stubSettings.rollbackSettings(), stubSettings.partitionQuerySettings(), stubSettings.partitionReadSettings()); List<? extends ServerStreamingCallSettings<?, ?>> callsWithNoRetry1 = Arrays.asList( stubSettings.executeStreamingSqlSettings(), stubSettings.streamingReadSettings()); for (UnaryCallSettings<?, ?> callSettings : callsWithRetry1) { assertThat(callSettings.getRetrySettings()).isEqualTo(witRetryPolicy1); } for (UnaryCallSettings<?, ?> callSettings : callsWithRetry2) { assertThat(callSettings.getRetrySettings()).isEqualTo(witRetryPolicy2); } for (UnaryCallSettings<?, ?> callSettings : callsWithRetry3) { assertThat(callSettings.getRetrySettings()).isEqualTo(witRetryPolicy3); } for (ServerStreamingCallSettings<?, ?> callSettings : callsWithNoRetry1) { assertThat(callSettings.getRetrySettings()).isEqualTo(noRetry1); } } @Test public void testSpannerCustomRetrySettings() { RetrySettings retrySettings = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofSeconds(9999L)) .setRetryDelayMultiplier(9999.99D) .setMaxRetryDelay(Duration.ofSeconds(9999L)) .setInitialRpcTimeout(Duration.ofSeconds(9999L)) .setRpcTimeoutMultiplier(9999.99D) .setMaxRpcTimeout(Duration.ofSeconds(9999L)) .setTotalTimeout(Duration.ofSeconds(9999L)) .build(); SpannerOptions.Builder builder = SpannerOptions.newBuilder().setProjectId("test-project"); SpannerStubSettings.Builder stubSettingsBuilder = builder.getSpannerStubSettingsBuilder(); List<? extends UnaryCallSettings.Builder<?, ?>> unaryCallSettingsBuilders = Arrays.asList( stubSettingsBuilder.beginTransactionSettings(), stubSettingsBuilder.createSessionSettings(), stubSettingsBuilder.deleteSessionSettings(), stubSettingsBuilder.executeBatchDmlSettings(), stubSettingsBuilder.executeSqlSettings(), stubSettingsBuilder.getSessionSettings(), stubSettingsBuilder.listSessionsSettings(), stubSettingsBuilder.partitionQuerySettings(), stubSettingsBuilder.partitionReadSettings(), stubSettingsBuilder.readSettings(), stubSettingsBuilder.rollbackSettings(), stubSettingsBuilder.commitSettings()); for (UnaryCallSettings.Builder<?, ?> callSettingsBuilder : unaryCallSettingsBuilders) { callSettingsBuilder.setRetrySettings(retrySettings); } List<? extends ServerStreamingCallSettings.Builder<?, ?>> streamingCallSettingsBuilders = Arrays.asList( stubSettingsBuilder.executeStreamingSqlSettings(), stubSettingsBuilder.streamingReadSettings()); for (ServerStreamingCallSettings.Builder<?, ?> callSettingsBuilder : streamingCallSettingsBuilders) { callSettingsBuilder.setRetrySettings(retrySettings); } SpannerOptions options = builder.build(); SpannerStubSettings stubSettings = options.getSpannerStubSettings(); List<? extends UnaryCallSettings<?, ?>> callsWithDefaultSettings = Arrays.asList( stubSettings.beginTransactionSettings(), stubSettings.createSessionSettings(), stubSettings.deleteSessionSettings(), stubSettings.executeBatchDmlSettings(), stubSettings.executeSqlSettings(), stubSettings.getSessionSettings(), stubSettings.listSessionsSettings(), stubSettings.partitionQuerySettings(), stubSettings.partitionReadSettings(), stubSettings.readSettings(), stubSettings.rollbackSettings(), stubSettings.commitSettings()); List<? extends ServerStreamingCallSettings<?, ?>> callsWithStreamingSettings = Arrays.asList( stubSettings.executeStreamingSqlSettings(), stubSettings.streamingReadSettings()); for (UnaryCallSettings<?, ?> callSettings : callsWithDefaultSettings) { assertThat(callSettings.getRetrySettings()).isEqualTo(retrySettings); } for (ServerStreamingCallSettings<?, ?> callSettings : callsWithStreamingSettings) { assertThat(callSettings.getRetrySettings()).isEqualTo(retrySettings); } } @Test public void testDatabaseAdminDefaultRetrySettings() { RetrySettings withRetryPolicy1 = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(1000L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(32000L)) .setInitialRpcTimeout(Duration.ofMillis(3600000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(3600000L)) .setTotalTimeout(Duration.ofMillis(3600000L)) .build(); RetrySettings withRetryPolicy2 = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(1000L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(32000L)) .setInitialRpcTimeout(Duration.ofMillis(30000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(30000L)) .setTotalTimeout(Duration.ofMillis(30000L)) .build(); RetrySettings noRetryPolicy2 = RetrySettings.newBuilder() .setInitialRpcTimeout(Duration.ofMillis(30000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(30000L)) .setTotalTimeout(Duration.ofMillis(30000L)) .build(); SpannerOptions options = SpannerOptions.newBuilder().setProjectId("test-project").build(); DatabaseAdminStubSettings stubSettings = options.getDatabaseAdminStubSettings(); List<? extends UnaryCallSettings<?, ?>> callsWithRetryPolicy1 = Arrays.asList( stubSettings.dropDatabaseSettings(), stubSettings.getDatabaseSettings(), stubSettings.getDatabaseDdlSettings()); List<? extends UnaryCallSettings<?, ?>> callsWithRetryPolicy2 = Arrays.asList(stubSettings.getIamPolicySettings()); List<? extends UnaryCallSettings<?, ?>> callsWithNoRetry2 = Arrays.asList( stubSettings.setIamPolicySettings(), stubSettings.testIamPermissionsSettings()); for (UnaryCallSettings<?, ?> callSettings : callsWithRetryPolicy1) { assertThat(callSettings.getRetrySettings()).isEqualTo(withRetryPolicy1); } for (UnaryCallSettings<?, ?> callSettings : callsWithRetryPolicy2) { assertThat(callSettings.getRetrySettings()).isEqualTo(withRetryPolicy2); } for (UnaryCallSettings<?, ?> callSettings : callsWithNoRetry2) { assertThat(callSettings.getRetrySettings()).isEqualTo(noRetryPolicy2); } } @Test public void testDatabaseAdminCustomRetrySettings() { RetrySettings retrySettings = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofSeconds(9999L)) .setRetryDelayMultiplier(9999.99D) .setMaxRetryDelay(Duration.ofSeconds(9999L)) .setInitialRpcTimeout(Duration.ofSeconds(9999L)) .setRpcTimeoutMultiplier(9999.99D) .setMaxRpcTimeout(Duration.ofSeconds(9999L)) .setTotalTimeout(Duration.ofSeconds(9999L)) .build(); SpannerOptions.Builder builder = SpannerOptions.newBuilder().setProjectId("test-project"); DatabaseAdminStubSettings.Builder stubSettingsBuilder = builder.getDatabaseAdminStubSettingsBuilder(); List<? extends UnaryCallSettings.Builder<?, ?>> unaryCallSettingsBuilders = Arrays.asList( stubSettingsBuilder.dropDatabaseSettings(), stubSettingsBuilder.getDatabaseDdlSettings(), stubSettingsBuilder.getDatabaseSettings()); for (UnaryCallSettings.Builder<?, ?> callSettingsBuilder : unaryCallSettingsBuilders) { callSettingsBuilder.setRetrySettings(retrySettings); } SpannerOptions options = builder.build(); DatabaseAdminStubSettings stubSettings = options.getDatabaseAdminStubSettings(); List<? extends UnaryCallSettings<?, ?>> callsWithDefaultSettings = Arrays.asList( stubSettings.dropDatabaseSettings(), stubSettings.getDatabaseDdlSettings(), stubSettings.getDatabaseSettings()); for (UnaryCallSettings<?, ?> callSettings : callsWithDefaultSettings) { assertThat(callSettings.getRetrySettings()).isEqualTo(retrySettings); } } @Test public void testInstanceAdminDefaultRetrySettings() { RetrySettings withRetryPolicy1 = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(1000L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(32000L)) .setInitialRpcTimeout(Duration.ofMillis(3600000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(3600000L)) .setTotalTimeout(Duration.ofMillis(3600000L)) .build(); RetrySettings withRetryPolicy2 = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(1000L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(32000L)) .setInitialRpcTimeout(Duration.ofMillis(30000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(30000L)) .setTotalTimeout(Duration.ofMillis(30000L)) .build(); RetrySettings noRetryPolicy1 = RetrySettings.newBuilder() .setInitialRpcTimeout(Duration.ofMillis(3600000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(3600000L)) .setTotalTimeout(Duration.ofMillis(3600000L)) .build(); RetrySettings noRetryPolicy2 = RetrySettings.newBuilder() .setInitialRpcTimeout(Duration.ofMillis(30000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(30000L)) .setTotalTimeout(Duration.ofMillis(30000L)) .build(); SpannerOptions options = SpannerOptions.newBuilder().setProjectId("test-project").build(); InstanceAdminStubSettings stubSettings = options.getInstanceAdminStubSettings(); List<? extends UnaryCallSettings<?, ?>> callsWithRetryPolicy1 = Arrays.asList( stubSettings.getInstanceConfigSettings(), stubSettings.listInstanceConfigsSettings(), stubSettings.deleteInstanceSettings(), stubSettings.getInstanceSettings(), stubSettings.listInstancesSettings()); List<? extends UnaryCallSettings<?, ?>> callsWithRetryPolicy2 = Arrays.asList(stubSettings.getIamPolicySettings()); List<? extends UnaryCallSettings<?, ?>> callsWithNoRetryPolicy1 = Arrays.asList(stubSettings.createInstanceSettings(), stubSettings.updateInstanceSettings()); List<? extends UnaryCallSettings<?, ?>> callsWithNoRetryPolicy2 = Arrays.asList( stubSettings.setIamPolicySettings(), stubSettings.testIamPermissionsSettings()); for (UnaryCallSettings<?, ?> callSettings : callsWithRetryPolicy1) { assertThat(callSettings.getRetrySettings()).isEqualTo(withRetryPolicy1); } for (UnaryCallSettings<?, ?> callSettings : callsWithRetryPolicy2) { assertThat(callSettings.getRetrySettings()).isEqualTo(withRetryPolicy2); } for (UnaryCallSettings<?, ?> callSettings : callsWithNoRetryPolicy1) { assertThat(callSettings.getRetrySettings()).isEqualTo(noRetryPolicy1); } for (UnaryCallSettings<?, ?> callSettings : callsWithNoRetryPolicy2) { assertThat(callSettings.getRetrySettings()).isEqualTo(noRetryPolicy2); } } @Test public void testInstanceAdminCustomRetrySettings() { RetrySettings retrySettings = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofSeconds(9999L)) .setRetryDelayMultiplier(9999.99D) .setMaxRetryDelay(Duration.ofSeconds(9999L)) .setInitialRpcTimeout(Duration.ofSeconds(9999L)) .setRpcTimeoutMultiplier(9999.99D) .setMaxRpcTimeout(Duration.ofSeconds(9999L)) .setTotalTimeout(Duration.ofSeconds(9999L)) .build(); SpannerOptions.Builder builder = SpannerOptions.newBuilder().setProjectId("test-project"); InstanceAdminStubSettings.Builder stubSettingsBuilder = builder.getInstanceAdminStubSettingsBuilder(); List<? extends UnaryCallSettings.Builder<?, ?>> unaryCallSettingsBuilders = Arrays.asList( stubSettingsBuilder.deleteInstanceSettings(), stubSettingsBuilder.getInstanceConfigSettings(), stubSettingsBuilder.getInstanceSettings(), stubSettingsBuilder.listInstanceConfigsSettings(), stubSettingsBuilder.listInstancesSettings()); for (UnaryCallSettings.Builder<?, ?> callSettingsBuilder : unaryCallSettingsBuilders) { callSettingsBuilder.setRetrySettings(retrySettings); } SpannerOptions options = builder.build(); InstanceAdminStubSettings stubSettings = options.getInstanceAdminStubSettings(); List<? extends UnaryCallSettings<?, ?>> callsWithDefaultSettings = Arrays.asList( stubSettings.getInstanceConfigSettings(), stubSettings.listInstanceConfigsSettings(), stubSettings.deleteInstanceSettings(), stubSettings.getInstanceSettings(), stubSettings.listInstancesSettings()); for (UnaryCallSettings<?, ?> callSettings : callsWithDefaultSettings) { assertThat(callSettings.getRetrySettings()).isEqualTo(retrySettings); } } @Test public void testInvalidTransport() { try { SpannerOptions.newBuilder().setTransportOptions(Mockito.mock(TransportOptions.class)); fail("Expected exception"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage()).isNotNull(); } } @Test public void testInvalidSessionLabels() { Map<String, String> labels = new HashMap<>(); labels.put("env", null); try { SpannerOptions.newBuilder().setSessionLabels(labels); fail("Expected exception"); } catch (NullPointerException ex) { assertThat(ex.getMessage()).isNotNull(); } } @Test public void testNullSessionLabels() { try { SpannerOptions.newBuilder().setSessionLabels(null); fail("Expected exception"); } catch (NullPointerException ex) { assertThat(ex.getMessage()).isNotNull(); } } @Test public void testDoNotCacheClosedSpannerInstance() { SpannerOptions options = SpannerOptions.newBuilder() .setProjectId("[PROJECT]") .setCredentials(NoCredentials.getInstance()) .build(); // Getting a service twice should give the same instance. Spanner service1 = options.getService(); Spanner service2 = options.getService(); assertThat(service1 == service2, is(true)); assertThat(service1.isClosed()).isFalse(); // Closing a service instance should cause the SpannerOptions to create a new service. service1.close(); Spanner service3 = options.getService(); assertThat(service3 == service1, is(false)); assertThat(service1.isClosed()).isTrue(); assertThat(service3.isClosed()).isFalse(); ; // Getting another service from the SpannerOptions should return the new cached instance. Spanner service4 = options.getService(); assertThat(service3 == service4, is(true)); assertThat(service3.isClosed()).isFalse(); service3.close(); } @Test public void testSetClientLibToken() { final String jdbcToken = "sp-jdbc"; final String hibernateToken = "sp-hib"; SpannerOptions options = SpannerOptions.newBuilder() .setProjectId("some-project") .setCredentials(NoCredentials.getInstance()) .setClientLibToken(jdbcToken) .build(); assertThat(options.getClientLibToken()).isEqualTo(jdbcToken); options = SpannerOptions.newBuilder() .setProjectId("some-project") .setCredentials(NoCredentials.getInstance()) .setClientLibToken(hibernateToken) .build(); assertThat(options.getClientLibToken()).isEqualTo(hibernateToken); options = SpannerOptions.newBuilder() .setProjectId("some-project") .setCredentials(NoCredentials.getInstance()) .build(); assertThat(options.getClientLibToken()).isEqualTo(ServiceOptions.getGoogApiClientLibName()); } @Test(expected = IllegalArgumentException.class) public void testSetInvalidClientLibToken() { SpannerOptions.newBuilder() .setProjectId("some-project") .setCredentials(NoCredentials.getInstance()) .setClientLibToken("foo"); } @Test public void testSetEmulatorHostWithoutProtocol() { // If the host doesn't have a protocol as a prefix, it will automatically be prefixed with // "http://". SpannerOptions options = SpannerOptions.newBuilder() .setProjectId("[PROJECT]") .setEmulatorHost("localhost:1234") .build(); assertThat(options.getHost()).isEqualTo("http://localhost:1234"); assertThat(options.getEndpoint()).isEqualTo("localhost:1234"); } @Test public void testSetEmulatorHostWithProtocol() { // If the host has a protocol, it should not be modified. SpannerOptions options = SpannerOptions.newBuilder() .setProjectId("[PROJECT]") .setEmulatorHost("http://localhost:1234") .build(); assertThat(options.getHost()).isEqualTo("http://localhost:1234"); assertThat(options.getEndpoint()).isEqualTo("localhost:1234"); } @Test public void testDefaultQueryOptions() { SpannerOptions.useEnvironment( new SpannerOptions.SpannerEnvironment() { @Override public String getOptimizerVersion() { return ""; } }); SpannerOptions options = SpannerOptions.newBuilder() .setDefaultQueryOptions( DatabaseId.of("p", "i", "d"), QueryOptions.newBuilder().setOptimizerVersion("1").build()) .setProjectId("p") .setCredentials(NoCredentials.getInstance()) .build(); assertThat(options.getDefaultQueryOptions(DatabaseId.of("p", "i", "d"))) .isEqualTo(QueryOptions.newBuilder().setOptimizerVersion("1").build()); assertThat(options.getDefaultQueryOptions(DatabaseId.of("p", "i", "o"))) .isEqualTo(QueryOptions.getDefaultInstance()); // Now simulate that the user has set an environment variable for the query optimizer version. SpannerOptions.useEnvironment( new SpannerOptions.SpannerEnvironment() { @Override public String getOptimizerVersion() { return "2"; } }); // Create options with '1' as the default query optimizer version. This should be overridden by // the environment variable. options = SpannerOptions.newBuilder() .setDefaultQueryOptions( DatabaseId.of("p", "i", "d"), QueryOptions.newBuilder().setOptimizerVersion("1").build()) .setProjectId("p") .setCredentials(NoCredentials.getInstance()) .build(); assertThat(options.getDefaultQueryOptions(DatabaseId.of("p", "i", "d"))) .isEqualTo(QueryOptions.newBuilder().setOptimizerVersion("2").build()); assertThat(options.getDefaultQueryOptions(DatabaseId.of("p", "i", "o"))) .isEqualTo(QueryOptions.newBuilder().setOptimizerVersion("2").build()); } @Test public void testCompressorName() { assertThat( SpannerOptions.newBuilder() .setProjectId("p") .setCompressorName("gzip") .build() .getCompressorName()) .isEqualTo("gzip"); assertThat( SpannerOptions.newBuilder() .setProjectId("p") .setCompressorName("identity") .build() .getCompressorName()) .isEqualTo("identity"); assertThat( SpannerOptions.newBuilder() .setProjectId("p") .setCompressorName(null) .build() .getCompressorName()) .isNull(); try { SpannerOptions.newBuilder().setCompressorName("foo"); fail("missing expected exception"); } catch (IllegalArgumentException e) { // ignore, this is the expected exception. } } @Test public void testSpannerCallContextTimeoutConfigurator_NullValues() { SpannerCallContextTimeoutConfigurator configurator = SpannerCallContextTimeoutConfigurator.create(); ApiCallContext inputCallContext = GrpcCallContext.createDefault(); assertThat( configurator.configure( inputCallContext, BatchCreateSessionsRequest.getDefaultInstance(), SpannerGrpc.getBatchCreateSessionsMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, CreateSessionRequest.getDefaultInstance(), SpannerGrpc.getCreateSessionMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, DeleteSessionRequest.getDefaultInstance(), SpannerGrpc.getDeleteSessionMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, GetSessionRequest.getDefaultInstance(), SpannerGrpc.getGetSessionMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, DeleteSessionRequest.getDefaultInstance(), SpannerGrpc.getDeleteSessionMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, ListSessionsRequest.getDefaultInstance(), SpannerGrpc.getListSessionsMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, BeginTransactionRequest.getDefaultInstance(), SpannerGrpc.getBeginTransactionMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, CommitRequest.getDefaultInstance(), SpannerGrpc.getCommitMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, RollbackRequest.getDefaultInstance(), SpannerGrpc.getRollbackMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, ExecuteSqlRequest.getDefaultInstance(), SpannerGrpc.getExecuteSqlMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, ExecuteSqlRequest.getDefaultInstance(), SpannerGrpc.getExecuteStreamingSqlMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, ExecuteBatchDmlRequest.getDefaultInstance(), SpannerGrpc.getExecuteBatchDmlMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, ReadRequest.getDefaultInstance(), SpannerGrpc.getReadMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, ReadRequest.getDefaultInstance(), SpannerGrpc.getStreamingReadMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, PartitionQueryRequest.getDefaultInstance(), SpannerGrpc.getPartitionQueryMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, PartitionReadRequest.getDefaultInstance(), SpannerGrpc.getPartitionReadMethod())) .isNull(); } @Test public void testSpannerCallContextTimeoutConfigurator_WithTimeouts() { SpannerCallContextTimeoutConfigurator configurator = SpannerCallContextTimeoutConfigurator.create(); configurator.withBatchUpdateTimeout(Duration.ofSeconds(1L)); configurator.withCommitTimeout(Duration.ofSeconds(2L)); configurator.withExecuteQueryTimeout(Duration.ofSeconds(3L)); configurator.withExecuteUpdateTimeout(Duration.ofSeconds(4L)); configurator.withPartitionQueryTimeout(Duration.ofSeconds(5L)); configurator.withPartitionReadTimeout(Duration.ofSeconds(6L)); configurator.withReadTimeout(Duration.ofSeconds(7L)); configurator.withRollbackTimeout(Duration.ofSeconds(8L)); ApiCallContext inputCallContext = GrpcCallContext.createDefault(); assertThat( configurator.configure( inputCallContext, BatchCreateSessionsRequest.getDefaultInstance(), SpannerGrpc.getBatchCreateSessionsMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, CreateSessionRequest.getDefaultInstance(), SpannerGrpc.getCreateSessionMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, DeleteSessionRequest.getDefaultInstance(), SpannerGrpc.getDeleteSessionMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, GetSessionRequest.getDefaultInstance(), SpannerGrpc.getGetSessionMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, DeleteSessionRequest.getDefaultInstance(), SpannerGrpc.getDeleteSessionMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, ListSessionsRequest.getDefaultInstance(), SpannerGrpc.getListSessionsMethod())) .isNull(); assertThat( configurator.configure( inputCallContext, BeginTransactionRequest.getDefaultInstance(), SpannerGrpc.getBeginTransactionMethod())) .isNull(); assertThat( configurator .configure( inputCallContext, CommitRequest.getDefaultInstance(), SpannerGrpc.getCommitMethod()) .getTimeout()) .isEqualTo(Duration.ofSeconds(2L)); assertThat( configurator .configure( inputCallContext, RollbackRequest.getDefaultInstance(), SpannerGrpc.getRollbackMethod()) .getTimeout()) .isEqualTo(Duration.ofSeconds(8L)); assertThat( configurator.configure( inputCallContext, ExecuteSqlRequest.getDefaultInstance(), SpannerGrpc.getExecuteSqlMethod())) .isNull(); assertThat( configurator .configure( inputCallContext, ExecuteSqlRequest.getDefaultInstance(), SpannerGrpc.getExecuteStreamingSqlMethod()) .getTimeout()) .isEqualTo(Duration.ofSeconds(3L)); assertThat( configurator .configure( inputCallContext, ExecuteBatchDmlRequest.getDefaultInstance(), SpannerGrpc.getExecuteBatchDmlMethod()) .getTimeout()) .isEqualTo(Duration.ofSeconds(1L)); assertThat( configurator.configure( inputCallContext, ReadRequest.getDefaultInstance(), SpannerGrpc.getReadMethod())) .isNull(); assertThat( configurator .configure( inputCallContext, ReadRequest.getDefaultInstance(), SpannerGrpc.getStreamingReadMethod()) .getTimeout()) .isEqualTo(Duration.ofSeconds(7L)); assertThat( configurator .configure( inputCallContext, PartitionQueryRequest.getDefaultInstance(), SpannerGrpc.getPartitionQueryMethod()) .getTimeout()) .isEqualTo(Duration.ofSeconds(5L)); assertThat( configurator .configure( inputCallContext, PartitionReadRequest.getDefaultInstance(), SpannerGrpc.getPartitionReadMethod()) .getTimeout()) .isEqualTo(Duration.ofSeconds(6L)); } }
[ "\"SPANNER_EMULATOR_HOST\"", "\"SPANNER_EMULATOR_HOST\"" ]
[]
[ "SPANNER_EMULATOR_HOST" ]
[]
["SPANNER_EMULATOR_HOST"]
java
1
0
cmd/fission-bundle/main.go
/* Copyright 2019 The Fission Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "flag" "fmt" "log" "os" "strconv" "contrib.go.opencensus.io/exporter/jaeger" docopt "github.com/docopt/docopt-go" "go.opencensus.io/trace" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/fission/fission/cmd/fission-bundle/mqtrigger" "github.com/fission/fission/pkg/buildermgr" "github.com/fission/fission/pkg/controller" "github.com/fission/fission/pkg/executor" "github.com/fission/fission/pkg/info" "github.com/fission/fission/pkg/kubewatcher" functionLogger "github.com/fission/fission/pkg/logger" mqt "github.com/fission/fission/pkg/mqtrigger" "github.com/fission/fission/pkg/router" "github.com/fission/fission/pkg/storagesvc" "github.com/fission/fission/pkg/timer" "github.com/fission/fission/pkg/utils/profile" ) func runController(logger *zap.Logger, port int) { controller.Start(logger, port, false) logger.Fatal("controller exited") } func runRouter(logger *zap.Logger, port int, executorUrl string) { router.Start(logger, port, executorUrl) logger.Fatal("router exited") } func runExecutor(logger *zap.Logger, port int, functionNamespace, envBuilderNamespace string) { err := executor.StartExecutor(logger, functionNamespace, envBuilderNamespace, port) if err != nil { logger.Fatal("error starting executor", zap.Error(err)) } } func runKubeWatcher(logger *zap.Logger, routerUrl string) { err := kubewatcher.Start(logger, routerUrl) if err != nil { logger.Fatal("error starting kubewatcher", zap.Error(err)) } } func runTimer(logger *zap.Logger, routerUrl string) { err := timer.Start(logger, routerUrl) if err != nil { logger.Fatal("error starting timer", zap.Error(err)) } } func runMessageQueueMgr(logger *zap.Logger, routerUrl string) { err := mqtrigger.Start(logger, routerUrl) if err != nil { logger.Fatal("error starting message queue manager", zap.Error(err)) } } // KEDA based MessageQueue Trigger Manager func runMQManager(logger *zap.Logger, routerURL string) { err := mqt.StartScalerManager(logger, routerURL) if err != nil { logger.Fatal("error starting mqt scaler manager", zap.Error(err)) } } func runStorageSvc(logger *zap.Logger, port int, storage storagesvc.Storage) { err := storagesvc.Start(logger, storage, port) if err != nil { logger.Fatal("error starting storage service", zap.Error(err)) } } func runBuilderMgr(logger *zap.Logger, storageSvcUrl string, envBuilderNamespace string) { err := buildermgr.Start(logger, storageSvcUrl, envBuilderNamespace) if err != nil { logger.Fatal("error starting builder manager", zap.Error(err)) } } func runLogger() { functionLogger.Start() log.Fatalf("Error: Logger exited.") } func getPort(logger *zap.Logger, portArg interface{}) int { portArgStr := portArg.(string) port, err := strconv.Atoi(portArgStr) if err != nil { logger.Fatal("invalid port number", zap.Error(err), zap.String("port", portArgStr)) } return port } func getStringArgWithDefault(arg interface{}, defaultValue string) string { if arg != nil { return arg.(string) } else { return defaultValue } } func registerTraceExporter(logger *zap.Logger, arguments map[string]interface{}) error { collectorEndpoint := os.Getenv("TRACE_JAEGER_COLLECTOR_ENDPOINT") if len(collectorEndpoint) == 0 { logger.Info("skipping trace exporter registration") return nil } serviceName := "Fission-Unknown" if arguments["--controllerPort"] != nil { serviceName = "Fission-Controller" } else if arguments["--routerPort"] != nil { serviceName = "Fission-Router" } else if arguments["--executorPort"] != nil { serviceName = "Fission-Executor" } else if arguments["--kubewatcher"] == true { serviceName = "Fission-KubeWatcher" } else if arguments["--timer"] == true { serviceName = "Fission-Timer" } else if arguments["--mqt"] == true { serviceName = "Fission-MessageQueueTrigger" } else if arguments["--builderMgr"] == true { serviceName = "Fission-BuilderMgr" } else if arguments["--storageServicePort"] != nil { serviceName = "Fission-StorageSvc" } else if arguments["--mqt_keda"] == true { serviceName = "Fission-Keda-MQTrigger" } exporter, err := jaeger.NewExporter(jaeger.Options{ CollectorEndpoint: collectorEndpoint, Process: jaeger.Process{ ServiceName: serviceName, Tags: []jaeger.Tag{ jaeger.BoolTag("fission", true), }, }, }) if err != nil { return err } samplingRate, err := strconv.ParseFloat(os.Getenv("TRACING_SAMPLING_RATE"), 32) if err != nil { return err } trace.RegisterExporter(exporter) trace.ApplyConfig(trace.Config{DefaultSampler: trace.ProbabilitySampler(samplingRate)}) return nil } func main() { var err error // From https://github.com/containous/traefik/pull/1817/files // Tell glog to log into STDERR. Otherwise, we risk // certain kinds of API errors getting logged into a directory not // available in a `FROM scratch` Docker container, causing glog to abort // hard with an exit code > 0. // TODO: fix the lint error. Error checking here is causing all components to crash with error "logtostderr not found" flag.Set("logtostderr", "true") //nolint: errcheck usage := `fission-bundle: Package of all fission microservices: controller, router, executor. Use it to start one or more of the fission servers: Controller is a stateless API frontend for fission resources. Pool manager maintains a pool of generalized function containers, and specializes them on-demand. Executor must be run from a pod in a Kubernetes cluster. Router implements HTTP triggers: it routes to running instances, working with the controller and executor. Kubewatcher implements Kubernetes Watch triggers: it watches Kubernetes resources and invokes functions described in the KubernetesWatchTrigger. The storage service implements storage for functions too large to fit in the Kubernetes API resource object. It supports various storage backends. Usage: fission-bundle --controllerPort=<port> fission-bundle --routerPort=<port> [--executorUrl=<url>] fission-bundle --executorPort=<port> [--namespace=<namespace>] [--fission-namespace=<namespace>] fission-bundle --kubewatcher [--routerUrl=<url>] fission-bundle --storageServicePort=<port> --storageType=<storateType> fission-bundle --builderMgr [--storageSvcUrl=<url>] [--envbuilder-namespace=<namespace>] fission-bundle --timer [--routerUrl=<url>] fission-bundle --mqt [--routerUrl=<url>] fission-bundle --mqt_keda [--routerUrl=<url>] fission-bundle --logger fission-bundle --version Options: --controllerPort=<port> Port that the controller should listen on. --routerPort=<port> Port that the router should listen on. --executorPort=<port> Port that the executor should listen on. --storageServicePort=<port> Port that the storage service should listen on. --executorUrl=<url> Executor URL. Not required if --executorPort is specified. --routerUrl=<url> Router URL. --etcdUrl=<etcdUrl> Etcd URL. --storageSvcUrl=<url> StorageService URL. --filePath=<filePath> Directory to store functions in. --namespace=<namespace> Kubernetes namespace in which to run function containers. Defaults to 'fission-function'. --kubewatcher Start Kubernetes events watcher. --timer Start Timer. --mqt Start message queue trigger. --mqt_keda Start message queue trigger of kind KEDA --builderMgr Start builder manager. --version Print version information ` profile.ProfileIfEnabled() var logger *zap.Logger var config zap.Config isDebugEnv, _ := strconv.ParseBool(os.Getenv("DEBUG_ENV")) if isDebugEnv { config = zap.NewDevelopmentConfig() config.DisableStacktrace = true config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder } else { config = zap.NewProductionConfig() config.DisableStacktrace = true config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder } logger, err = config.Build() if err != nil { log.Fatalf("I can't initialize zap logger: %v", err) } defer logger.Sync() version := fmt.Sprintf("Fission Bundle Version: %v", info.BuildInfo().String()) arguments, err := docopt.ParseArgs(usage, nil, version) if err != nil { logger.Fatal("Could not parse command line arguments", zap.Error(err)) } err = registerTraceExporter(logger, arguments) if err != nil { logger.Fatal("Could not register trace exporter", zap.Error(err), zap.Any("argument", arguments)) } functionNs := getStringArgWithDefault(arguments["--namespace"], "fission-function") envBuilderNs := getStringArgWithDefault(arguments["--envbuilder-namespace"], "fission-builder") executorUrl := getStringArgWithDefault(arguments["--executorUrl"], "http://executor.fission") routerUrl := getStringArgWithDefault(arguments["--routerUrl"], "http://router.fission") storageSvcUrl := getStringArgWithDefault(arguments["--storageSvcUrl"], "http://storagesvc.fission") if arguments["--controllerPort"] != nil { port := getPort(logger, arguments["--controllerPort"]) runController(logger, port) } if arguments["--routerPort"] != nil { port := getPort(logger, arguments["--routerPort"]) runRouter(logger, port, executorUrl) } if arguments["--executorPort"] != nil { port := getPort(logger, arguments["--executorPort"]) runExecutor(logger, port, functionNs, envBuilderNs) } if arguments["--kubewatcher"] == true { runKubeWatcher(logger, routerUrl) } if arguments["--timer"] == true { runTimer(logger, routerUrl) } if arguments["--mqt"] == true { runMessageQueueMgr(logger, routerUrl) } if arguments["--mqt_keda"] == true { runMQManager(logger, routerUrl) } if arguments["--builderMgr"] == true { runBuilderMgr(logger, storageSvcUrl, envBuilderNs) } if arguments["--logger"] == true { runLogger() } if arguments["--storageServicePort"] != nil { port := getPort(logger, arguments["--storageServicePort"]) var storage storagesvc.Storage if arguments["--storageType"] != nil && arguments["--storageType"] == string(storagesvc.StorageTypeS3) { storage = storagesvc.NewS3Storage() } else if arguments["--storageType"] == string(storagesvc.StorageTypeLocal) { storage = storagesvc.NewLocalStorage("/fission") } runStorageSvc(logger, port, storage) } select {} }
[ "\"TRACE_JAEGER_COLLECTOR_ENDPOINT\"", "\"TRACING_SAMPLING_RATE\"", "\"DEBUG_ENV\"" ]
[]
[ "TRACING_SAMPLING_RATE", "TRACE_JAEGER_COLLECTOR_ENDPOINT", "DEBUG_ENV" ]
[]
["TRACING_SAMPLING_RATE", "TRACE_JAEGER_COLLECTOR_ENDPOINT", "DEBUG_ENV"]
go
3
0
example/19-put-object-with-metadata/main.go
package main import ( "bytes" "fmt" "log" "net/http" "os" "github.com/XiaoMi/go-fds/fds" ) func main() { fdsConf, err := fds.NewClientConfiguration(os.Getenv("GO_FDS_TEST_ENDPOINT")) if err != nil { log.Fatal(err) } fdsClient := fds.New(os.Getenv("GO_FDS_TEST_ACCESS_KEY_ID"), os.Getenv("GO_FDS_TEST_ACCESS_KEY_SECRET"), fdsConf) // user defined metadata objectMetaData := fds.NewObjectMetadata() objectMetaData.Set(fds.XiaomiMetaPrefix+"uid", "1000") request := &fds.PutObjectRequest{ BucketName: "bucketname", ObjectName: "test.txt", ContentType: "text/plain", ContentMd5: "5eb63bbbe01eeed093cb22bb8f5acdc3", Metadata: objectMetaData, Data: bytes.NewReader([]byte("hello world")), } resp, err := fdsClient.PutObject(request) if err != nil { log.Fatal(err) } fmt.Println(resp) }
[ "\"GO_FDS_TEST_ENDPOINT\"", "\"GO_FDS_TEST_ACCESS_KEY_ID\"", "\"GO_FDS_TEST_ACCESS_KEY_SECRET\"" ]
[]
[ "GO_FDS_TEST_ACCESS_KEY_ID", "GO_FDS_TEST_ACCESS_KEY_SECRET", "GO_FDS_TEST_ENDPOINT" ]
[]
["GO_FDS_TEST_ACCESS_KEY_ID", "GO_FDS_TEST_ACCESS_KEY_SECRET", "GO_FDS_TEST_ENDPOINT"]
go
3
0
cli/cmd/dump_meta_cmd.go
package cmd import ( "encoding/json" "errors" "fmt" "os" "bytes" "github.com/fatih/color" "github.com/spf13/cobra" "github.com/spf13/viper" "io/ioutil" ) type JobMeta struct { Id string `json:"id"` Name string `json:"name"` Ref string `json:"ref"` RefName string `json:"ref_name"` Tag string `json:"tag"` Stage string `json:"stage"` Url string `json:"url"` } type ProjectMeta struct { Id string `json:"id"` Dir string `json:"dir"` } type ServerMeta struct { Name string `json:"name"` Revision string `json:"revision"` Version string `json:"version"` } type Meta struct { Job *JobMeta `json:"job"` Project *ProjectMeta `json:"project"` Server *ServerMeta `json:"server"` } func init() { RootCmd.AddCommand(dumpMetaCmd) dumpMetaCmd.Flags().StringP("file", "f", "ci.json", "The meta file\ncan also be defined with env var: META_FILE") viper.BindPFlag("meta_file", dumpMetaCmd.Flags().Lookup("file")) viper.BindEnv("meta_file", "META_FILE") } var dumpMetaCmd = &cobra.Command{ Use: "dump-meta", Short: "Dump meta information about CI in a file", RunE: func(cmd *cobra.Command, args []string) error { file := viper.GetString("meta_file") color.Yellow("creating meta file %s\n", file) meta := &Meta{ Job: &JobMeta{ Id: os.Getenv("CI_JOB_ID"), Name: os.Getenv("CI_JOB_NAME"), Ref: os.Getenv("CI_COMMIT_SHA"), RefName: os.Getenv("CI_COMMIT_REF_NAME"), Tag: os.Getenv("CI_COMMIT_TAG"), Stage: os.Getenv("CI_JOB_STAGE"), Url: os.Getenv("CI_JOB_URL"), }, Project: &ProjectMeta{ Id: os.Getenv("CI_PROJECT_ID"), Dir: os.Getenv("CI_PROJECT_DIR"), }, Server: &ServerMeta{ Name: os.Getenv("CI_SERVER_NAME"), Revision: os.Getenv("CI_SERVER_REVISION"), Version: os.Getenv("CI_SERVER_VERSION"), }, } metaJson, err := json.Marshal(meta) if err != nil { return errors.New(fmt.Sprintf("an error occurred while marshalling meta\n%v", err)) } var indented bytes.Buffer json.Indent(&indented, metaJson, "", " ") if viper.GetBool("verbose") { os.Stdout.Write(indented.Bytes()) fmt.Println("") } err = ioutil.WriteFile(file, indented.Bytes(), 0644) if err != nil { return errors.New(fmt.Sprintf("unable to create meta file %s\n%v", file, err)) } color.Green("✔ successfully wrote meta to: %s\n", file) return nil }, }
[ "\"CI_JOB_ID\"", "\"CI_JOB_NAME\"", "\"CI_COMMIT_SHA\"", "\"CI_COMMIT_REF_NAME\"", "\"CI_COMMIT_TAG\"", "\"CI_JOB_STAGE\"", "\"CI_JOB_URL\"", "\"CI_PROJECT_ID\"", "\"CI_PROJECT_DIR\"", "\"CI_SERVER_NAME\"", "\"CI_SERVER_REVISION\"", "\"CI_SERVER_VERSION\"" ]
[]
[ "CI_JOB_NAME", "CI_PROJECT_ID", "CI_JOB_STAGE", "CI_JOB_ID", "CI_COMMIT_REF_NAME", "CI_PROJECT_DIR", "CI_COMMIT_SHA", "CI_SERVER_VERSION", "CI_SERVER_NAME", "CI_SERVER_REVISION", "CI_COMMIT_TAG", "CI_JOB_URL" ]
[]
["CI_JOB_NAME", "CI_PROJECT_ID", "CI_JOB_STAGE", "CI_JOB_ID", "CI_COMMIT_REF_NAME", "CI_PROJECT_DIR", "CI_COMMIT_SHA", "CI_SERVER_VERSION", "CI_SERVER_NAME", "CI_SERVER_REVISION", "CI_COMMIT_TAG", "CI_JOB_URL"]
go
12
0
server/CeSuts.py
# File: CeSuts.py ; This file is part of Twister. # version: 3.013 # Copyright (C) 2012-2014, Luxoft # Authors: # Andreea Proca <[email protected]> # Andrei Costachi <[email protected]> # Cristi Constantin <[email protected]> # 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. ''' Module to manage SUT operations ''' import os import sys import copy import thread from binascii import hexlify import cherrypy from cherrypy import _cptools from lxml import etree try: import simplejson as json except Exception: import json TWISTER_PATH = os.getenv('TWISTER_PATH') if not TWISTER_PATH: print 'TWISTER_PATH environment variable is not set! Exiting!' exit(1) if TWISTER_PATH not in sys.path: sys.path.append(TWISTER_PATH) from common.tsclogging import logFull, logDebug, logInfo, logWarning, logError from common.helpers import userHome from server.CeCommonAllocator import CommonAllocator CONSTANT_DICTIONARY = {'version': 0, 'name': '/', 'meta': {}, 'children': {}} def xml_to_res(xml, gparams): """ Import xml file to SUT. """ def recursive_xml_to_res(xml, res_dict): """ Recursive method - read the xml and generate a dictionary. """ c_nd = {} for folder in xml.findall('folder'): tb_path = folder.find('path') if tb_path is not None: c_nd = {'path':[], 'meta': {}, 'id': '', 'children': {}} tb_path_text = tb_path.text tb_path_list = [q for q in tb_path_text.split('/') if q] c_nd['path'].extend(tb_path_list) else: c_nd = {'meta': {}, 'id': '', 'children': {}} # Populate META properties meta = folder.find('meta') if meta is not None: for meta_params in meta.findall('param'): meta_name = meta_params.find('name') if meta_name is not None: meta_value = meta_params.find('value') if meta_value is not None and meta_value.text is not None: c_nd['meta'][meta_name.text] = meta_value.text else: c_nd['meta'][meta_name.text] = '' # If the XML node contains an ID, use it; else, create a random ID tb_id = folder.find('id') if tb_id is not None: id_value = tb_id.find('value') if id_value is not None and id_value.text is not None: c_nd['id'] = id_value.text else: c_nd['id'] = hexlify(os.urandom(5)) else: c_nd['id'] = hexlify(os.urandom(5)) # Add children for this node res_dict[folder.find('fname').text] = c_nd recursive_xml_to_res(folder, res_dict[folder.find('fname').text]['children']) # we have to get the information at root level(path, meta, id, version) first # version is added only if it exists in xml; the SUT exported files do not # have the version tag root_dict = {'path':[], 'meta':{}, 'id':'', 'children':{}} tb_path_text = xml.find('path').text tb_path = [q for q in tb_path_text.split('/') if q] if tb_path: root_dict['path'].extend(tb_path) else: root_dict['path'].append('') meta = xml.find('meta') for meta_elem in meta: key = meta_elem.find('name').text val = meta_elem.find('value').text if val: root_dict['meta'][key] = val else: root_dict['meta'][key] = '' root_dict['id'] = xml.find('id').text if xml.find('version') is not None and xml.find('version').text is not None: root_dict['version'] = int(xml.find('version').text) gparams = root_dict # rest of the xml file can be read recursively recursive_xml_to_res(xml, gparams['children']) return gparams def res_to_xml(parent_node, xml, skip_header=False): """ Export TB to xml. """ # The node is valid ? if not parent_node: return False # if we are at root level, we need to get path, meta, id and version fields if not skip_header: # path is a list with 0 or 1 elements path = etree.SubElement(xml, 'path') if parent_node.get('path') is not None and len(parent_node.get('path')) == 1: path.text = '/'.join(parent_node.get('path')) else: path.text = '' meta = etree.SubElement(xml, 'meta') # meta is a dictionary for k_var, v_var in parent_node.get('meta').iteritems(): tag = etree.SubElement(meta, 'param') prop = etree.SubElement(tag, 'name') prop.text = str(k_var) val = etree.SubElement(tag, 'value') if v_var: val.text = str(v_var) else: val.text = '' typ = etree.SubElement(tag, 'type') typ.text = 'string' etree.SubElement(tag, 'desc') tb_id = etree.SubElement(xml, 'id') tb_id.text = parent_node.get('id') # add version only if it exists in dictionary; the SUT # files don't have version if parent_node.get('version') is not None: version = etree.SubElement(xml, 'version') version.text = str(parent_node.get('version')) # This node has children ? if not parent_node.get('children'): return False for node in sorted(parent_node['children'].keys()): c_nd = dict(parent_node['children'][node]) # Create empty folder folder = etree.SubElement(xml, 'folder') # Folder fname fname = etree.SubElement(folder, 'fname') fname.text = node # Folder fdesc etree.SubElement(folder, 'fdesc') # get the path if exists if c_nd.get('path'): path = etree.SubElement(folder, 'path') path.text = '/'.join(c_nd.get('path')) # get meta information meta = etree.SubElement(folder, 'meta') for k_var, v_var in c_nd['meta'].iteritems(): tag = etree.SubElement(meta, 'param') prop = etree.SubElement(tag, 'name') prop.text = str(k_var) val = etree.SubElement(tag, 'value') if v_var: val.text = str(v_var) else: val.text = '' typ = etree.SubElement(tag, 'type') typ.text = 'string' etree.SubElement(tag, 'desc') # get the id if c_nd.get('id'): tag = etree.SubElement(folder, 'id') val = etree.SubElement(tag, 'value') val.text = c_nd['id'] typ = etree.SubElement(tag, 'type') typ.text = 'string' desc = etree.SubElement(tag, 'desc') res_to_xml(c_nd, folder, True) return xml class Suts(_cptools.XMLRPCController, CommonAllocator): """ Basic operations for SUTs. """ def __init__(self, project): self.project = project self.type = 'sut' self.resources = CONSTANT_DICTIONARY self.reservedResources = {} self.lockedResources = {} self.id_list = {} self.acc_lock = thread.allocate_lock() # Task change lock self.ren_lock = thread.allocate_lock() # Rename lock self.imp_lock = thread.allocate_lock() # Import lock self.save_lock = thread.allocate_lock() # Save lock self.load_lock = thread.allocate_lock() # Save lock def save_sut(self, props={}, resource_name=None): """ Function used to write the changes on HDD. The save is separate for Devices and SUTs, so the version is not incremented for both, before saving. """ user = self.user_info(props)[0] logDebug('CeSuts:_save {} {} {} '.format(props, resource_name, user)) log = [] # Write changes, using the Access Lock. with self.save_lock: if resource_name[0] == '/': resource_name = resource_name[1:] if resource_name.split('.')[-1] == 'user': suts_gb_path = self.project.get_user_info(user, 'sut_path') else: suts_gb_path = self.project.get_user_info(user, 'sys_sut_path') if not suts_gb_path: suts_gb_path = '{}/config/sut/'.format(TWISTER_PATH) filename = os.path.join(suts_gb_path, '.'.join(resource_name.split('.')[:-1] + ['json'])) if resource_name.split('.')[-1] == 'system': try: resp = self.project.localFs.write_system_file(filename, \ json.dumps(self.resources['children'][resource_name], indent=4), 'w') except Exception as exp_err: log.append(exp_err) logError('User {}: Saving ERROR system:: `{}`.'.format(user, exp_err)) if resource_name.split('.')[-1] == 'user': # user SUT file; we have to check if the cleacase plugin # is activated; if so, use it to write the SUT file; else # use the UserService to read it cc_cfg = self.project.get_clearcase_config(user, 'sut_path') if cc_cfg: view = cc_cfg['view'] actv = cc_cfg['actv'] path = cc_cfg['path'] user_view_actv = '{}:{}:{}'.format(user, view, actv) f_name = ''.join(resource_name.split('.')[:-1]) resp = self.project.clearFs.write_user_file(user_view_actv, path +'/'+ f_name + '.json', \ json.dumps(self.resources['children'][resource_name], indent=4)) else: # Get the user connection resp = self.project.localFs.write_user_file(user, filename, \ json.dumps(self.resources['children'][resource_name], indent=4), 'w') if resp is not True: log.append(resp) logError('User {}: Saving ERROR user:: `{}`.'.format(user, resp)) # targeted resource is saved now; do not continue with # the rest of resources if log: return '*ERROR* ' + str(log) # update id_list self.parse_sut(self.resources['children'][resource_name], resource_name) return True @cherrypy.expose def save_sut_as(self, sut_name, path): """ Function used to write the sut on the user specified path on the disk. sut_name: is the new name of the sut to be saved path: is the path where the sut is saved. It doesn't contain the sut name at the end. """ user = self.user_info({})[0] logFull('CeSuts:_save_as {} {} {} '.format(sut_name, path, user)) log = [] # Write changes, using the Access Lock. with self.save_lock: if sut_name[0] == '/': sut_name = sut_name[1:] if not os.path.exists(path): msg = 'Path does not exist: {}'.format(path) logError(msg) return '*ERROR* '+msg # remove the '_' added when the sut was created real_name = sut_name[1:] filename = os.path.join(path, '.'.join(real_name.split('.')[:-1] + ['json'])) try: self.project.localFs.write_user_file(user, filename, \ json.dumps(self.resources['children'][sut_name], indent=4), 'w') except Exception as exp_err: log.append(exp_err) logError('User {}: Saving ERROR system:: `{}`.'.format(user, exp_err)) # targeted resource is saved now; do not continue with # the rest of resources if log: return '*ERROR* ' + str(log) # remove the new sut from resources self.resources['children'].pop(sut_name) logDebug('Sut resource: `{}` removed from the resources'.format(sut_name)) return True def format_content(self, content, kids_list): """ Find all the ids from a sut. Helps creating id_list. """ if not content: return kids_list if not content.get('children'): kids_list.add(content['id']) return kids_list for node in content['children']: kids_list.add(content['children'][node]['id']) self.format_content(content['children'][node], kids_list) def parse_sut(self, sut_content=None, sut_name=None): """ Adds elements to id_list. """ kids_list = set() kids_list.add(sut_content['id']) self.format_content(sut_content, kids_list) kids_list = list(kids_list) self.id_list[sut_name] = kids_list return True def find_sut_id(self, sut_id): """ Search for an ID in id_list. """ for key, value in self.id_list.items(): if sut_id in value: return key return False def _format_dict_sut(self, result, query): """ Helper function. """ try: result = self.format_resource(result, query) except Exception: logFull('The sut `{}` is already formated !'.format(query)) if isinstance(result['path'], list): result['path'] = '/'.join(result['path']) return result @cherrypy.expose def index_suts(self, props={}): """ Open all SUT files and creats dict having entries like: {sut_name : [ids]} """ user_info = self.user_info(props) user = user_info[0] usr_home = userHome(user) sut_content = False try: # System SUT path suts_gb_path = self.project.get_user_info(user, 'sys_sut_path') if not suts_gb_path: suts_gb_path = '{}/config/sut/'.format(TWISTER_PATH) sut_all_pats = [p for p in os.listdir(suts_gb_path)\ if os.path.isfile(os.path.join(suts_gb_path, p))\ and p.split('.')[-1] == 'json'] for sut_path in sut_all_pats: sut_name = '.'.join(['.'.join(sut_path.split('.')[:-1] + ['system'])]) with open(os.path.join(suts_gb_path, sut_path), 'r') as f_p: sut_content = json.load(f_p) self.parse_sut(sut_content, sut_name) except Exception as exp_err: logError('_load ERROR:: {} for user {}'.format(exp_err, user)) # User SUT path suts_gb_path = self.project.get_user_info(user, 'sut_path') if not suts_gb_path: suts_gb_path = '{}/twister/config/sut/'.format(usr_home) # user SUT file; we have to check if the cleacase plugin # is activated; if so, use it to read the SUT file; else # use the UserService to read it # open all the json files and parse them - need to index all the ids # that sut contains cc_cfg = self.project.get_clearcase_config(user, 'sut_path') if cc_cfg: view = cc_cfg['view'] actv = cc_cfg['actv'] path = cc_cfg['path'] user_view_actv = '{}:{}:{}'.format(user, view, actv) sut_all_pats = [p for p in os.listdir(suts_gb_path)\ if os.path.isfile(os.path.join(suts_gb_path, p))\ and p.split('.')[-1] == 'json'] for sut_path in sut_all_pats: sut_name = '.'.join(['.'.join(sut_path.split('.')[:-1] + ['user'])]) resp = self.project.clearFs.read_user_file(user_view_actv, path +'/'+ sut_name) try: sut_content = json.loads(resp) except Exception: msg = "User {}: Cannot load ClearCase SUT `{}`!".format(user, sut_name) logWarning(msg) return '*ERROR* ' + msg self.parse_sut(sut_content, sut_name) else: sut_all_pats = [p for p in os.listdir(suts_gb_path)\ if os.path.isfile(os.path.join(suts_gb_path, p))\ and p.split('.')[-1] == 'json'] for sut_path in sut_all_pats: sut_name = '.'.join(['.'.join(sut_path.split('.')[:-1] + ['user'])]) if suts_gb_path[-1] != '/' and sut_path[-1] != '/': complete_sut_path = suts_gb_path + '/' + sut_path else: complete_sut_path = suts_gb_path + sut_path resp = self.project.localFs.read_user_file(user, complete_sut_path) try: sut_content = json.loads(resp) except Exception: msg = "User {}: Cannot load SUT `{}`!".format(user, sut_name) logWarning(msg) return '*ERROR* ' + msg self.parse_sut(sut_content, sut_name) return True @cherrypy.expose def get_sut(self, query, props={}): """ Get the contant of one SUT file using it's name. Must provide a SUT name.<type> (type = user/system) If query is an id -> positive answer only if sut is in self.resources """ user_info = self.user_info(props) username = user_info[0] follow_links = False # Follow links to TestBeds ? if 'follow_links' in props: follow_links = props['follow_links'] del props['follow_links'] logDebug('CeSuts: get_sut {} {} {}'.format(query, username, follow_links)) usr_home = userHome(username) initial_query = None if not query: msg = "The name of the SUT is empty!" logDebug(msg) return False if ':' in query: meta = query.split(':')[1] query = query.split(':')[0] else: meta = '' sut_type = query.split('.')[-1] # This is an ID # Will return result only if the SUT is in self.resources if '/' not in query and sut_type == query: initial_query = query res_dict = self.get_resource(query) if isinstance(res_dict, dict): if len(res_dict['path']) > 1: sut_content = self._format_dict_sut(res_dict, query) # If this SUT / component is linked with a TB if sut_content['meta'].get('_id') and follow_links: # Ok, this might be a Device path, instead of SUT path! tb_id = sut_content['meta']['_id'] self.project.testbeds.load_tb(verbose=False) sut_content = self.project.testbeds.\ get_tb(tb_id, props) # If the Device ID is invalid, bye bye! if not isinstance(sut_content, dict): return False if meta: return sut_content['meta'].get(meta, '') else: return sut_content query = res_dict['path'][0] sut_type = query.split('.')[-1] else: # Maybe this sut is already indexed result = self.find_sut_id(query) # If not index all suts and search if not result: self.index_suts(props) result = self.find_sut_id(query) # Probably is a component not saved yet, get it from self.reservedResources if not result: if meta: result = self.get_info_sut(query + ":" + meta, props) else: result = self.get_info_sut(query, props) if isinstance(result, dict): result = self._format_dict_sut(result, query) return result else: msg = 'Invalid SUT ID `{}`, for user `{}`!'.format(query, username) logWarning(msg) return msg query = result sut_type = query.split('.')[-1] # if the query is for a component return the entire SUT if query[1:].count('/') >= 1: initial_query = query parts = [q for q in query.split('/') if q] query = parts[0] try: index = sut_type.index('/') sut_type = sut_type[:index] except Exception: logFull('SutType does not contain any /') if sut_type == 'system': # System SUT path sut_path = self.project.get_user_info(username, 'sys_sut_path') if not sut_path: sut_path = '{}/config/sut/'.format(TWISTER_PATH) elif sut_type == 'user': # User SUT path sut_path = self.project.get_user_info(username, 'sut_path') if not sut_path: sut_path = '{}/twister/config/sut/'.format(usr_home) else: msg = 'Invalid SUT type `{}`, for user `{}`!'.format(sut_type, username) logWarning(msg) return msg # avoid having more than one "/" or not having at all if query[0] == '/' and sut_path[-1] == '/': query = query[1:] elif query[0] != '/' and sut_path[-1] != '/': query = '/' + query f_name = '.'.join(query.split('.')[:-1]) + '.json' sut_file = sut_path + f_name sut_content = False if not os.path.isdir(sut_path): # Cannot get read access to the SUT directory msg = '*ERROR* Cannot get access to SUT path `{}`, user `{}`!'.format(sut_path, username) logWarning(msg) return msg if sut_type == 'system': # System SUT file try: with open(sut_file, 'r') as f_p: sut_content = json.load(f_p) except Exception as exp_err: return '*ERROR* User {}: Cannot read SUT file `{}`! Exception {}'.format( username, sut_file, exp_err) else: # User SUT file, check if the ClearCase plugin is activated # If so, use it to read the SUT file; else use the UserService to read it cc_cfg = self.project.get_clearcase_config(username, 'sut_path') if cc_cfg: view = cc_cfg['view'] actv = cc_cfg['actv'] path = cc_cfg['path'] user_view_actv = '{}:{}:{}'.format(username, view, actv) sut_path = (path +'/'+ f_name).replace('//', '/') resp = self.project.clearFs.read_user_file(user_view_actv, sut_path) # Invalid sut file? if resp.startswith('*ERROR*'): logWarning(resp) return resp try: sut_content = json.loads(resp) except Exception: logWarning('User {}: Cannot load ClearCase SUT `{}`!'.format(username, sut_path)) sut_content = False else: sut_path = (sut_path + '/' + f_name).replace('//', '/') resp = self.project.localFs.read_user_file(username, sut_path) # Invalid sut file? if resp.startswith('*ERROR*'): logWarning(resp) return resp try: sut_content = json.loads(resp) except Exception: logWarning('User {}: Cannot load SUT `{}`!'.format(username, sut_path)) sut_content = False if isinstance(sut_content, str) and sut_content.startswith('*ERROR*'): return sut_content if (sut_content is False) or (not isinstance(sut_content, dict)): msg = 'User {}: Invalid SUT `{}`!'.format(username, f_name) logWarning(msg) return '*ERROR* ' + msg # At this point, the SUT is a valid dictionary if query[0] == '/': query = query[1:] if sut_content.get('path'): sut_content['path'] = sut_content['path'][0] else: sut_content['path'] = query self.resources['children'][query] = copy.deepcopy(sut_content) # make older resources files that don't have 'path' compatible self.resources['children'][query]['path'] = [query] modified = self.fix_path(self.resources['children'][query], [query]) if modified: # now we have to save the version with path issaved = self.save_sut(props, query) if isinstance(issaved, str): msg = 'Cannot save SUT `{}`, for user `{}`!'.format(query, username) logWarning(msg) return msg if initial_query: result = self.get_info_sut(initial_query, props) if isinstance(result, dict): sut_content = self._format_dict_sut(result, query) elif follow_links: parts = [p for p in initial_query.split('/') if p] if len(parts) == 1: msg = '*ERROR* Internal server error!' logWarning(msg) return msg curr_parts = [parts.pop(0)] while 1: try: curr_parts.append(parts.pop(0)) except Exception: break curr_path = '/' + '/'.join(curr_parts) result = self.get_resource(curr_path) # SUT not loaded if not isinstance(result, dict): msg = '*ERROR* Invalid SUT path `{}`!'.format(curr_path) logWarning(msg) return False if result['meta'].get('_id'): # Ok, this might be a Device path, instead of SUT path! tb_id = result['meta']['_id'] self.project.testbeds.load_tb(verbose=False) result = self.project.testbeds.get_tb(tb_id, props) # If the Device ID is invalid, bye bye! if not isinstance(result, dict): return False tb_path = '/' + result['path'] + '/' + '/'.join(parts) result = self.project.testbeds.get_tb(tb_path, props) # If the Device ID is invalid, bye bye! if not isinstance(result, dict): return False if meta: return result['meta'].get(meta, '') else: return result # Internal error? else: msg = '*ERROR* Invalid SUT path `{}`!'.format(initial_query) logWarning(msg) return msg try: sut_content = self.format_resource(sut_content, query) except Exception: logFull('User {}: The sut is already formated {}.'.format(username, query)) # If this SUT / component is linked with a TB if sut_content['meta'].get('_id'): # Ok, this might be a Device path, instead of SUT path! tb_id = sut_content['meta']['_id'] self.project.testbeds.load_tb(verbose=False) sut_content = self.project.testbeds.get_tb(tb_id, props) # If the Device ID is invalid, bye bye! if not isinstance(sut_content, dict): msg = '*ERROR* Invalid TB link on SUT `{}`!'.format(initial_query) logWarning(msg) return msg if meta: return sut_content['meta'].get(meta, '') else: return sut_content @cherrypy.expose def get_info_sut(self, res_query, props={}): """ Get the current version of the meta SUT modified and unsaved or the version from the disk. """ user_info = self.user_info(props) logDebug('CeSuts:get_meta_sut {} {}'.format(res_query, props)) if ':' in res_query: res_query, meta = res_query.split(':') else: meta = '' result = None # If the SUT is reserved, get the latest unsaved changes if user_info[0] in self.reservedResources: for i in range(len(self.reservedResources[user_info[0]].values())): current_res_reserved = CONSTANT_DICTIONARY current_path_root = self.reservedResources[user_info[0]].values()[i]['path'][0] current_res_reserved['children'][current_path_root] = self.reservedResources[user_info[0]].values()[i] result = self.get_resource(res_query, current_res_reserved) if isinstance(result, dict): break if not isinstance(result, dict): result = self.get_resource(res_query) # SUT not loaded if not isinstance(result, dict): msg = 'Cannot find `{}`. Call `get_sut` for a SUT, component, or meta.'.format(res_query) logWarning(msg) return False if isinstance(result, dict): if meta: return result['meta'].get(meta, '') else: return result return False @cherrypy.expose def reserve_sut(self, res_query, props={}): """ load the SUT wanted and then reserve it """ self.get_sut(res_query, props) return self.reserve_resource(res_query, props) @cherrypy.expose def create_component_sut(self, name, parent=None, props={}): """ Create new component for an existing SUT """ logFull('CeSuts:create_component_sut: parent = {} props = {} name = {}'.format(parent, props, name)) if parent == '/' or parent == '1': msg = "The parent value is not an existing SUT. Mayebe you want to add a new SUT. Parent: {}".format(parent) logError(msg) return '*ERROR* ' + msg user_info = self.user_info(props) _is_res_reserved = self.is_resource_reserved(parent, props) if _is_res_reserved and _is_res_reserved != user_info[0]: msg = 'User {}: Cannot create new component: The SUT is reserved for {} !'\ .format(user_info[0], _is_res_reserved) logError(msg) return '*ERROR* ' + msg _is_res_locked = self.is_resource_locked(parent) if _is_res_locked and _is_res_locked != user_info[0]: msg = 'User {}: Reserve SUT: The SUT is locked for {} !'\ .format(user_info[0], _is_res_locked) logError(msg) return '*ERROR* ' + msg props = self.valid_props(props) with self.acc_lock: #the resource should be reserved previously parent_p = self.get_reserved_resource(parent, props) if not parent_p: logError('Cannot access reserved SUT, path or ID `{}` !'.format(parent)) return False if name in parent_p['children']: msg = "A component with this name '{}'' already exists for this Sut: '{}'".format(name, parent) logDebug(msg) return '*ERROR* ' + msg #the resources is deep in the tree, we have to get its direct parent if len(parent_p['path']) >= 2: full_path = parent_p['path'] base_path = "/".join(parent_p['path'][1:]) parent_p = self.get_path(base_path, parent_p) parent_p['path'] = full_path if '/' in name: logDebug('Stripping slash characters from `{}` `{}`...'.format(name, parent)) name = name.replace('/', '') # the resource doesn't exist - create it res_id = self.generate_index() parent_p['children'][name] = {'id': res_id, 'meta': props, 'children': {}, 'path':parent_p['path'] + [name]} epnames_tag = '_epnames_{}'.format(user_info[0]) # If the epnames tag exists in resources if epnames_tag in parent_p['children'][name]['meta']: # And the tag is empty if not parent_p['children'][name]['meta'][epnames_tag]: logDebug('User {}: Deleting `{}` tag from new resource.'.format(user_info[0], epnames_tag)) del parent_p['children'][name]['meta'][epnames_tag] return res_id @cherrypy.expose def create_new_sut(self, name, parent=None, props={}, save=True): """ Create a SUT. """ user_info = self.user_info(props) logFull('CeSuts: create_new_sut: parent = {} -- props = {} -- name = {}'.format(parent, props, name)) props = self.valid_props(props) if parent != '/' and parent != "1": msg = "User {}: The parent value is not root. Mayebe you want to add a component \ to an existing SUT. Parent: {}".format(user_info, parent) logError(msg) return '*ERROR* ' + msg with self.acc_lock: #root can not be reserved so we just take it if name.split('.')[-1] != 'user' and \ name.split('.')[-1] != 'system': name = '.'.join([name, 'user']) if '/' in name: logDebug('Stripping slash characters from `{}`...'.format(name)) name = name.replace('/', '') if name in self.resources['children']: msg = "User {}: A SUT with this name '{}'' already exists'".format(user_info[0], name) logDebug(msg) return '*ERROR* ' + msg # the resource doesn't exist - create it res_id = self.generate_index() self.resources['children'][name] = {'id': res_id, 'meta': props, 'children': {}, 'path': [name]} #save this new SUT if save: issaved = self.save_sut(props, name) if isinstance(issaved, str): msg = "We could not save this SUT {}".format(name) logDebug(msg) return issaved return res_id @cherrypy.expose def update_meta_sut(self, name, parent=None, props={}): """ Modify a SUT using a name, a parent Path or ID and some properties. This method changes meta for a certain SUT. """ user_info = self.user_info(props) logDebug('CeSuts:update_meta_sut: parent = {} -- props = {} -- username = {} -- name = {}'\ .format(parent, props, user_info[0], name)) # if props does not have the correct format we stop this operation if not props or not self.valid_props(props): msg = "Wrong format for props = {}".format(props) logDebug(msg) return '*ERROR* ' + msg # can not verify if reserved '/' because I load only the sut that I need if parent == "/" or parent == "1": if name.split('.')[-1] != 'user' and \ name.split('.')[-1] != 'system': name = '.'.join([name, 'user']) # we can not reserve the root so we just take the sut we need verify_reserved = name else: # take the sut that has the component we need verify_reserved = parent # what if this sut is already reserved by other user? We STOP _is_res_reserved = self.is_resource_reserved(verify_reserved, props) if _is_res_reserved and _is_res_reserved != user_info[0]: msg = 'User {}: Cannot update meta: The resource is reserved for {} !'\ .format(user_info[0], _is_res_reserved) logError(msg) return '*ERROR* ' + msg # what if this sut is already locked by other user? We STOP _is_res_locked = self.is_resource_locked(verify_reserved) if _is_res_locked and _is_res_locked != user_info[0]: msg = 'User {}: Reserve resource: The resource is locked for {} !'\ .format(user_info[0], _is_res_locked) logError(msg) return '*ERROR* ' + msg with self.acc_lock: parent_p = self.get_reserved_resource(verify_reserved, props) if not parent_p: logError('Cannot access reserved SUT, path or ID `{}` !'.format(verify_reserved)) return False if '/' in name: logDebug('Stripping slash characters from `{}`...'.format(name)) name = name.replace('/', '') # the resources is deep in the tree, we have to get its direct parent if len(parent_p['path']) >= 2: full_path = parent_p['path'] base_path = "/".join(parent_p['path'][1:]) parent_p = self.get_path(base_path, parent_p) parent_p['path'] = full_path # get the child, update its meta if name in parent_p['children']: child_p = parent_p['children'][name] # update the parent itself elif name in parent_p['path']: child_p = parent_p # We have to update the props props = self.valid_props(props) epnames_tag = '_epnames_{}'.format(user_info[0]) child_p['meta'].update(props) # if _id key is present in meta and it has no value, we have # to remove it from meta dictionary if '_id' in child_p['meta'].keys() and not child_p['meta'].get('_id', False): child_p['meta'].pop('_id') # If the epnames tag exists in resources if epnames_tag in child_p['meta']: # And the tag is empty if not child_p['meta'][epnames_tag]: logDebug('User {}: Deleting `{}` tag from resources.'.format(user_info[0], epnames_tag)) del child_p['meta'][epnames_tag] return "true" @cherrypy.expose def set_sut(self, name, parent=None, props={}): """ Higher level wrapper over functions Create new SUT, create component and update meta. """ if parent == '/' or parent == '1': if name[0] != '/': name = '/' + name ndata = self.get_sut(name, props) if not isinstance(ndata, dict): return self.create_new_sut(name, parent, props) else: return self.update_meta_sut(name, parent, props) # The parent is NOT root self.get_sut(parent, props) pdata = self.get_resource(parent) user_info = self.user_info(props) if not isinstance(pdata, dict): logWarning('User `{}`: No such parent `{}`!'.format(user_info[0], parent)) return False # If exists, update meta if name in pdata['children']: return self.update_meta_sut(name, parent, props) # This is a new component else: return self.create_component_sut(name, parent, props) @cherrypy.expose def rename_sut(self, res_query, new_name, props={}): """ Rename a SUT if it is not reserved or locked by someone. If its asked to rename the root of a sut and new_name doesn't specify the type (user/system) we add ".user". We do that by creating a new Sut having name: new_name and delete the old Sut. """ user_info = self.user_info(props) logFull('CeSuts:rename_sut {} {}'.format(res_query, props)) if '/' in new_name or ':' in new_name: msg = 'New resource name ({}) cannot contain `/` or `:`!'.format(new_name) logError(msg) return '*ERROR* ' + msg if ':' in res_query: res_query = res_query.split(':')[0] usr_sut_list = self.list_all_suts(user_info[0]) # check if res_query exists if res_query[0] == '/': res_query = res_query[1:] found_old_sut = [item for item in usr_sut_list if item['name'] == res_query] if not found_old_sut: msg = 'User {}: SUT file {} doesn\'t exist !'.format(user_info[0], res_query) logError(msg) return '*ERROR* ' + msg # add 'user' or 'system' at the end of the new_name if it does not have it if new_name.split('.')[-1] != 'user' and new_name.split('.')[-1] != 'system': if res_query.split('.')[-1] == 'user' or res_query.split('.')[-1] == 'system': new_name = '.'.join([new_name, res_query.split('.')[-1]]) else: new_name = '.'.join([new_name, 'user']) # check that the 'new_name' doesn't exists found_new_sut = [item for item in usr_sut_list if item['name'] == new_name] if found_new_sut: msg = 'User {}: New SUT file {} already exist !'.format(user_info[0], new_name) logError(msg) return '*ERROR* ' + msg # make sure the SUT file names start with / if res_query[0] != '/': res_query = '/' + res_query if new_name[0] != '/': new_name = '/' + new_name if new_name == res_query: msg = "Not renaming: Both the current name and the new name are the same." logError(msg) return "*ERROR*" + msg # Check if resource is reserved; if so, it cannot be renamed _is_res_reserved = self.is_resource_reserved(res_query, props) if _is_res_reserved: msg = 'User {}: Cannot delete: The resource is reserved for {} !'\ .format(user_info[0], _is_res_reserved) logError(msg) return '*ERROR* ' + msg _is_res_locked = self.is_resource_locked(res_query) if _is_res_locked and _is_res_locked != user_info[0]: msg = 'User {}: Reserve resource: The resource is locked for {} !'\ .format(user_info[0], _is_res_locked) logError(msg) return '*ERROR* ' + msg # Create a new SUT having this new name new_sut_id = self.create_new_sut(new_name, "/", props) if isinstance(new_sut_id, str): if '*ERROR*' in new_sut_id: msg = 'User {}: New SUT file {} cannot be created!'.format(user_info[0], new_name) logError(msg) return '*ERROR* ' + msg reserve_res = self.reserve_resource(new_name, props) if isinstance(reserve_res, str): if '*ERROR*' in reserve_res: msg = 'User {}: New SUT file {} cannot be reserved!'.format(user_info[0], new_name) logError(msg) return '*ERROR* ' + msg # method to clean the new SUT if needed def clean_new_sut(new_sut, user): """ Delete the new SUT if the rename Failed. """ self.reservedResources[user].pop(new_sut) if not self.reservedResources[user]: self.reservedResources.pop(user) self.delete_sut(new_sut, props) # Try to reserve source SUT file; if error, clean up the new SUT reserve_res = self.reserve_resource(res_query, props) if isinstance(reserve_res, str): if '*ERROR*' in reserve_res: msg = 'User {}: Source SUT file {} cannot be reserved!'.format(user_info[0], res_query) logError(msg) clean_new_sut(new_sut_id, user_info[0]) return '*ERROR* ' + msg # get the new path new_sut = self.reservedResources[user_info[0]][new_sut_id] # get the old sut old_sut = self.get_reserved_resource(res_query, props) # get all the structure of the old sut new_sut['meta'] = old_sut['meta'] new_sut['children'] = old_sut['children'] # if the sut has children we have to update the path self.change_path(new_sut, new_sut['path']) # release the old sut; and delete if needed self.reservedResources[user_info[0]].pop(old_sut['id']) if not self.reservedResources[user_info[0]]: self.reservedResources.pop(user_info[0]) deleted = self.delete_sut(res_query, props) if isinstance(deleted, str) and deleted.startswith('*ERROR*'): #could not delete the old sut so we keep it and delete the new one clean_new_sut(new_sut_id, user_info[0]) msg = "User {} :We couldn't delete the old sut so we cannot complete the rename operation."\ .format(user_info[0]) logError(msg) return '*ERROR* ' + msg else: # save and release the new sut self.save_release_reserved_sut(new_name, props) return "True" @cherrypy.expose def rename_meta_sut(self, res_query, new_name, props={}): """ Rename meta for SUT. SUT must be reserved. """ user_info = self.user_info(props) logFull('CeSuts:get_meta_sut {} {}'.format(res_query, props)) if ':' in res_query: meta = res_query.split(':')[1] res_query = res_query.split(':')[0] else: logError("CeSuts:get_meta_sut: User {} called this method without meta!".format(user_info[0])) return "false" #what if this sut is already reserved by other user? We STOP _is_res_reserved = self.is_resource_reserved(res_query, props) if _is_res_reserved and _is_res_reserved != user_info[0]: msg = 'User {}: Cannot update meta: The resource is reserved for {} !'\ .format(user_info[0], _is_res_reserved) logError(msg) return '*ERROR* ' + msg #what if this sut is already locked by other user? We STOP _is_res_locked = self.is_resource_locked(res_query) if _is_res_locked and _is_res_locked != user_info[0]: msg = 'User {}: Reserve resource: The resource is locked for {} !'.format(user_info[0], _is_res_locked) logError(msg) return '*ERROR* ' + msg with self.acc_lock: parent_p = self.get_reserved_resource(res_query, props) if not parent_p: logError('Cannot access reserved SUT, path or ID `{}` !'.format(res_query)) return False try: if isinstance(parent_p['path'], list): # modify meta to the parent if len(parent_p['path']) == 1: child = parent_p # modify to a component else: base_path = "/".join(parent_p['path'][1:]) child = self.get_path(base_path, parent_p) child['meta'][new_name] = child['meta'].pop(meta) except Exception: msg = "This meta that you entered thoes not exist {}".format(meta) logDebug(msg) return "false" return self.save_reserved_sut(res_query, props) @cherrypy.expose def delete_component_sut(self, res_query, props={}): """ Permanently delete a component of a SUT or meta. It can be deleted only if SUT is reserved. """ user_info = self.user_info(props) user = user_info[0] logFull('CeSuts:delete_component_sut {}'.format(res_query)) if ':' in res_query: meta = res_query.split(':')[1] res_query = res_query.split(':')[0] else: meta = '' # Check if resource is reserved; if so, it cannot be deleted _is_res_reserved = self.is_resource_reserved(res_query, props) if _is_res_reserved and _is_res_reserved != user: msg = 'User {}: Cannot delete: The resource is reserved for {} !'.format( user, _is_res_reserved) logWarning(msg) return '*ERROR* ' + msg _is_res_locked = self.is_resource_locked(res_query) if _is_res_locked and _is_res_locked != user: msg = 'User {}: Cannot delete: The resource is locked for {} !'.format( user, _is_res_locked) logWarning(msg) return '*ERROR* ' + msg # The resource should be reserved parent_p = self.get_reserved_resource(res_query, props) if not parent_p: logWarning('User {}: Cannot access reserved SUT, path or ID `{}` !'.format( user, res_query)) return False # Delete meta if meta: # we have to delete only the meta property correct_path = copy.deepcopy(parent_p['path']) # modify meta for parent if len(parent_p['path']) == 1: child = parent_p # modify meta for component else: base_path = "/".join(parent_p['path'][1:]) child = self.get_path(base_path, parent_p) try: child['meta'].pop(meta) except Exception: msg = 'User {}: Property `{}` does not exist!'.format(user, meta) logWarning(msg) return 'false' child['path'] = correct_path # Delete component else: full_path = '' # the resources is deep in the tree, have to get its direct parent if len(parent_p['path']) > 2: full_path = copy.deepcopy(parent_p['path']) base_path = "/".join(parent_p['path'][1:-1]) parent_p = self.get_path(base_path, parent_p) if not full_path: full_path = parent_p['path'] parent_p['children'].pop(full_path[-1]) parent_p['path'] = full_path[:-1] return 'true' @cherrypy.expose def delete_sut(self, res_query, props={}): """ Permanently delete a SUT. Sut can be deteleted only if it is not reserved by anyone. """ user_info = self.user_info(props) logFull('CeSuts:delete_sut {}'.format(res_query)) # Check if resource is reserved; if so, it cannot be deleted _is_res_reserved = self.is_resource_reserved(res_query, props) if _is_res_reserved: msg = 'User {}: Cannot delete: The resource is reserved for {} !'\ .format(user_info[0], _is_res_reserved) logError(msg) return '*ERROR* ' + msg _is_res_locked = self.is_resource_locked(res_query) if _is_res_locked: msg = 'User {}: Reserve resource: The resource is locked for {} !'\ .format(user_info[0], _is_res_locked) logError(msg) return '*ERROR* ' + msg usr_home = userHome(user_info[0]) # temporary fix; the SUT must be removed from self.resources def delete_sut_memory(sut_to_remove): parent_p = self.get_resource('/') if parent_p is not None and parent_p['children'].get(sut_to_remove) is not None: parent_p['children'].pop(sut_to_remove) # end temporary fix # SUT file can be user or system file if res_query.split('.')[-1] == 'system': suts_gb_path = self.project.get_user_info(user_info[0], 'sys_sut_path') if not suts_gb_path: suts_gb_path = '{}/config/sut/'.format(TWISTER_PATH) try: os.remove(suts_gb_path + res_query.split('.')[0] + '.json') delete_sut_memory(res_query.split('/')[-1]) return "True" except Exception as exp_err: msg = 'User {}: Cannot delete SUT file: `{}` !'.format(user_info[0], res_query.split('.')[0] + '.json') logError(msg + " ERROR: " + exp_err) return '*ERROR* ' + msg return "True" else: usr_sut_path = self.project.get_user_info(user_info[0], 'sut_path') if not usr_sut_path: usr_sut_path = '{}/twister/config/sut/'.format(usr_home) delete_sut_memory(res_query.split('/')[-1]) # delete from id_list if possible try: del self.id_list[res_query] except Exception: logDebug('User {}: id_list does not contain the sut: {}'.format(user_info[0], res_query)) # get user SUT file; we have to check if the cleacase plugin # is activated; if so, use it to read the SUT files from view; # else use the UserService to read it cc_cfg = self.project.get_clearcase_config(user_info[0], 'sut_path') if cc_cfg: view = cc_cfg['view'] actv = cc_cfg['actv'] path = cc_cfg['path'] user_view_actv = '{}:{}:{}'.format(user_info[0], view, actv) if path[-1] != '/' and res_query[-1] != '/': complete_sut_path = path + '/' + res_query.split('.')[0] + '.json' else: complete_sut_path = path + res_query.split('.')[0] + '.json' return self.project.clearFs.delete_user_file(user_view_actv, complete_sut_path) else: if usr_sut_path[-1] != '/' and res_query[-1] != '/': complete_sut_path = usr_sut_path + '/' + res_query.split('.')[0] + '.json' else: complete_sut_path = usr_sut_path + res_query.split('.')[0] + '.json' return self.project.localFs.delete_user_file(user_info[0], complete_sut_path) @cherrypy.expose def list_all_suts(self, user): """ Fast list suts. """ suts = [] result = [] usr_home = userHome(user) # System SUT path sys_sut_path = self.project.get_user_info(user, 'sys_sut_path') if not sys_sut_path: sys_sut_path = '{}/config/sut/'.format(TWISTER_PATH) # User SUT path usr_sut_path = self.project.get_user_info(user, 'sut_path') if not usr_sut_path: usr_sut_path = '{}/twister/config/sut/'.format(usr_home) # first, get all system SUT files if os.path.isdir(sys_sut_path): s_suts = ['{}.system'.format(os.path.splitext(d)[0]) \ for d in os.listdir(sys_sut_path) \ if os.path.splitext(d)[1] == '.json'] suts.extend(s_suts) # get user SUT file; we have to check if the cleacase plugin # is activated; if so, use it to read the SUT files from view; # else use the UserService to read it cc_cfg = self.project.get_clearcase_config(user, 'sut_path') if cc_cfg: view = cc_cfg['view'] actv = cc_cfg['actv'] path = cc_cfg['path'] user_view_actv = '{}:{}:{}'.format(user, view, actv) resp = self.project.clearFs.list_user_files(user_view_actv, path, False, False) if isinstance(resp, str): logWarning(resp) return '*ERROR* ' + resp for f_file in resp['children']: f_name, file_ext = os.path.splitext(f_file['path']) if file_ext and file_ext == '.json': suts.append(f_name + '.user') else: if os.path.isdir(usr_sut_path): resp = self.project.localFs.list_user_files(user, usr_sut_path, False, False) if isinstance(resp, str): logWarning(resp) for f_file in resp['children']: f_name, file_ext = os.path.splitext(f_file['path']) if file_ext and file_ext == '.json': suts.append(f_name + '.user') def quick_find_path(dictionary, spath): """ Find path. """ for usr, locks in dictionary.iteritems(): for id_sut, data in locks.iteritems(): path = data.get('path', ['']) if isinstance(path, str) or isinstance(path, unicode): path = [path] if path == [spath]: return usr return False for s_sut in sorted(suts): ruser = quick_find_path(self.reservedResources, s_sut) luser = quick_find_path(self.lockedResources, s_sut) if (not ruser) and (not luser): result.append({'name': s_sut, 'status': 'free'}) elif ruser: result.append({'name': s_sut, 'status': 'reserved', 'user': ruser}) elif luser: result.append({'name': s_sut, 'status': 'locked', 'user': luser}) # Both reserved and locked ? else: result.append({'name': s_sut, 'status': 'reserved', 'user': ruser}) suts_on_disk = [s['name'] for s in result] # if the status of the CE is stopped for the current user # update the CE memory; check for consistency status = self.project.users[user]['status'] if status == 0: suts_in_memory = self.resources['children'].keys() for sut in suts_in_memory: if sut not in suts_on_disk: id = self.resources['children'][sut].get('id') if user in self.reservedResources and id in self.reservedResources[user]: logDebug('Removed sut `{}` from reserved resources.'.format(sut)) self.reservedResources[user].pop(id) if user in self.lockedResources and id in self.lockedResources[user]: logDebug('Removed sut `{}` from locked resources.'.format(sut)) self.lockedResources[user].pop(id) logDebug('Removed sut `{}` from memory.'.format(sut)) self.resources['children'].pop(sut) logDebug('User {}: Fast listing SUTs... Found {}.'.format(user, suts)) return result @cherrypy.expose def import_sut_xml(self, xml_file, sut_type='user', props={}): """ Import one sut XML file. """ user_info = self.user_info(props) user = user_info[0] logDebug('User {}: import XML file `{}`...'.format(user, xml_file)) try: params_xml = etree.parse(xml_file) except Exception: msg = "The file you selected: '{}' it's not an xml file. Try again!".format(xml_file) logDebug(msg) return '*ERROR* ' + msg # parse the xml file and build the json format xml_ret = xml_to_res(params_xml, {}) # build the filename to be saved; xml_file has absolute path; we need # to extract the last string after /, remove extension and add .json sut_file = xml_file.split('/')[-1].split('.')[0] sut_file = sut_file + '.json' sut_path = None if sut_type == 'system': # System SUT path sut_path = self.project.get_user_info(user, 'sys_sut_path') if not sut_path: sut_path = '{}/config/sut/'.format(TWISTER_PATH) else: # User SUT path sut_path = self.project.get_user_info(user, 'sut_path') if not sut_path: usr_home = userHome(user) sut_path = '{}/twister/config/sut/'.format(usr_home) sut_file = sut_path + '/' + sut_file resp = True if sut_type == 'system': resp = self.project.localFs.write_system_file(sut_file, json.dumps(xml_ret, indent=4), 'w') else: resp = self.project.localFs.write_user_file(user, sut_file, json.dumps(xml_ret, indent=4), 'w') return resp @cherrypy.expose def export_sut_xml(self, xml_file, query, props={}): """ Export as XML file. """ user_info = self.user_info(props) user = user_info[0] logDebug('User {}: export XML file `{}`, query = {}...'.format(user, xml_file, query)) sut_path = None sut_type = query.split('.')[-1] if sut_type == 'system': # System SUT path sut_path = self.project.get_user_info(user, 'sys_sut_path') if not sut_path: sut_path = '{}/config/sut/'.format(TWISTER_PATH) else: # User SUT path sut_path = self.project.get_user_info(user, 'sut_path') if not sut_path: usr_home = userHome(user) sut_path = '{}/twister/config/sut/'.format(usr_home) sut_filename = sut_path + '/' + query.split('/')[1].split('.')[0] + '.json' logInfo('User {}: Export SUT file `{}` to `{}`.'.format(user, sut_filename, xml_file)) # read the content of the user SUT file and load it in json if sut_type == 'system': resp = self.project.localFs.read_system_file(sut_filename, 'r') else: resp = self.project.localFs.read_user_file(user, sut_filename, 'r') try: json_resp = json.loads(resp) except Exception: msg = "User {}: Cannot load SUT file `{}`!".format(user, sut_filename) logWarning(msg) return '*ERROR* ' + msg # generate the xml structure xml = etree.Element('root') res_to_xml(json_resp, xml) # write the xml file xml_header = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n\n' resp = self.project.localFs.write_user_file(user, xml_file, xml_header, 'w') if resp != True: logError(resp) return resp resp = self.project.localFs.write_user_file(user, xml_file, etree.tostring(xml, pretty_print=True), 'w') if resp != True: logError(resp) return resp return True @cherrypy.expose def lock_sut(self, res_query, props={}): """ Lock SUT. Add to lockedResources """ return self.lock_resource(res_query, props) @cherrypy.expose def unlock_sut(self, res_query, props={}): """ Unlock SUT. Delete from lockedResources. """ return self.unlock_resource(res_query, props) @cherrypy.expose def is_sut_locked(self, res_query): """ Verify if SUT is locked. """ result = self.is_resource_locked(res_query) if not result: return "false" return result @cherrypy.expose def is_sut_reserved(self, res_query, props={}): """ Verify if SUT is reserved. """ result = self.is_resource_reserved(res_query, props) if not result: return "false" return result @cherrypy.expose def save_reserved_sut_as(self, name, res_query, props={}): """ Save a reserved SUT as name+path. """ user_info = self.user_info(props) user = user_info[0] logFull('CeSuts:save_reserved_sut_as {} {} {}'.format(name, res_query, user)) path = '/'.join(name.split('/')[:-1]) name = name.split('/')[-1] # add a '_' at the begining to be able to save as a new sut with the same name as the old one # the sut is deleted from memory after the json.dump target_name = '/_'+name+ '.' +res_query.split('.')[-1]#'.user' # verify if the sut exists usr_sut_list = self.list_all_suts(user) if res_query[0] == '/': res_query = res_query[1:] found_old_sut = [item for item in usr_sut_list if item['name'] == res_query] if not found_old_sut: msg = 'User {}: SUT file {} doesn\'t exist !'.format(user, res_query) logError(msg) return '*ERROR* ' + msg res_query = '/' + res_query # #verify if a SUT having the same name exists found_new_sut = [item for item in usr_sut_list if item['name'] == target_name] if found_new_sut: msg = 'User {}: New SUT file {} already exist !'.format(user, target_name) logError(msg) return '*ERROR* ' + msg # Check if resource is reserved; if so, it cannot be deleted _is_res_reserved = self.is_resource_reserved(res_query, props) if _is_res_reserved and _is_res_reserved != user: msg = 'User {}: Cannot save as: The resource is reserved for {} !'.\ format(user, _is_res_reserved) logError(msg) return '*ERROR* ' + msg _is_res_locked = self.is_resource_locked(res_query) if _is_res_locked and _is_res_locked != user: msg = 'User {}: Reserve resource: The resource is locked for {} !'.\ format(user, _is_res_locked) logError(msg) return '*ERROR* ' + msg # Create a new SUT having this new name new_sut_id = self.create_new_sut(target_name, '/', props, False) if isinstance(new_sut_id, str) and '*ERROR*' in new_sut_id: msg = 'User {}: New SUT file {} cannot be created!'.format(user, target_name) logError(msg) return '*ERROR* ' + msg # Reserve the target SUT self.reserve_resource(target_name, props) # Get the new path new_sut = self.reservedResources[user_info[0]][new_sut_id] # Get the old sut old_sut = self.get_reserved_resource(res_query, props) # Get all the structure of the old sut new_sut['meta'].update(copy.deepcopy(old_sut['meta'])) # Copy children new_sut['children'].update(copy.deepcopy(old_sut['children'])) # Recursive fix children IDs self.change_ids(new_sut) # Recursive fix children paths self.change_path(new_sut, new_sut['path']) # Exit now return self.save_reserved_sut(target_name, '{}', path) @cherrypy.expose def save_reserved_sut(self, res_query, props={}, path=''): """ User has made some changes only on self.reserved_resources. In this method we sync self.reserved_resources with self.resources and the store on the disk """ user_info = self.user_info(props) logFull('CeSuts:save_reserved_sut {} {}'.format(res_query, user_info[0])) resources = self.resources # If no resources... if not resources.get('children'): msg = 'User {}: Save reserved resource: There are no resources defined !'.format(user_info[0]) logError(msg) return '*ERROR* ' + msg user_info = self.user_info(props) if ':' in res_query: res_query = res_query.split(':')[0] if not self.reservedResources.get(user_info[0]): msg = "It seems that this user does not have changes to save! {}".format(user_info[0]) logDebug(msg) return '*ERROR* ' + msg resource_node = self.get_resource(res_query) if not resource_node or isinstance(resource_node, str): msg = 'User {}: Cannot find SUT {}'.format(user_info[0], res_query) logFull(msg) return '*ERROR* ' + msg if len(resource_node['path']) > 1: resource_node = self.get_path(resource_node['path'][0], resources) reserved_node = self.reservedResources[user_info[0]][resource_node['id']] # Maybe the user renamed the TB if reserved_node['path'][0] != resource_node['path'][0]: self.resources['children'][reserved_node['path'][0]] = \ self.resources['children'].pop(resource_node['path'][0]) # ...or maybe the name of the resource is the same resources['children'].update([(reserved_node['path'][0], reserved_node), ]) # Update path resources['children'][reserved_node['path'][0]]['path'] = [reserved_node['path'][0]] # Now save if path == '': issaved = self.save_sut(props, resource_node['path'][0]) else: issaved = self.save_sut_as(resource_node['path'][0], path) if isinstance(issaved, str): logDebug("We could not save this Sut for user = {}.".format(user_info[0])) return issaved return True @cherrypy.expose def save_release_reserved_sut(self, res_query, props={}): """ Save the changes. Sync self.resources with self.reserved_resources and save to the disk """ user_info = self.user_info(props) logFull('CeSuts:save_release_reserved_sut {} {} {}'.format(res_query, props, user_info[0])) result = self.save_reserved_sut(res_query, props) if result and not isinstance(result, str): if ':' in res_query: res_query = res_query.split(':')[0] # Having the id, we can discard and release directly if user_info[0] in self.reservedResources.keys(): if res_query in self.reservedResources[user_info[0]]: node_id = res_query else: resource_node = self.get_resource(res_query) if not resource_node or isinstance(resource_node, str): logFull('User {} can not find the resource {}'.format(user_info[0], res_query)) return None if len(resource_node['path']) > 1: resource_node = self.get_path(resource_node['path'][0], self.resources) node_id = resource_node['id'] reserved_node = self.reservedResources[user_info[0]][node_id] self.reservedResources[user_info[0]].pop(reserved_node['id']) if not self.reservedResources[user_info[0]]: self.reservedResources.pop(user_info[0]) return True else: return result @cherrypy.expose def discard_release_reserved_sut(self, res_query, props={}): """ Discard changes and release SUT. Delete entry from reservedResources. """ return self.discard_release_reserved_resource(res_query, props) @cherrypy.expose def consistency_check_suts(self, user): """ Makes a diff between the content of the self.resources dictionary and what is on the disk. If a sut is in dictionary and is not on the disk anymore, then it is deleted form the self.resources. If a new sut is on the disk, it is loaded in memory. """ def get_disk_sut_names(suts_on_disk): sut_names = [] for sut_d in suts_on_disk: sut_names.append(sut_d['name']) return sut_names # listing all suts result = self.list_all_suts(user) suts_on_disk = get_disk_sut_names(result) # if the status of the CE is stopped for the current user # update the CE memory status = self.project.users[user]['status'] if status == 0: suts_in_memory = self.resources['children'].keys() for sut in suts_in_memory: if sut not in suts_on_disk: id = self.resources['children'][sut].get('id') if user in self.reservedResources and id in self.reservedResources[user]: logDebug('Removed sut `{}` from reserved resources.'.format(sut)) self.reservedResources[user].pop(id) else: logDebug('Sut `{}` cannot be removed from the reserved resources.'.format(sut)) continue if user in self.lockedResources and id in self.lockedResources[user]: logDebug('Removed sut `{}` from locked resources.'.format(sut)) self.lockedResources[user].pop(id) else: logDebug('Sut `{}` cannot be removed from the locked resources.'.format(sut)) continue logDebug('Removed sut `{}` from memory.'.format(sut)) self.resources['children'].pop(sut) return result # Eof()
[]
[]
[ "TWISTER_PATH" ]
[]
["TWISTER_PATH"]
python
1
0
ssh/ssh.go
package ssh import ( "fmt" "net" "os" "os/exec" "strings" log "github.com/Sirupsen/logrus" ) func GetSSHCommand(host string, port int, user string, sshKey string, args ...string) *exec.Cmd { defaultSSHArgs := []string{ "-o", "IdentitiesOnly=yes", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-o", "LogLevel=quiet", // suppress "Warning: Permanently added '[localhost]:2022' (ECDSA) to the list of known hosts." "-p", fmt.Sprintf("%d", port), "-i", sshKey, fmt.Sprintf("%s@%s", user, host), } sshArgs := append(defaultSSHArgs, args...) cmd := exec.Command("ssh", sshArgs...) cmd.Stderr = os.Stderr if os.Getenv("DEBUG") != "" { cmd.Stdout = os.Stdout } log.Debugf("executing: %v", strings.Join(cmd.Args, " ")) return cmd } func GenerateSSHKey(path string) error { if _, err := exec.LookPath("ssh-keygen"); err != nil { return fmt.Errorf("ssh-keygen not found in the path, please install ssh-keygen") } if _, err := os.Stat(path); err != nil { if !os.IsNotExist(err) { return err } cmd := exec.Command("ssh-keygen", "-t", "rsa", "-N", "", "-f", path) if os.Getenv("DEBUG") != "" { cmd.Stdout = os.Stdout } cmd.Stderr = os.Stderr log.Debugf("executing: %v %v\n", cmd.Path, strings.Join(cmd.Args, " ")) if err := cmd.Run(); err != nil { return err } } return nil } func WaitForTCP(addr string) error { for { conn, err := net.Dial("tcp", addr) if err != nil { continue } defer conn.Close() if _, err = conn.Read(make([]byte, 1)); err != nil { continue } break } return nil }
[ "\"DEBUG\"", "\"DEBUG\"" ]
[]
[ "DEBUG" ]
[]
["DEBUG"]
go
1
0
backend/apps/browse/templatetags/file_size.py
from django import template register = template.Library() @register.filter(name='file_size') def sizeof_fmt(num, suffix='B'): for unit in [' ',' K',' M',' G',' T',' P',' E',' Z']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, ' Y', suffix)
[]
[]
[]
[]
[]
python
null
null
null
testflo/isolatedrun.py
""" This is meant to be executed as a subprocess of testflo. """ if __name__ == '__main__': import sys import os import traceback from testflo.test import Test from testflo.cover import save_coverage from testflo.qman import get_client_queue queue = get_client_queue() os.environ['TESTFLO_QUEUE'] = '' try: try: test = Test(sys.argv[1]) test.nocapture = True # so we don't lose stdout test.run() except: print(traceback.format_exc()) test.status = 'FAIL' test.err_msg = traceback.format_exc() save_coverage() except: test.err_msg = traceback.format_exc() test.status = 'FAIL' sys.stdout.flush() sys.stderr.flush() queue.put(test)
[]
[]
[ "TESTFLO_QUEUE" ]
[]
["TESTFLO_QUEUE"]
python
1
0
Lib/test/test_urllib.py
"""Regression tests for what was in Python 2's "urllib" module""" import urllib.parse import urllib.request import urllib.error import http.client import email.message import io import unittest from unittest.mock import patch from test import support from test.support import os_helper, warnings_helper import os try: import ssl except ImportError: ssl = None import sys import tempfile from nturl2path import url2pathname, pathname2url from base64 import b64encode import collections def hexescape(char): """Escape char as RFC 2396 specifies""" hex_repr = hex(ord(char))[2:].upper() if len(hex_repr) == 1: hex_repr = "0%s" % hex_repr return "%" + hex_repr # Shortcut for testing FancyURLopener _urlopener = None def urlopen(url, data=None, proxies=None): """urlopen(url [, data]) -> open file-like object""" global _urlopener if proxies is not None: opener = urllib.request.FancyURLopener(proxies=proxies) elif not _urlopener: opener = FancyURLopener() _urlopener = opener else: opener = _urlopener if data is None: return opener.open(url) else: return opener.open(url, data) def FancyURLopener(): with warnings_helper.check_warnings( ('FancyURLopener style of invoking requests is deprecated.', DeprecationWarning)): return urllib.request.FancyURLopener() def fakehttp(fakedata, mock_close=False): class FakeSocket(io.BytesIO): io_refs = 1 def sendall(self, data): FakeHTTPConnection.buf = data def makefile(self, *args, **kwds): self.io_refs += 1 return self def read(self, amt=None): if self.closed: return b"" return io.BytesIO.read(self, amt) def readline(self, length=None): if self.closed: return b"" return io.BytesIO.readline(self, length) def close(self): self.io_refs -= 1 if self.io_refs == 0: io.BytesIO.close(self) class FakeHTTPConnection(http.client.HTTPConnection): # buffer to store data for verification in urlopen tests. buf = None def connect(self): self.sock = FakeSocket(self.fakedata) type(self).fakesock = self.sock if mock_close: # bpo-36918: HTTPConnection destructor calls close() which calls # flush(). Problem: flush() calls self.fp.flush() which raises # "ValueError: I/O operation on closed file" which is logged as an # "Exception ignored in". Override close() to silence this error. def close(self): pass FakeHTTPConnection.fakedata = fakedata return FakeHTTPConnection class FakeHTTPMixin(object): def fakehttp(self, fakedata, mock_close=False): fake_http_class = fakehttp(fakedata, mock_close=mock_close) self._connection_class = http.client.HTTPConnection http.client.HTTPConnection = fake_http_class def unfakehttp(self): http.client.HTTPConnection = self._connection_class class FakeFTPMixin(object): def fakeftp(self): class FakeFtpWrapper(object): def __init__(self, user, passwd, host, port, dirs, timeout=None, persistent=True): pass def retrfile(self, file, type): return io.BytesIO(), 0 def close(self): pass self._ftpwrapper_class = urllib.request.ftpwrapper urllib.request.ftpwrapper = FakeFtpWrapper def unfakeftp(self): urllib.request.ftpwrapper = self._ftpwrapper_class class urlopen_FileTests(unittest.TestCase): """Test urlopen() opening a temporary file. Try to test as much functionality as possible so as to cut down on reliance on connecting to the Net for testing. """ def setUp(self): # Create a temp file to use for testing self.text = bytes("test_urllib: %s\n" % self.__class__.__name__, "ascii") f = open(os_helper.TESTFN, 'wb') try: f.write(self.text) finally: f.close() self.pathname = os_helper.TESTFN self.quoted_pathname = urllib.parse.quote(self.pathname) self.returned_obj = urlopen("file:%s" % self.quoted_pathname) def tearDown(self): """Shut down the open object""" self.returned_obj.close() os.remove(os_helper.TESTFN) def test_interface(self): # Make sure object returned by urlopen() has the specified methods for attr in ("read", "readline", "readlines", "fileno", "close", "info", "geturl", "getcode", "__iter__"): self.assertTrue(hasattr(self.returned_obj, attr), "object returned by urlopen() lacks %s attribute" % attr) def test_read(self): self.assertEqual(self.text, self.returned_obj.read()) def test_readline(self): self.assertEqual(self.text, self.returned_obj.readline()) self.assertEqual(b'', self.returned_obj.readline(), "calling readline() after exhausting the file did not" " return an empty string") def test_readlines(self): lines_list = self.returned_obj.readlines() self.assertEqual(len(lines_list), 1, "readlines() returned the wrong number of lines") self.assertEqual(lines_list[0], self.text, "readlines() returned improper text") def test_fileno(self): file_num = self.returned_obj.fileno() self.assertIsInstance(file_num, int, "fileno() did not return an int") self.assertEqual(os.read(file_num, len(self.text)), self.text, "Reading on the file descriptor returned by fileno() " "did not return the expected text") def test_close(self): # Test close() by calling it here and then having it be called again # by the tearDown() method for the test self.returned_obj.close() def test_headers(self): self.assertIsInstance(self.returned_obj.headers, email.message.Message) def test_url(self): self.assertEqual(self.returned_obj.url, self.quoted_pathname) @unittest.skip("TODO: RUSTPYTHON (AttributeError: 'BufferedReader' object has no attribute 'status')") def test_status(self): self.assertIsNone(self.returned_obj.status) def test_info(self): self.assertIsInstance(self.returned_obj.info(), email.message.Message) def test_geturl(self): self.assertEqual(self.returned_obj.geturl(), self.quoted_pathname) def test_getcode(self): self.assertIsNone(self.returned_obj.getcode()) def test_iter(self): # Test iterator # Don't need to count number of iterations since test would fail the # instant it returned anything beyond the first line from the # comparison. # Use the iterator in the usual implicit way to test for ticket #4608. for line in self.returned_obj: self.assertEqual(line, self.text) def test_relativelocalfile(self): self.assertRaises(ValueError,urllib.request.urlopen,'./' + self.pathname) class ProxyTests(unittest.TestCase): def setUp(self): # Records changes to env vars self.env = os_helper.EnvironmentVarGuard() # Delete all proxy related env vars for k in list(os.environ): if 'proxy' in k.lower(): self.env.unset(k) def tearDown(self): # Restore all proxy related env vars self.env.__exit__() del self.env def test_getproxies_environment_keep_no_proxies(self): self.env.set('NO_PROXY', 'localhost') proxies = urllib.request.getproxies_environment() # getproxies_environment use lowered case truncated (no '_proxy') keys self.assertEqual('localhost', proxies['no']) # List of no_proxies with space. self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com:1234') self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com')) self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888')) self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234')) def test_proxy_cgi_ignore(self): try: self.env.set('HTTP_PROXY', 'http://somewhere:3128') proxies = urllib.request.getproxies_environment() self.assertEqual('http://somewhere:3128', proxies['http']) self.env.set('REQUEST_METHOD', 'GET') proxies = urllib.request.getproxies_environment() self.assertNotIn('http', proxies) finally: self.env.unset('REQUEST_METHOD') self.env.unset('HTTP_PROXY') def test_proxy_bypass_environment_host_match(self): bypass = urllib.request.proxy_bypass_environment self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com:1234, .d.o.t') self.assertTrue(bypass('localhost')) self.assertTrue(bypass('LocalHost')) # MixedCase self.assertTrue(bypass('LOCALHOST')) # UPPERCASE self.assertTrue(bypass('.localhost')) self.assertTrue(bypass('newdomain.com:1234')) self.assertTrue(bypass('.newdomain.com:1234')) self.assertTrue(bypass('foo.d.o.t')) # issue 29142 self.assertTrue(bypass('d.o.t')) self.assertTrue(bypass('anotherdomain.com:8888')) self.assertTrue(bypass('.anotherdomain.com:8888')) self.assertTrue(bypass('www.newdomain.com:1234')) self.assertFalse(bypass('prelocalhost')) self.assertFalse(bypass('newdomain.com')) # no port self.assertFalse(bypass('newdomain.com:1235')) # wrong port def test_proxy_bypass_environment_always_match(self): bypass = urllib.request.proxy_bypass_environment self.env.set('NO_PROXY', '*') self.assertTrue(bypass('newdomain.com')) self.assertTrue(bypass('newdomain.com:1234')) self.env.set('NO_PROXY', '*, anotherdomain.com') self.assertTrue(bypass('anotherdomain.com')) self.assertFalse(bypass('newdomain.com')) self.assertFalse(bypass('newdomain.com:1234')) def test_proxy_bypass_environment_newline(self): bypass = urllib.request.proxy_bypass_environment self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com:1234') self.assertFalse(bypass('localhost\n')) self.assertFalse(bypass('anotherdomain.com:8888\n')) self.assertFalse(bypass('newdomain.com:1234\n')) class ProxyTests_withOrderedEnv(unittest.TestCase): def setUp(self): # We need to test conditions, where variable order _is_ significant self._saved_env = os.environ # Monkey patch os.environ, start with empty fake environment os.environ = collections.OrderedDict() def tearDown(self): os.environ = self._saved_env def test_getproxies_environment_prefer_lowercase(self): # Test lowercase preference with removal os.environ['no_proxy'] = '' os.environ['No_Proxy'] = 'localhost' self.assertFalse(urllib.request.proxy_bypass_environment('localhost')) self.assertFalse(urllib.request.proxy_bypass_environment('arbitrary')) os.environ['http_proxy'] = '' os.environ['HTTP_PROXY'] = 'http://somewhere:3128' proxies = urllib.request.getproxies_environment() self.assertEqual({}, proxies) # Test lowercase preference of proxy bypass and correct matching including ports os.environ['no_proxy'] = 'localhost, noproxy.com, my.proxy:1234' os.environ['No_Proxy'] = 'xyz.com' self.assertTrue(urllib.request.proxy_bypass_environment('localhost')) self.assertTrue(urllib.request.proxy_bypass_environment('noproxy.com:5678')) self.assertTrue(urllib.request.proxy_bypass_environment('my.proxy:1234')) self.assertFalse(urllib.request.proxy_bypass_environment('my.proxy')) self.assertFalse(urllib.request.proxy_bypass_environment('arbitrary')) # Test lowercase preference with replacement os.environ['http_proxy'] = 'http://somewhere:3128' os.environ['Http_Proxy'] = 'http://somewhereelse:3128' proxies = urllib.request.getproxies_environment() self.assertEqual('http://somewhere:3128', proxies['http']) class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin, FakeFTPMixin): """Test urlopen() opening a fake http connection.""" def check_read(self, ver): self.fakehttp(b"HTTP/" + ver + b" 200 OK\r\n\r\nHello!") try: fp = urlopen("http://python.org/") self.assertEqual(fp.readline(), b"Hello!") self.assertEqual(fp.readline(), b"") self.assertEqual(fp.geturl(), 'http://python.org/') self.assertEqual(fp.getcode(), 200) finally: self.unfakehttp() def test_url_fragment(self): # Issue #11703: geturl() omits fragments in the original URL. url = 'http://docs.python.org/library/urllib.html#OK' self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!") try: fp = urllib.request.urlopen(url) self.assertEqual(fp.geturl(), url) finally: self.unfakehttp() def test_willclose(self): self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!") try: resp = urlopen("http://www.python.org") self.assertTrue(resp.fp.will_close) finally: self.unfakehttp() # TODO: RUSTPYTHON @unittest.expectedFailure @unittest.skipUnless(ssl, "ssl module required") def test_url_path_with_control_char_rejected(self): for char_no in list(range(0, 0x21)) + [0x7f]: char = chr(char_no) schemeless_url = f"//localhost:7777/test{char}/" self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.") try: # We explicitly test urllib.request.urlopen() instead of the top # level 'def urlopen()' function defined in this... (quite ugly) # test suite. They use different url opening codepaths. Plain # urlopen uses FancyURLOpener which goes via a codepath that # calls urllib.parse.quote() on the URL which makes all of the # above attempts at injection within the url _path_ safe. escaped_char_repr = repr(char).replace('\\', r'\\') InvalidURL = http.client.InvalidURL with self.assertRaisesRegex( InvalidURL, f"contain control.*{escaped_char_repr}"): urllib.request.urlopen(f"http:{schemeless_url}") with self.assertRaisesRegex( InvalidURL, f"contain control.*{escaped_char_repr}"): urllib.request.urlopen(f"https:{schemeless_url}") # This code path quotes the URL so there is no injection. resp = urlopen(f"http:{schemeless_url}") self.assertNotIn(char, resp.geturl()) finally: self.unfakehttp() # TODO: RUSTPYTHON @unittest.expectedFailure @unittest.skipUnless(ssl, "ssl module required") def test_url_path_with_newline_header_injection_rejected(self): self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.") host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\r\nTEST: 123" schemeless_url = "//" + host + ":8080/test/?test=a" try: # We explicitly test urllib.request.urlopen() instead of the top # level 'def urlopen()' function defined in this... (quite ugly) # test suite. They use different url opening codepaths. Plain # urlopen uses FancyURLOpener which goes via a codepath that # calls urllib.parse.quote() on the URL which makes all of the # above attempts at injection within the url _path_ safe. InvalidURL = http.client.InvalidURL with self.assertRaisesRegex( InvalidURL, r"contain control.*\\r.*(found at least . .)"): urllib.request.urlopen(f"http:{schemeless_url}") with self.assertRaisesRegex(InvalidURL, r"contain control.*\\n"): urllib.request.urlopen(f"https:{schemeless_url}") # This code path quotes the URL so there is no injection. resp = urlopen(f"http:{schemeless_url}") self.assertNotIn(' ', resp.geturl()) self.assertNotIn('\r', resp.geturl()) self.assertNotIn('\n', resp.geturl()) finally: self.unfakehttp() # TODO: RUSTPYTHON @unittest.expectedFailure @unittest.skipUnless(ssl, "ssl module required") def test_url_host_with_control_char_rejected(self): for char_no in list(range(0, 0x21)) + [0x7f]: char = chr(char_no) schemeless_url = f"//localhost{char}/test/" self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.") try: escaped_char_repr = repr(char).replace('\\', r'\\') InvalidURL = http.client.InvalidURL with self.assertRaisesRegex( InvalidURL, f"contain control.*{escaped_char_repr}"): urlopen(f"http:{schemeless_url}") with self.assertRaisesRegex(InvalidURL, f"contain control.*{escaped_char_repr}"): urlopen(f"https:{schemeless_url}") finally: self.unfakehttp() # TODO: RUSTPYTHON @unittest.expectedFailure @unittest.skipUnless(ssl, "ssl module required") def test_url_host_with_newline_header_injection_rejected(self): self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.") host = "localhost\r\nX-injected: header\r\n" schemeless_url = "//" + host + ":8080/test/?test=a" try: InvalidURL = http.client.InvalidURL with self.assertRaisesRegex( InvalidURL, r"contain control.*\\r"): urlopen(f"http:{schemeless_url}") with self.assertRaisesRegex(InvalidURL, r"contain control.*\\n"): urlopen(f"https:{schemeless_url}") finally: self.unfakehttp() def test_read_0_9(self): # "0.9" response accepted (but not "simple responses" without # a status line) self.check_read(b"0.9") def test_read_1_0(self): self.check_read(b"1.0") def test_read_1_1(self): self.check_read(b"1.1") def test_read_bogus(self): # urlopen() should raise OSError for many error codes. self.fakehttp(b'''HTTP/1.1 401 Authentication Required Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Connection: close Content-Type: text/html; charset=iso-8859-1 ''', mock_close=True) try: self.assertRaises(OSError, urlopen, "http://python.org/") finally: self.unfakehttp() def test_invalid_redirect(self): # urlopen() should raise OSError for many error codes. self.fakehttp(b'''HTTP/1.1 302 Found Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Location: file://guidocomputer.athome.com:/python/license Connection: close Content-Type: text/html; charset=iso-8859-1 ''', mock_close=True) try: msg = "Redirection to url 'file:" with self.assertRaisesRegex(urllib.error.HTTPError, msg): urlopen("http://python.org/") finally: self.unfakehttp() def test_redirect_limit_independent(self): # Ticket #12923: make sure independent requests each use their # own retry limit. for i in range(FancyURLopener().maxtries): self.fakehttp(b'''HTTP/1.1 302 Found Location: file://guidocomputer.athome.com:/python/license Connection: close ''', mock_close=True) try: self.assertRaises(urllib.error.HTTPError, urlopen, "http://something") finally: self.unfakehttp() def test_empty_socket(self): # urlopen() raises OSError if the underlying socket does not send any # data. (#1680230) self.fakehttp(b'') try: self.assertRaises(OSError, urlopen, "http://something") finally: self.unfakehttp() def test_missing_localfile(self): # Test for #10836 with self.assertRaises(urllib.error.URLError) as e: urlopen('file://localhost/a/file/which/doesnot/exists.py') self.assertTrue(e.exception.filename) self.assertTrue(e.exception.reason) def test_file_notexists(self): fd, tmp_file = tempfile.mkstemp() tmp_fileurl = 'file://localhost/' + tmp_file.replace(os.path.sep, '/') try: self.assertTrue(os.path.exists(tmp_file)) with urlopen(tmp_fileurl) as fobj: self.assertTrue(fobj) finally: os.close(fd) os.unlink(tmp_file) self.assertFalse(os.path.exists(tmp_file)) with self.assertRaises(urllib.error.URLError): urlopen(tmp_fileurl) def test_ftp_nohost(self): test_ftp_url = 'ftp:///path' with self.assertRaises(urllib.error.URLError) as e: urlopen(test_ftp_url) self.assertFalse(e.exception.filename) self.assertTrue(e.exception.reason) def test_ftp_nonexisting(self): with self.assertRaises(urllib.error.URLError) as e: urlopen('ftp://localhost/a/file/which/doesnot/exists.py') self.assertFalse(e.exception.filename) self.assertTrue(e.exception.reason) @patch.object(urllib.request, 'MAXFTPCACHE', 0) def test_ftp_cache_pruning(self): self.fakeftp() try: urllib.request.ftpcache['test'] = urllib.request.ftpwrapper('user', 'pass', 'localhost', 21, []) urlopen('ftp://localhost') finally: self.unfakeftp() def test_userpass_inurl(self): self.fakehttp(b"HTTP/1.0 200 OK\r\n\r\nHello!") try: fp = urlopen("http://user:[email protected]/") self.assertEqual(fp.readline(), b"Hello!") self.assertEqual(fp.readline(), b"") self.assertEqual(fp.geturl(), 'http://user:[email protected]/') self.assertEqual(fp.getcode(), 200) finally: self.unfakehttp() def test_userpass_inurl_w_spaces(self): self.fakehttp(b"HTTP/1.0 200 OK\r\n\r\nHello!") try: userpass = "a b:c d" url = "http://{}@python.org/".format(userpass) fakehttp_wrapper = http.client.HTTPConnection authorization = ("Authorization: Basic %s\r\n" % b64encode(userpass.encode("ASCII")).decode("ASCII")) fp = urlopen(url) # The authorization header must be in place self.assertIn(authorization, fakehttp_wrapper.buf.decode("UTF-8")) self.assertEqual(fp.readline(), b"Hello!") self.assertEqual(fp.readline(), b"") # the spaces are quoted in URL so no match self.assertNotEqual(fp.geturl(), url) self.assertEqual(fp.getcode(), 200) finally: self.unfakehttp() def test_URLopener_deprecation(self): with warnings_helper.check_warnings(('',DeprecationWarning)): urllib.request.URLopener() @unittest.skipUnless(ssl, "ssl module required") def test_cafile_and_context(self): context = ssl.create_default_context() with warnings_helper.check_warnings(('', DeprecationWarning)): with self.assertRaises(ValueError): urllib.request.urlopen( "https://localhost", cafile="/nonexistent/path", context=context ) @unittest.skip("TODO: RUSTPYTHON, error in setUp(); ValueError: error decoding base64: Invalid byte 32, offset 95.") class urlopen_DataTests(unittest.TestCase): """Test urlopen() opening a data URL.""" def setUp(self): # clear _opener global variable self.addCleanup(urllib.request.urlcleanup) # text containing URL special- and unicode-characters self.text = "test data URLs :;,%=& \u00f6 \u00c4 " # 2x1 pixel RGB PNG image with one black and one white pixel self.image = ( b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x02\x00\x00\x00' b'\x01\x08\x02\x00\x00\x00{@\xe8\xdd\x00\x00\x00\x01sRGB\x00\xae' b'\xce\x1c\xe9\x00\x00\x00\x0fIDAT\x08\xd7c```\xf8\xff\xff?\x00' b'\x06\x01\x02\xfe\no/\x1e\x00\x00\x00\x00IEND\xaeB`\x82') self.text_url = ( "data:text/plain;charset=UTF-8,test%20data%20URLs%20%3A%3B%2C%25%3" "D%26%20%C3%B6%20%C3%84%20") self.text_url_base64 = ( "data:text/plain;charset=ISO-8859-1;base64,dGVzdCBkYXRhIFVSTHMgOjs" "sJT0mIPYgxCA%3D") # base64 encoded data URL that contains ignorable spaces, # such as "\n", " ", "%0A", and "%20". self.image_url = ( "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7\n" "QOjdAAAAAXNSR0IArs4c6QAAAA9JREFUCNdj%0AYGBg%2BP//PwAGAQL%2BCm8 " "vHgAAAABJRU5ErkJggg%3D%3D%0A%20") self.text_url_resp = urllib.request.urlopen(self.text_url) self.text_url_base64_resp = urllib.request.urlopen( self.text_url_base64) self.image_url_resp = urllib.request.urlopen(self.image_url) def test_interface(self): # Make sure object returned by urlopen() has the specified methods for attr in ("read", "readline", "readlines", "close", "info", "geturl", "getcode", "__iter__"): self.assertTrue(hasattr(self.text_url_resp, attr), "object returned by urlopen() lacks %s attribute" % attr) def test_info(self): self.assertIsInstance(self.text_url_resp.info(), email.message.Message) self.assertEqual(self.text_url_base64_resp.info().get_params(), [('text/plain', ''), ('charset', 'ISO-8859-1')]) self.assertEqual(self.image_url_resp.info()['content-length'], str(len(self.image))) self.assertEqual(urllib.request.urlopen("data:,").info().get_params(), [('text/plain', ''), ('charset', 'US-ASCII')]) def test_geturl(self): self.assertEqual(self.text_url_resp.geturl(), self.text_url) self.assertEqual(self.text_url_base64_resp.geturl(), self.text_url_base64) self.assertEqual(self.image_url_resp.geturl(), self.image_url) def test_read_text(self): self.assertEqual(self.text_url_resp.read().decode( dict(self.text_url_resp.info().get_params())['charset']), self.text) def test_read_text_base64(self): self.assertEqual(self.text_url_base64_resp.read().decode( dict(self.text_url_base64_resp.info().get_params())['charset']), self.text) def test_read_image(self): self.assertEqual(self.image_url_resp.read(), self.image) def test_missing_comma(self): self.assertRaises(ValueError,urllib.request.urlopen,'data:text/plain') def test_invalid_base64_data(self): # missing padding character self.assertRaises(ValueError,urllib.request.urlopen,'data:;base64,Cg=') class urlretrieve_FileTests(unittest.TestCase): """Test urllib.urlretrieve() on local files""" def setUp(self): # clear _opener global variable self.addCleanup(urllib.request.urlcleanup) # Create a list of temporary files. Each item in the list is a file # name (absolute path or relative to the current working directory). # All files in this list will be deleted in the tearDown method. Note, # this only helps to makes sure temporary files get deleted, but it # does nothing about trying to close files that may still be open. It # is the responsibility of the developer to properly close files even # when exceptional conditions occur. self.tempFiles = [] # Create a temporary file. self.registerFileForCleanUp(os_helper.TESTFN) self.text = b'testing urllib.urlretrieve' try: FILE = open(os_helper.TESTFN, 'wb') FILE.write(self.text) FILE.close() finally: try: FILE.close() except: pass def tearDown(self): # Delete the temporary files. for each in self.tempFiles: try: os.remove(each) except: pass def constructLocalFileUrl(self, filePath): filePath = os.path.abspath(filePath) try: filePath.encode("utf-8") except UnicodeEncodeError: raise unittest.SkipTest("filePath is not encodable to utf8") return "file://%s" % urllib.request.pathname2url(filePath) def createNewTempFile(self, data=b""): """Creates a new temporary file containing the specified data, registers the file for deletion during the test fixture tear down, and returns the absolute path of the file.""" newFd, newFilePath = tempfile.mkstemp() try: self.registerFileForCleanUp(newFilePath) newFile = os.fdopen(newFd, "wb") newFile.write(data) newFile.close() finally: try: newFile.close() except: pass return newFilePath def registerFileForCleanUp(self, fileName): self.tempFiles.append(fileName) def test_basic(self): # Make sure that a local file just gets its own location returned and # a headers value is returned. result = urllib.request.urlretrieve("file:%s" % os_helper.TESTFN) self.assertEqual(result[0], os_helper.TESTFN) self.assertIsInstance(result[1], email.message.Message, "did not get an email.message.Message instance " "as second returned value") def test_copy(self): # Test that setting the filename argument works. second_temp = "%s.2" % os_helper.TESTFN self.registerFileForCleanUp(second_temp) result = urllib.request.urlretrieve(self.constructLocalFileUrl( os_helper.TESTFN), second_temp) self.assertEqual(second_temp, result[0]) self.assertTrue(os.path.exists(second_temp), "copy of the file was not " "made") FILE = open(second_temp, 'rb') try: text = FILE.read() FILE.close() finally: try: FILE.close() except: pass self.assertEqual(self.text, text) def test_reporthook(self): # Make sure that the reporthook works. def hooktester(block_count, block_read_size, file_size, count_holder=[0]): self.assertIsInstance(block_count, int) self.assertIsInstance(block_read_size, int) self.assertIsInstance(file_size, int) self.assertEqual(block_count, count_holder[0]) count_holder[0] = count_holder[0] + 1 second_temp = "%s.2" % os_helper.TESTFN self.registerFileForCleanUp(second_temp) urllib.request.urlretrieve( self.constructLocalFileUrl(os_helper.TESTFN), second_temp, hooktester) def test_reporthook_0_bytes(self): # Test on zero length file. Should call reporthook only 1 time. report = [] def hooktester(block_count, block_read_size, file_size, _report=report): _report.append((block_count, block_read_size, file_size)) srcFileName = self.createNewTempFile() urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName), os_helper.TESTFN, hooktester) self.assertEqual(len(report), 1) self.assertEqual(report[0][2], 0) def test_reporthook_5_bytes(self): # Test on 5 byte file. Should call reporthook only 2 times (once when # the "network connection" is established and once when the block is # read). report = [] def hooktester(block_count, block_read_size, file_size, _report=report): _report.append((block_count, block_read_size, file_size)) srcFileName = self.createNewTempFile(b"x" * 5) urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName), os_helper.TESTFN, hooktester) self.assertEqual(len(report), 2) self.assertEqual(report[0][2], 5) self.assertEqual(report[1][2], 5) def test_reporthook_8193_bytes(self): # Test on 8193 byte file. Should call reporthook only 3 times (once # when the "network connection" is established, once for the next 8192 # bytes, and once for the last byte). report = [] def hooktester(block_count, block_read_size, file_size, _report=report): _report.append((block_count, block_read_size, file_size)) srcFileName = self.createNewTempFile(b"x" * 8193) urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName), os_helper.TESTFN, hooktester) self.assertEqual(len(report), 3) self.assertEqual(report[0][2], 8193) self.assertEqual(report[0][1], 8192) self.assertEqual(report[1][1], 8192) self.assertEqual(report[2][1], 8192) class urlretrieve_HttpTests(unittest.TestCase, FakeHTTPMixin): """Test urllib.urlretrieve() using fake http connections""" def test_short_content_raises_ContentTooShortError(self): self.addCleanup(urllib.request.urlcleanup) self.fakehttp(b'''HTTP/1.1 200 OK Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Connection: close Content-Length: 100 Content-Type: text/html; charset=iso-8859-1 FF ''') def _reporthook(par1, par2, par3): pass with self.assertRaises(urllib.error.ContentTooShortError): try: urllib.request.urlretrieve(support.TEST_HTTP_URL, reporthook=_reporthook) finally: self.unfakehttp() def test_short_content_raises_ContentTooShortError_without_reporthook(self): self.addCleanup(urllib.request.urlcleanup) self.fakehttp(b'''HTTP/1.1 200 OK Date: Wed, 02 Jan 2008 03:03:54 GMT Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e Connection: close Content-Length: 100 Content-Type: text/html; charset=iso-8859-1 FF ''') with self.assertRaises(urllib.error.ContentTooShortError): try: urllib.request.urlretrieve(support.TEST_HTTP_URL) finally: self.unfakehttp() class QuotingTests(unittest.TestCase): r"""Tests for urllib.quote() and urllib.quote_plus() According to RFC 3986 (Uniform Resource Identifiers), to escape a character you write it as '%' + <2 character US-ASCII hex value>. The Python code of ``'%' + hex(ord(<character>))[2:]`` escapes a character properly. Case does not matter on the hex letters. The various character sets specified are: Reserved characters : ";/?:@&=+$," Have special meaning in URIs and must be escaped if not being used for their special meaning Data characters : letters, digits, and "-_.!~*'()" Unreserved and do not need to be escaped; can be, though, if desired Control characters : 0x00 - 0x1F, 0x7F Have no use in URIs so must be escaped space : 0x20 Must be escaped Delimiters : '<>#%"' Must be escaped Unwise : "{}|\^[]`" Must be escaped """ def test_never_quote(self): # Make sure quote() does not quote letters, digits, and "_,.-" do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "_.-~"]) result = urllib.parse.quote(do_not_quote) self.assertEqual(do_not_quote, result, "using quote(): %r != %r" % (do_not_quote, result)) result = urllib.parse.quote_plus(do_not_quote) self.assertEqual(do_not_quote, result, "using quote_plus(): %r != %r" % (do_not_quote, result)) def test_default_safe(self): # Test '/' is default value for 'safe' parameter self.assertEqual(urllib.parse.quote.__defaults__[0], '/') def test_safe(self): # Test setting 'safe' parameter does what it should do quote_by_default = "<>" result = urllib.parse.quote(quote_by_default, safe=quote_by_default) self.assertEqual(quote_by_default, result, "using quote(): %r != %r" % (quote_by_default, result)) result = urllib.parse.quote_plus(quote_by_default, safe=quote_by_default) self.assertEqual(quote_by_default, result, "using quote_plus(): %r != %r" % (quote_by_default, result)) # Safe expressed as bytes rather than str result = urllib.parse.quote(quote_by_default, safe=b"<>") self.assertEqual(quote_by_default, result, "using quote(): %r != %r" % (quote_by_default, result)) # "Safe" non-ASCII characters should have no effect # (Since URIs are not allowed to have non-ASCII characters) result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="\xfc") expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="") self.assertEqual(expect, result, "using quote(): %r != %r" % (expect, result)) # Same as above, but using a bytes rather than str result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe=b"\xfc") expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="") self.assertEqual(expect, result, "using quote(): %r != %r" % (expect, result)) def test_default_quoting(self): # Make sure all characters that should be quoted are by default sans # space (separate test for that). should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F should_quote.append(r'<>#%"{}|\^[]`') should_quote.append(chr(127)) # For 0x7F should_quote = ''.join(should_quote) for char in should_quote: result = urllib.parse.quote(char) self.assertEqual(hexescape(char), result, "using quote(): " "%s should be escaped to %s, not %s" % (char, hexescape(char), result)) result = urllib.parse.quote_plus(char) self.assertEqual(hexescape(char), result, "using quote_plus(): " "%s should be escapes to %s, not %s" % (char, hexescape(char), result)) del should_quote partial_quote = "ab[]cd" expected = "ab%5B%5Dcd" result = urllib.parse.quote(partial_quote) self.assertEqual(expected, result, "using quote(): %r != %r" % (expected, result)) result = urllib.parse.quote_plus(partial_quote) self.assertEqual(expected, result, "using quote_plus(): %r != %r" % (expected, result)) def test_quoting_space(self): # Make sure quote() and quote_plus() handle spaces as specified in # their unique way result = urllib.parse.quote(' ') self.assertEqual(result, hexescape(' '), "using quote(): %r != %r" % (result, hexescape(' '))) result = urllib.parse.quote_plus(' ') self.assertEqual(result, '+', "using quote_plus(): %r != +" % result) given = "a b cd e f" expect = given.replace(' ', hexescape(' ')) result = urllib.parse.quote(given) self.assertEqual(expect, result, "using quote(): %r != %r" % (expect, result)) expect = given.replace(' ', '+') result = urllib.parse.quote_plus(given) self.assertEqual(expect, result, "using quote_plus(): %r != %r" % (expect, result)) def test_quoting_plus(self): self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma'), 'alpha%2Bbeta+gamma') self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', '+'), 'alpha+beta+gamma') # Test with bytes self.assertEqual(urllib.parse.quote_plus(b'alpha+beta gamma'), 'alpha%2Bbeta+gamma') # Test with safe bytes self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', b'+'), 'alpha+beta+gamma') def test_quote_bytes(self): # Bytes should quote directly to percent-encoded values given = b"\xa2\xd8ab\xff" expect = "%A2%D8ab%FF" result = urllib.parse.quote(given) self.assertEqual(expect, result, "using quote(): %r != %r" % (expect, result)) # Encoding argument should raise type error on bytes input self.assertRaises(TypeError, urllib.parse.quote, given, encoding="latin-1") # quote_from_bytes should work the same result = urllib.parse.quote_from_bytes(given) self.assertEqual(expect, result, "using quote_from_bytes(): %r != %r" % (expect, result)) def test_quote_with_unicode(self): # Characters in Latin-1 range, encoded by default in UTF-8 given = "\xa2\xd8ab\xff" expect = "%C2%A2%C3%98ab%C3%BF" result = urllib.parse.quote(given) self.assertEqual(expect, result, "using quote(): %r != %r" % (expect, result)) # Characters in Latin-1 range, encoded by with None (default) result = urllib.parse.quote(given, encoding=None, errors=None) self.assertEqual(expect, result, "using quote(): %r != %r" % (expect, result)) # Characters in Latin-1 range, encoded with Latin-1 given = "\xa2\xd8ab\xff" expect = "%A2%D8ab%FF" result = urllib.parse.quote(given, encoding="latin-1") self.assertEqual(expect, result, "using quote(): %r != %r" % (expect, result)) # Characters in BMP, encoded by default in UTF-8 given = "\u6f22\u5b57" # "Kanji" expect = "%E6%BC%A2%E5%AD%97" result = urllib.parse.quote(given) self.assertEqual(expect, result, "using quote(): %r != %r" % (expect, result)) # Characters in BMP, encoded with Latin-1 given = "\u6f22\u5b57" self.assertRaises(UnicodeEncodeError, urllib.parse.quote, given, encoding="latin-1") # Characters in BMP, encoded with Latin-1, with replace error handling given = "\u6f22\u5b57" expect = "%3F%3F" # "??" result = urllib.parse.quote(given, encoding="latin-1", errors="replace") self.assertEqual(expect, result, "using quote(): %r != %r" % (expect, result)) # Characters in BMP, Latin-1, with xmlcharref error handling given = "\u6f22\u5b57" expect = "%26%2328450%3B%26%2323383%3B" # "&#28450;&#23383;" result = urllib.parse.quote(given, encoding="latin-1", errors="xmlcharrefreplace") self.assertEqual(expect, result, "using quote(): %r != %r" % (expect, result)) def test_quote_plus_with_unicode(self): # Encoding (latin-1) test for quote_plus given = "\xa2\xd8 \xff" expect = "%A2%D8+%FF" result = urllib.parse.quote_plus(given, encoding="latin-1") self.assertEqual(expect, result, "using quote_plus(): %r != %r" % (expect, result)) # Errors test for quote_plus given = "ab\u6f22\u5b57 cd" expect = "ab%3F%3F+cd" result = urllib.parse.quote_plus(given, encoding="latin-1", errors="replace") self.assertEqual(expect, result, "using quote_plus(): %r != %r" % (expect, result)) class UnquotingTests(unittest.TestCase): """Tests for unquote() and unquote_plus() See the doc string for quoting_Tests for details on quoting and such. """ def test_unquoting(self): # Make sure unquoting of all ASCII values works escape_list = [] for num in range(128): given = hexescape(chr(num)) expect = chr(num) result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) result = urllib.parse.unquote_plus(given) self.assertEqual(expect, result, "using unquote_plus(): %r != %r" % (expect, result)) escape_list.append(given) escape_string = ''.join(escape_list) del escape_list result = urllib.parse.unquote(escape_string) self.assertEqual(result.count('%'), 1, "using unquote(): not all characters escaped: " "%s" % result) self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, None) self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, ()) def test_unquoting_badpercent(self): # Test unquoting on bad percent-escapes given = '%xab' expect = given result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) given = '%x' expect = given result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) given = '%' expect = given result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) # unquote_to_bytes given = '%xab' expect = bytes(given, 'ascii') result = urllib.parse.unquote_to_bytes(given) self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r" % (expect, result)) given = '%x' expect = bytes(given, 'ascii') result = urllib.parse.unquote_to_bytes(given) self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r" % (expect, result)) given = '%' expect = bytes(given, 'ascii') result = urllib.parse.unquote_to_bytes(given) self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r" % (expect, result)) self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, None) self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, ()) def test_unquoting_mixed_case(self): # Test unquoting on mixed-case hex digits in the percent-escapes given = '%Ab%eA' expect = b'\xab\xea' result = urllib.parse.unquote_to_bytes(given) self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r" % (expect, result)) def test_unquoting_parts(self): # Make sure unquoting works when have non-quoted characters # interspersed given = 'ab%sd' % hexescape('c') expect = "abcd" result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using quote(): %r != %r" % (expect, result)) result = urllib.parse.unquote_plus(given) self.assertEqual(expect, result, "using unquote_plus(): %r != %r" % (expect, result)) def test_unquoting_plus(self): # Test difference between unquote() and unquote_plus() given = "are+there+spaces..." expect = given result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) expect = given.replace('+', ' ') result = urllib.parse.unquote_plus(given) self.assertEqual(expect, result, "using unquote_plus(): %r != %r" % (expect, result)) def test_unquote_to_bytes(self): given = 'br%C3%BCckner_sapporo_20050930.doc' expect = b'br\xc3\xbcckner_sapporo_20050930.doc' result = urllib.parse.unquote_to_bytes(given) self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r" % (expect, result)) # Test on a string with unescaped non-ASCII characters # (Technically an invalid URI; expect those characters to be UTF-8 # encoded). result = urllib.parse.unquote_to_bytes("\u6f22%C3%BC") expect = b'\xe6\xbc\xa2\xc3\xbc' # UTF-8 for "\u6f22\u00fc" self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r" % (expect, result)) # Test with a bytes as input given = b'%A2%D8ab%FF' expect = b'\xa2\xd8ab\xff' result = urllib.parse.unquote_to_bytes(given) self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r" % (expect, result)) # Test with a bytes as input, with unescaped non-ASCII bytes # (Technically an invalid URI; expect those bytes to be preserved) given = b'%A2\xd8ab%FF' expect = b'\xa2\xd8ab\xff' result = urllib.parse.unquote_to_bytes(given) self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r" % (expect, result)) def test_unquote_with_unicode(self): # Characters in the Latin-1 range, encoded with UTF-8 given = 'br%C3%BCckner_sapporo_20050930.doc' expect = 'br\u00fcckner_sapporo_20050930.doc' result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) # Characters in the Latin-1 range, encoded with None (default) result = urllib.parse.unquote(given, encoding=None, errors=None) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) # Characters in the Latin-1 range, encoded with Latin-1 result = urllib.parse.unquote('br%FCckner_sapporo_20050930.doc', encoding="latin-1") expect = 'br\u00fcckner_sapporo_20050930.doc' self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) # Characters in BMP, encoded with UTF-8 given = "%E6%BC%A2%E5%AD%97" expect = "\u6f22\u5b57" # "Kanji" result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) # Decode with UTF-8, invalid sequence given = "%F3%B1" expect = "\ufffd" # Replacement character result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) # Decode with UTF-8, invalid sequence, replace errors result = urllib.parse.unquote(given, errors="replace") self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) # Decode with UTF-8, invalid sequence, ignoring errors given = "%F3%B1" expect = "" result = urllib.parse.unquote(given, errors="ignore") self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) # A mix of non-ASCII and percent-encoded characters, UTF-8 result = urllib.parse.unquote("\u6f22%C3%BC") expect = '\u6f22\u00fc' self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) # A mix of non-ASCII and percent-encoded characters, Latin-1 # (Note, the string contains non-Latin-1-representable characters) result = urllib.parse.unquote("\u6f22%FC", encoding="latin-1") expect = '\u6f22\u00fc' self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) @unittest.skip("TODO: RUSTPYTHON (TypeError: Expected str, got bytes)") def test_unquoting_with_bytes_input(self): # ASCII characters decoded to a string given = b'blueberryjam' expect = 'blueberryjam' result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) # A mix of non-ASCII hex-encoded characters and ASCII characters given = b'bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y' expect = 'bl\u00e5b\u00e6rsyltet\u00f8y' result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) # A mix of non-ASCII percent-encoded characters and ASCII characters given = b'bl%c3%a5b%c3%a6rsyltet%c3%b8j' expect = 'bl\u00e5b\u00e6rsyltet\u00f8j' result = urllib.parse.unquote(given) self.assertEqual(expect, result, "using unquote(): %r != %r" % (expect, result)) class urlencode_Tests(unittest.TestCase): """Tests for urlencode()""" def help_inputtype(self, given, test_type): """Helper method for testing different input types. 'given' must lead to only the pairs: * 1st, 1 * 2nd, 2 * 3rd, 3 Test cannot assume anything about order. Docs make no guarantee and have possible dictionary input. """ expect_somewhere = ["1st=1", "2nd=2", "3rd=3"] result = urllib.parse.urlencode(given) for expected in expect_somewhere: self.assertIn(expected, result, "testing %s: %s not found in %s" % (test_type, expected, result)) self.assertEqual(result.count('&'), 2, "testing %s: expected 2 '&'s; got %s" % (test_type, result.count('&'))) amp_location = result.index('&') on_amp_left = result[amp_location - 1] on_amp_right = result[amp_location + 1] self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(), "testing %s: '&' not located in proper place in %s" % (test_type, result)) self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps "testing %s: " "unexpected number of characters: %s != %s" % (test_type, len(result), (5 * 3) + 2)) def test_using_mapping(self): # Test passing in a mapping object as an argument. self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'}, "using dict as input type") def test_using_sequence(self): # Test passing in a sequence of two-item sequences as an argument. self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')], "using sequence of two-item tuples as input") def test_quoting(self): # Make sure keys and values are quoted using quote_plus() given = {"&":"="} expect = "%s=%s" % (hexescape('&'), hexescape('=')) result = urllib.parse.urlencode(given) self.assertEqual(expect, result) given = {"key name":"A bunch of pluses"} expect = "key+name=A+bunch+of+pluses" result = urllib.parse.urlencode(given) self.assertEqual(expect, result) def test_doseq(self): # Test that passing True for 'doseq' parameter works correctly given = {'sequence':['1', '2', '3']} expect = "sequence=%s" % urllib.parse.quote_plus(str(['1', '2', '3'])) result = urllib.parse.urlencode(given) self.assertEqual(expect, result) result = urllib.parse.urlencode(given, True) for value in given["sequence"]: expect = "sequence=%s" % value self.assertIn(expect, result) self.assertEqual(result.count('&'), 2, "Expected 2 '&'s, got %s" % result.count('&')) def test_empty_sequence(self): self.assertEqual("", urllib.parse.urlencode({})) self.assertEqual("", urllib.parse.urlencode([])) def test_nonstring_values(self): self.assertEqual("a=1", urllib.parse.urlencode({"a": 1})) self.assertEqual("a=None", urllib.parse.urlencode({"a": None})) def test_nonstring_seq_values(self): self.assertEqual("a=1&a=2", urllib.parse.urlencode({"a": [1, 2]}, True)) self.assertEqual("a=None&a=a", urllib.parse.urlencode({"a": [None, "a"]}, True)) data = collections.OrderedDict([("a", 1), ("b", 1)]) self.assertEqual("a=a&a=b", urllib.parse.urlencode({"a": data}, True)) def test_urlencode_encoding(self): # ASCII encoding. Expect %3F with errors="replace' given = (('\u00a0', '\u00c1'),) expect = '%3F=%3F' result = urllib.parse.urlencode(given, encoding="ASCII", errors="replace") self.assertEqual(expect, result) # Default is UTF-8 encoding. given = (('\u00a0', '\u00c1'),) expect = '%C2%A0=%C3%81' result = urllib.parse.urlencode(given) self.assertEqual(expect, result) # Latin-1 encoding. given = (('\u00a0', '\u00c1'),) expect = '%A0=%C1' result = urllib.parse.urlencode(given, encoding="latin-1") self.assertEqual(expect, result) def test_urlencode_encoding_doseq(self): # ASCII Encoding. Expect %3F with errors="replace' given = (('\u00a0', '\u00c1'),) expect = '%3F=%3F' result = urllib.parse.urlencode(given, doseq=True, encoding="ASCII", errors="replace") self.assertEqual(expect, result) # ASCII Encoding. On a sequence of values. given = (("\u00a0", (1, "\u00c1")),) expect = '%3F=1&%3F=%3F' result = urllib.parse.urlencode(given, True, encoding="ASCII", errors="replace") self.assertEqual(expect, result) # Utf-8 given = (("\u00a0", "\u00c1"),) expect = '%C2%A0=%C3%81' result = urllib.parse.urlencode(given, True) self.assertEqual(expect, result) given = (("\u00a0", (42, "\u00c1")),) expect = '%C2%A0=42&%C2%A0=%C3%81' result = urllib.parse.urlencode(given, True) self.assertEqual(expect, result) # latin-1 given = (("\u00a0", "\u00c1"),) expect = '%A0=%C1' result = urllib.parse.urlencode(given, True, encoding="latin-1") self.assertEqual(expect, result) given = (("\u00a0", (42, "\u00c1")),) expect = '%A0=42&%A0=%C1' result = urllib.parse.urlencode(given, True, encoding="latin-1") self.assertEqual(expect, result) def test_urlencode_bytes(self): given = ((b'\xa0\x24', b'\xc1\x24'),) expect = '%A0%24=%C1%24' result = urllib.parse.urlencode(given) self.assertEqual(expect, result) result = urllib.parse.urlencode(given, True) self.assertEqual(expect, result) # Sequence of values given = ((b'\xa0\x24', (42, b'\xc1\x24')),) expect = '%A0%24=42&%A0%24=%C1%24' result = urllib.parse.urlencode(given, True) self.assertEqual(expect, result) def test_urlencode_encoding_safe_parameter(self): # Send '$' (\x24) as safe character # Default utf-8 encoding given = ((b'\xa0\x24', b'\xc1\x24'),) result = urllib.parse.urlencode(given, safe=":$") expect = '%A0$=%C1$' self.assertEqual(expect, result) given = ((b'\xa0\x24', b'\xc1\x24'),) result = urllib.parse.urlencode(given, doseq=True, safe=":$") expect = '%A0$=%C1$' self.assertEqual(expect, result) # Safe parameter in sequence given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),) expect = '%A0$=%C1$&%A0$=13&%A0$=42' result = urllib.parse.urlencode(given, True, safe=":$") self.assertEqual(expect, result) # Test all above in latin-1 encoding given = ((b'\xa0\x24', b'\xc1\x24'),) result = urllib.parse.urlencode(given, safe=":$", encoding="latin-1") expect = '%A0$=%C1$' self.assertEqual(expect, result) given = ((b'\xa0\x24', b'\xc1\x24'),) expect = '%A0$=%C1$' result = urllib.parse.urlencode(given, doseq=True, safe=":$", encoding="latin-1") given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),) expect = '%A0$=%C1$&%A0$=13&%A0$=42' result = urllib.parse.urlencode(given, True, safe=":$", encoding="latin-1") self.assertEqual(expect, result) class Pathname_Tests(unittest.TestCase): """Test pathname2url() and url2pathname()""" def test_basic(self): # Make sure simple tests pass expected_path = os.path.join("parts", "of", "a", "path") expected_url = "parts/of/a/path" result = urllib.request.pathname2url(expected_path) self.assertEqual(expected_url, result, "pathname2url() failed; %s != %s" % (result, expected_url)) result = urllib.request.url2pathname(expected_url) self.assertEqual(expected_path, result, "url2pathame() failed; %s != %s" % (result, expected_path)) def test_quoting(self): # Test automatic quoting and unquoting works for pathnam2url() and # url2pathname() respectively given = os.path.join("needs", "quot=ing", "here") expect = "needs/%s/here" % urllib.parse.quote("quot=ing") result = urllib.request.pathname2url(given) self.assertEqual(expect, result, "pathname2url() failed; %s != %s" % (expect, result)) expect = given result = urllib.request.url2pathname(result) self.assertEqual(expect, result, "url2pathname() failed; %s != %s" % (expect, result)) given = os.path.join("make sure", "using_quote") expect = "%s/using_quote" % urllib.parse.quote("make sure") result = urllib.request.pathname2url(given) self.assertEqual(expect, result, "pathname2url() failed; %s != %s" % (expect, result)) given = "make+sure/using_unquote" expect = os.path.join("make+sure", "using_unquote") result = urllib.request.url2pathname(given) self.assertEqual(expect, result, "url2pathname() failed; %s != %s" % (expect, result)) @unittest.skipUnless(sys.platform == 'win32', 'test specific to the nturl2path functions.') @unittest.expectedFailure def test_prefixes(self): # Test special prefixes are correctly handled in pathname2url() given = '\\\\?\\C:\\dir' expect = '///C:/dir' result = urllib.request.pathname2url(given) self.assertEqual(expect, result, "pathname2url() failed; %s != %s" % (expect, result)) given = '\\\\?\\unc\\server\\share\\dir' expect = '/server/share/dir' result = urllib.request.pathname2url(given) self.assertEqual(expect, result, "pathname2url() failed; %s != %s" % (expect, result)) @unittest.skipUnless(sys.platform == 'win32', 'test specific to the urllib.url2path function.') def test_ntpath(self): given = ('/C:/', '///C:/', '/C|//') expect = 'C:\\' for url in given: result = urllib.request.url2pathname(url) self.assertEqual(expect, result, 'urllib.request..url2pathname() failed; %s != %s' % (expect, result)) given = '///C|/path' expect = 'C:\\path' result = urllib.request.url2pathname(given) self.assertEqual(expect, result, 'urllib.request.url2pathname() failed; %s != %s' % (expect, result)) class Utility_Tests(unittest.TestCase): """Testcase to test the various utility functions in the urllib.""" def test_thishost(self): """Test the urllib.request.thishost utility function returns a tuple""" self.assertIsInstance(urllib.request.thishost(), tuple) class URLopener_Tests(FakeHTTPMixin, unittest.TestCase): """Testcase to test the open method of URLopener class.""" def test_quoted_open(self): class DummyURLopener(urllib.request.URLopener): def open_spam(self, url): return url with warnings_helper.check_warnings( ('DummyURLopener style of invoking requests is deprecated.', DeprecationWarning)): self.assertEqual(DummyURLopener().open( 'spam://example/ /'),'//example/%20/') # test the safe characters are not quoted by urlopen self.assertEqual(DummyURLopener().open( "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"), "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/") @warnings_helper.ignore_warnings(category=DeprecationWarning) def test_urlopener_retrieve_file(self): with os_helper.temp_dir() as tmpdir: fd, tmpfile = tempfile.mkstemp(dir=tmpdir) os.close(fd) fileurl = "file:" + urllib.request.pathname2url(tmpfile) filename, _ = urllib.request.URLopener().retrieve(fileurl) # Some buildbots have TEMP folder that uses a lowercase drive letter. self.assertEqual(os.path.normcase(filename), os.path.normcase(tmpfile)) @warnings_helper.ignore_warnings(category=DeprecationWarning) def test_urlopener_retrieve_remote(self): url = "http://www.python.org/file.txt" self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!") self.addCleanup(self.unfakehttp) filename, _ = urllib.request.URLopener().retrieve(url) self.assertEqual(os.path.splitext(filename)[1], ".txt") @warnings_helper.ignore_warnings(category=DeprecationWarning) def test_local_file_open(self): # bpo-35907, CVE-2019-9948: urllib must reject local_file:// scheme class DummyURLopener(urllib.request.URLopener): def open_local_file(self, url): return url for url in ('local_file://example', 'local-file://example'): self.assertRaises(OSError, urllib.request.urlopen, url) self.assertRaises(OSError, urllib.request.URLopener().open, url) self.assertRaises(OSError, urllib.request.URLopener().retrieve, url) self.assertRaises(OSError, DummyURLopener().open, url) self.assertRaises(OSError, DummyURLopener().retrieve, url) class RequestTests(unittest.TestCase): """Unit tests for urllib.request.Request.""" def test_default_values(self): Request = urllib.request.Request request = Request("http://www.python.org") self.assertEqual(request.get_method(), 'GET') request = Request("http://www.python.org", {}) self.assertEqual(request.get_method(), 'POST') def test_with_method_arg(self): Request = urllib.request.Request request = Request("http://www.python.org", method='HEAD') self.assertEqual(request.method, 'HEAD') self.assertEqual(request.get_method(), 'HEAD') request = Request("http://www.python.org", {}, method='HEAD') self.assertEqual(request.method, 'HEAD') self.assertEqual(request.get_method(), 'HEAD') request = Request("http://www.python.org", method='GET') self.assertEqual(request.get_method(), 'GET') request.method = 'HEAD' self.assertEqual(request.get_method(), 'HEAD') class URL2PathNameTests(unittest.TestCase): def test_converting_drive_letter(self): self.assertEqual(url2pathname("///C|"), 'C:') self.assertEqual(url2pathname("///C:"), 'C:') self.assertEqual(url2pathname("///C|/"), 'C:\\') def test_converting_when_no_drive_letter(self): # cannot end a raw string in \ self.assertEqual(url2pathname("///C/test/"), r'\\\C\test' '\\') self.assertEqual(url2pathname("////C/test/"), r'\\C\test' '\\') def test_simple_compare(self): self.assertEqual(url2pathname("///C|/foo/bar/spam.foo"), r'C:\foo\bar\spam.foo') def test_non_ascii_drive_letter(self): self.assertRaises(IOError, url2pathname, "///\u00e8|/") def test_roundtrip_url2pathname(self): list_of_paths = ['C:', r'\\\C\test\\', r'C:\foo\bar\spam.foo' ] for path in list_of_paths: self.assertEqual(url2pathname(pathname2url(path)), path) class PathName2URLTests(unittest.TestCase): def test_converting_drive_letter(self): self.assertEqual(pathname2url("C:"), '///C:') self.assertEqual(pathname2url("C:\\"), '///C:') def test_converting_when_no_drive_letter(self): self.assertEqual(pathname2url(r"\\\folder\test" "\\"), '/////folder/test/') self.assertEqual(pathname2url(r"\\folder\test" "\\"), '////folder/test/') self.assertEqual(pathname2url(r"\folder\test" "\\"), '/folder/test/') def test_simple_compare(self): self.assertEqual(pathname2url(r'C:\foo\bar\spam.foo'), "///C:/foo/bar/spam.foo" ) def test_long_drive_letter(self): self.assertRaises(IOError, pathname2url, "XX:\\") def test_roundtrip_pathname2url(self): list_of_paths = ['///C:', '/////folder/test/', '///C:/foo/bar/spam.foo'] for path in list_of_paths: self.assertEqual(pathname2url(url2pathname(path)), path) if __name__ == '__main__': unittest.main()
[]
[]
[ "No_Proxy", "Http_Proxy", "HTTP_PROXY", "http_proxy", "no_proxy" ]
[]
["No_Proxy", "Http_Proxy", "HTTP_PROXY", "http_proxy", "no_proxy"]
python
5
0
main_test.go
package main import ( "os" "testing" "github.com/jetstack/cert-manager/test/acme/dns" ) var zone = os.Getenv("TEST_ZONE_NAME") func TestRunsSuite(t *testing.T) { // The manifest path should contain a file named config.json that is a // snippet of valid configuration that should be included on the // ChallengeRequest passed as part of the test cases. fixture := dns.NewFixture(&selectelDNSProviderSolver{}, dns.SetResolvedZone(zone), dns.SetAllowAmbientCredentials(false), dns.SetManifestPath("testdata/selectel"), dns.SetStrict(true), ) fixture.RunConformance(t) }
[ "\"TEST_ZONE_NAME\"" ]
[]
[ "TEST_ZONE_NAME" ]
[]
["TEST_ZONE_NAME"]
go
1
0
src/pip/_internal/wheel.py
""" Support for installing and building the "wheel" binary package format. """ from __future__ import absolute_import import collections import compileall import csv import hashlib import logging import os.path import re import shutil import stat import sys import warnings from base64 import urlsafe_b64encode from email.parser import Parser from pip._vendor import pkg_resources from pip._vendor.distlib.scripts import ScriptMaker from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.six import StringIO from pip._internal import pep425tags from pip._internal.download import path_to_url, unpack_url from pip._internal.exceptions import ( InstallationError, InvalidWheelFilename, UnsupportedWheel, ) from pip._internal.locations import ( PIP_DELETE_MARKER_FILENAME, distutils_scheme, ) from pip._internal.models.link import Link from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( call_subprocess, captured_stdout, ensure_dir, read_chunks, ) from pip._internal.utils.setuptools_build import SETUPTOOLS_SHIM from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING from pip._internal.utils.ui import open_spinner if MYPY_CHECK_RUNNING: from typing import ( # noqa: F401 Dict, List, Optional, Sequence, Mapping, Tuple, IO, Text, Any, Union, Iterable ) from pip._vendor.packaging.requirements import Requirement # noqa: F401 from pip._internal.req.req_install import InstallRequirement # noqa: F401 from pip._internal.download import PipSession # noqa: F401 from pip._internal.index import PackageFinder # noqa: F401 from pip._internal.operations.prepare import ( # noqa: F401 RequirementPreparer ) from pip._internal.cache import WheelCache # noqa: F401 from pip._internal.pep425tags import Pep425Tag # noqa: F401 InstalledCSVRow = Tuple[str, ...] VERSION_COMPATIBLE = (1, 0) logger = logging.getLogger(__name__) def normpath(src, p): return os.path.relpath(src, p).replace(os.path.sep, '/') def rehash(path, blocksize=1 << 20): # type: (str, int) -> Tuple[str, str] """Return (hash, length) for path using hashlib.sha256()""" h = hashlib.sha256() length = 0 with open(path, 'rb') as f: for block in read_chunks(f, size=blocksize): length += len(block) h.update(block) digest = 'sha256=' + urlsafe_b64encode( h.digest() ).decode('latin1').rstrip('=') # unicode/str python2 issues return (digest, str(length)) # type: ignore def open_for_csv(name, mode): # type: (str, Text) -> IO if sys.version_info[0] < 3: nl = {} # type: Dict[str, Any] bin = 'b' else: nl = {'newline': ''} # type: Dict[str, Any] bin = '' return open(name, mode + bin, **nl) def replace_python_tag(wheelname, new_tag): # type: (str, str) -> str """Replace the Python tag in a wheel file name with a new value. """ parts = wheelname.split('-') parts[-3] = new_tag return '-'.join(parts) def fix_script(path): # type: (str) -> Optional[bool] """Replace #!python with #!/path/to/python Return True if file was changed.""" # XXX RECORD hashes will need to be updated if os.path.isfile(path): with open(path, 'rb') as script: firstline = script.readline() if not firstline.startswith(b'#!python'): return False exename = sys.executable.encode(sys.getfilesystemencoding()) firstline = b'#!' + exename + os.linesep.encode("ascii") rest = script.read() with open(path, 'wb') as script: script.write(firstline) script.write(rest) return True return None dist_info_re = re.compile(r"""^(?P<namever>(?P<name>.+?)(-(?P<ver>.+?))?) \.dist-info$""", re.VERBOSE) def root_is_purelib(name, wheeldir): # type: (str, str) -> bool """ Return True if the extracted wheel in wheeldir should go into purelib. """ name_folded = name.replace("-", "_") for item in os.listdir(wheeldir): match = dist_info_re.match(item) if match and match.group('name') == name_folded: with open(os.path.join(wheeldir, item, 'WHEEL')) as wheel: for line in wheel: line = line.lower().rstrip() if line == "root-is-purelib: true": return True return False def get_entrypoints(filename): # type: (str) -> Tuple[Dict[str, str], Dict[str, str]] if not os.path.exists(filename): return {}, {} # This is done because you can pass a string to entry_points wrappers which # means that they may or may not be valid INI files. The attempt here is to # strip leading and trailing whitespace in order to make them valid INI # files. with open(filename) as fp: data = StringIO() for line in fp: data.write(line.strip()) data.write("\n") data.seek(0) # get the entry points and then the script names entry_points = pkg_resources.EntryPoint.parse_map(data) console = entry_points.get('console_scripts', {}) gui = entry_points.get('gui_scripts', {}) def _split_ep(s): """get the string representation of EntryPoint, remove space and split on '='""" return str(s).replace(" ", "").split("=") # convert the EntryPoint objects into strings with module:function console = dict(_split_ep(v) for v in console.values()) gui = dict(_split_ep(v) for v in gui.values()) return console, gui def message_about_scripts_not_on_PATH(scripts): # type: (Sequence[str]) -> Optional[str] """Determine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None. """ if not scripts: return None # Group scripts by the path they were installed in grouped_by_dir = collections.defaultdict(set) # type: Dict[str, set] for destfile in scripts: parent_dir = os.path.dirname(destfile) script_name = os.path.basename(destfile) grouped_by_dir[parent_dir].add(script_name) # We don't want to warn for directories that are on PATH. not_warn_dirs = [ os.path.normcase(i).rstrip(os.sep) for i in os.environ.get("PATH", "").split(os.pathsep) ] # If an executable sits with sys.executable, we don't warn for it. # This covers the case of venv invocations without activating the venv. not_warn_dirs.append(os.path.normcase(os.path.dirname(sys.executable))) warn_for = { parent_dir: scripts for parent_dir, scripts in grouped_by_dir.items() if os.path.normcase(parent_dir) not in not_warn_dirs } if not warn_for: return None # Format a message msg_lines = [] for parent_dir, scripts in warn_for.items(): scripts = sorted(scripts) if len(scripts) == 1: start_text = "script {} is".format(scripts[0]) else: start_text = "scripts {} are".format( ", ".join(scripts[:-1]) + " and " + scripts[-1] ) msg_lines.append( "The {} installed in '{}' which is not on PATH." .format(start_text, parent_dir) ) last_line_fmt = ( "Consider adding {} to PATH or, if you prefer " "to suppress this warning, use --no-warn-script-location." ) if len(msg_lines) == 1: msg_lines.append(last_line_fmt.format("this directory")) else: msg_lines.append(last_line_fmt.format("these directories")) # Returns the formatted multiline message return "\n".join(msg_lines) def sorted_outrows(outrows): # type: (Iterable[InstalledCSVRow]) -> List[InstalledCSVRow] """ Return the given rows of a RECORD file in sorted order. Each row is a 3-tuple (path, hash, size) and corresponds to a record of a RECORD file (see PEP 376 and PEP 427 for details). For the rows passed to this function, the size can be an integer as an int or string, or the empty string. """ # Normally, there should only be one row per path, in which case the # second and third elements don't come into play when sorting. # However, in cases in the wild where a path might happen to occur twice, # we don't want the sort operation to trigger an error (but still want # determinism). Since the third element can be an int or string, we # coerce each element to a string to avoid a TypeError in this case. # For additional background, see-- # https://github.com/pypa/pip/issues/5868 return sorted(outrows, key=lambda row: tuple(str(x) for x in row)) def get_csv_rows_for_installed( old_csv_rows, # type: Iterable[List[str]] installed, # type: Dict[str, str] changed, # type: set generated, # type: List[str] lib_dir, # type: str ): # type: (...) -> List[InstalledCSVRow] installed_rows = [] # type: List[InstalledCSVRow] for row in old_csv_rows: if len(row) > 3: logger.warning( 'RECORD line has more than three elements: {}'.format(row) ) fpath = row[0] fpath = installed.pop(fpath, fpath) if fpath in changed: digest, length = rehash(fpath) row[1] = digest row[2] = length installed_rows.append(tuple(row)) for f in generated: digest, length = rehash(f) installed_rows.append((normpath(f, lib_dir), digest, str(length))) for f in installed: installed_rows.append((installed[f], '', '')) return installed_rows def move_wheel_files( name, # type: str req, # type: Requirement wheeldir, # type: str user=False, # type: bool home=None, # type: Optional[str] root=None, # type: Optional[str] pycompile=True, # type: bool scheme=None, # type: Optional[Mapping[str, str]] isolated=False, # type: bool prefix=None, # type: Optional[str] warn_script_location=True # type: bool ): # type: (...) -> None """Install a wheel""" # TODO: Investigate and break this up. # TODO: Look into moving this into a dedicated class for representing an # installation. if not scheme: scheme = distutils_scheme( name, user=user, home=home, root=root, isolated=isolated, prefix=prefix, ) if root_is_purelib(name, wheeldir): lib_dir = scheme['purelib'] else: lib_dir = scheme['platlib'] info_dir = [] # type: List[str] data_dirs = [] source = wheeldir.rstrip(os.path.sep) + os.path.sep # Record details of the files moved # installed = files copied from the wheel to the destination # changed = files changed while installing (scripts #! line typically) # generated = files newly generated during the install (script wrappers) installed = {} # type: Dict[str, str] changed = set() generated = [] # type: List[str] # Compile all of the pyc files that we're going to be installing if pycompile: with captured_stdout() as stdout: with warnings.catch_warnings(): warnings.filterwarnings('ignore') compileall.compile_dir(source, force=True, quiet=True) logger.debug(stdout.getvalue()) def record_installed(srcfile, destfile, modified=False): """Map archive RECORD paths to installation RECORD paths.""" oldpath = normpath(srcfile, wheeldir) newpath = normpath(destfile, lib_dir) installed[oldpath] = newpath if modified: changed.add(destfile) def clobber(source, dest, is_base, fixer=None, filter=None): ensure_dir(dest) # common for the 'include' path for dir, subdirs, files in os.walk(source): basedir = dir[len(source):].lstrip(os.path.sep) destdir = os.path.join(dest, basedir) if is_base and basedir.split(os.path.sep, 1)[0].endswith('.data'): continue for s in subdirs: destsubdir = os.path.join(dest, basedir, s) if is_base and basedir == '' and destsubdir.endswith('.data'): data_dirs.append(s) continue elif (is_base and s.endswith('.dist-info') and canonicalize_name(s).startswith( canonicalize_name(req.name))): assert not info_dir, ('Multiple .dist-info directories: ' + destsubdir + ', ' + ', '.join(info_dir)) info_dir.append(destsubdir) for f in files: # Skip unwanted files if filter and filter(f): continue srcfile = os.path.join(dir, f) destfile = os.path.join(dest, basedir, f) # directory creation is lazy and after the file filtering above # to ensure we don't install empty dirs; empty dirs can't be # uninstalled. ensure_dir(destdir) # copyfile (called below) truncates the destination if it # exists and then writes the new contents. This is fine in most # cases, but can cause a segfault if pip has loaded a shared # object (e.g. from pyopenssl through its vendored urllib3) # Since the shared object is mmap'd an attempt to call a # symbol in it will then cause a segfault. Unlinking the file # allows writing of new contents while allowing the process to # continue to use the old copy. if os.path.exists(destfile): os.unlink(destfile) # We use copyfile (not move, copy, or copy2) to be extra sure # that we are not moving directories over (copyfile fails for # directories) as well as to ensure that we are not copying # over any metadata because we want more control over what # metadata we actually copy over. shutil.copyfile(srcfile, destfile) # Copy over the metadata for the file, currently this only # includes the atime and mtime. st = os.stat(srcfile) if hasattr(os, "utime"): os.utime(destfile, (st.st_atime, st.st_mtime)) # If our file is executable, then make our destination file # executable. if os.access(srcfile, os.X_OK): st = os.stat(srcfile) permissions = ( st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH ) os.chmod(destfile, permissions) changed = False if fixer: changed = fixer(destfile) record_installed(srcfile, destfile, changed) clobber(source, lib_dir, True) assert info_dir, "%s .dist-info directory not found" % req # Get the defined entry points ep_file = os.path.join(info_dir[0], 'entry_points.txt') console, gui = get_entrypoints(ep_file) def is_entrypoint_wrapper(name): # EP, EP.exe and EP-script.py are scripts generated for # entry point EP by setuptools if name.lower().endswith('.exe'): matchname = name[:-4] elif name.lower().endswith('-script.py'): matchname = name[:-10] elif name.lower().endswith(".pya"): matchname = name[:-4] else: matchname = name # Ignore setuptools-generated scripts return (matchname in console or matchname in gui) for datadir in data_dirs: fixer = None filter = None for subdir in os.listdir(os.path.join(wheeldir, datadir)): fixer = None if subdir == 'scripts': fixer = fix_script filter = is_entrypoint_wrapper source = os.path.join(wheeldir, datadir, subdir) dest = scheme[subdir] clobber(source, dest, False, fixer=fixer, filter=filter) maker = ScriptMaker(None, scheme['scripts']) # Ensure old scripts are overwritten. # See https://github.com/pypa/pip/issues/1800 maker.clobber = True # Ensure we don't generate any variants for scripts because this is almost # never what somebody wants. # See https://bitbucket.org/pypa/distlib/issue/35/ maker.variants = {''} # This is required because otherwise distlib creates scripts that are not # executable. # See https://bitbucket.org/pypa/distlib/issue/32/ maker.set_mode = True # Simplify the script and fix the fact that the default script swallows # every single stack trace. # See https://bitbucket.org/pypa/distlib/issue/34/ # See https://bitbucket.org/pypa/distlib/issue/33/ def _get_script_text(entry): if entry.suffix is None: raise InstallationError( "Invalid script entry point: %s for req: %s - A callable " "suffix is required. Cf https://packaging.python.org/en/" "latest/distributing.html#console-scripts for more " "information." % (entry, req) ) return maker.script_template % { "module": entry.prefix, "import_name": entry.suffix.split(".")[0], "func": entry.suffix, } # ignore type, because mypy disallows assigning to a method, # see https://github.com/python/mypy/issues/2427 maker._get_script_text = _get_script_text # type: ignore maker.script_template = r"""# -*- coding: utf-8 -*- import re import sys from %(module)s import %(import_name)s if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(%(func)s()) """ # Special case pip and setuptools to generate versioned wrappers # # The issue is that some projects (specifically, pip and setuptools) use # code in setup.py to create "versioned" entry points - pip2.7 on Python # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into # the wheel metadata at build time, and so if the wheel is installed with # a *different* version of Python the entry points will be wrong. The # correct fix for this is to enhance the metadata to be able to describe # such versioned entry points, but that won't happen till Metadata 2.0 is # available. # In the meantime, projects using versioned entry points will either have # incorrect versioned entry points, or they will not be able to distribute # "universal" wheels (i.e., they will need a wheel per Python version). # # Because setuptools and pip are bundled with _ensurepip and virtualenv, # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we # override the versioned entry points in the wheel and generate the # correct ones. This code is purely a short-term measure until Metadata 2.0 # is available. # # To add the level of hack in this section of code, in order to support # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment # variable which will control which version scripts get installed. # # ENSUREPIP_OPTIONS=altinstall # - Only pipX.Y and easy_install-X.Y will be generated and installed # ENSUREPIP_OPTIONS=install # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note # that this option is technically if ENSUREPIP_OPTIONS is set and is # not altinstall # DEFAULT # - The default behavior is to install pip, pipX, pipX.Y, easy_install # and easy_install-X.Y. pip_script = console.pop('pip', None) if pip_script: if "ENSUREPIP_OPTIONS" not in os.environ: spec = 'pip = ' + pip_script generated.extend(maker.make(spec)) if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall": spec = 'pip%s = %s' % (sys.version[:1], pip_script) generated.extend(maker.make(spec)) spec = 'pip%s = %s' % (sys.version[:3], pip_script) generated.extend(maker.make(spec)) # Delete any other versioned pip entry points pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)] for k in pip_ep: del console[k] easy_install_script = console.pop('easy_install', None) if easy_install_script: if "ENSUREPIP_OPTIONS" not in os.environ: spec = 'easy_install = ' + easy_install_script generated.extend(maker.make(spec)) spec = 'easy_install-%s = %s' % (sys.version[:3], easy_install_script) generated.extend(maker.make(spec)) # Delete any other versioned easy_install entry points easy_install_ep = [ k for k in console if re.match(r'easy_install(-\d\.\d)?$', k) ] for k in easy_install_ep: del console[k] # Generate the console and GUI entry points specified in the wheel if len(console) > 0: generated_console_scripts = maker.make_multiple( ['%s = %s' % kv for kv in console.items()] ) generated.extend(generated_console_scripts) if warn_script_location: msg = message_about_scripts_not_on_PATH(generated_console_scripts) if msg is not None: logger.warning(msg) if len(gui) > 0: generated.extend( maker.make_multiple( ['%s = %s' % kv for kv in gui.items()], {'gui': True} ) ) # Record pip as the installer installer = os.path.join(info_dir[0], 'INSTALLER') temp_installer = os.path.join(info_dir[0], 'INSTALLER.pip') with open(temp_installer, 'wb') as installer_file: installer_file.write(b'pip\n') shutil.move(temp_installer, installer) generated.append(installer) # Record details of all files installed record = os.path.join(info_dir[0], 'RECORD') temp_record = os.path.join(info_dir[0], 'RECORD.pip') with open_for_csv(record, 'r') as record_in: with open_for_csv(temp_record, 'w+') as record_out: reader = csv.reader(record_in) outrows = get_csv_rows_for_installed( reader, installed=installed, changed=changed, generated=generated, lib_dir=lib_dir, ) writer = csv.writer(record_out) # Sort to simplify testing. for row in sorted_outrows(outrows): writer.writerow(row) shutil.move(temp_record, record) def wheel_version(source_dir): # type: (Optional[str]) -> Optional[Tuple[int, ...]] """ Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return None if we couldn't parse / extract it. """ try: dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0] wheel_data = dist.get_metadata('WHEEL') wheel_data = Parser().parsestr(wheel_data) version = wheel_data['Wheel-Version'].strip() version = tuple(map(int, version.split('.'))) return version except Exception: return None def check_compatibility(version, name): # type: (Optional[Tuple[int, ...]], str) -> None """ Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given """ if not version: raise UnsupportedWheel( "%s is in an unsupported or invalid wheel" % name ) if version[0] > VERSION_COMPATIBLE[0]: raise UnsupportedWheel( "%s's Wheel-Version (%s) is not compatible with this version " "of pip" % (name, '.'.join(map(str, version))) ) elif version > VERSION_COMPATIBLE: logger.warning( 'Installing from a newer Wheel-Version (%s)', '.'.join(map(str, version)), ) class Wheel(object): """A wheel file""" # TODO: Maybe move the class into the models sub-package # TODO: Maybe move the install code into this class wheel_file_re = re.compile( r"""^(?P<namever>(?P<name>.+?)-(?P<ver>.*?)) ((-(?P<build>\d[^-]*?))?-(?P<pyver>.+?)-(?P<abi>.+?)-(?P<plat>.+?) \.whl|\.dist-info)$""", re.VERBOSE ) def __init__(self, filename): # type: (str) -> None """ :raises InvalidWheelFilename: when the filename is invalid for a wheel """ wheel_info = self.wheel_file_re.match(filename) if not wheel_info: raise InvalidWheelFilename( "%s is not a valid wheel filename." % filename ) self.filename = filename self.name = wheel_info.group('name').replace('_', '-') # we'll assume "_" means "-" due to wheel naming scheme # (https://github.com/pypa/pip/issues/1150) self.version = wheel_info.group('ver').replace('_', '-') self.build_tag = wheel_info.group('build') self.pyversions = wheel_info.group('pyver').split('.') self.abis = wheel_info.group('abi').split('.') self.plats = wheel_info.group('plat').split('.') # All the tag combinations from this file self.file_tags = { (x, y, z) for x in self.pyversions for y in self.abis for z in self.plats } def support_index_min(self, tags=None): # type: (Optional[List[Pep425Tag]]) -> Optional[int] """ Return the lowest index that one of the wheel's file_tag combinations achieves in the supported_tags list e.g. if there are 8 supported tags, and one of the file tags is first in the list, then return 0. Returns None is the wheel is not supported. """ if tags is None: # for mock tags = pep425tags.get_supported() indexes = [tags.index(c) for c in self.file_tags if c in tags] return min(indexes) if indexes else None def supported(self, tags=None): # type: (Optional[List[Pep425Tag]]) -> bool """Is this wheel supported on this system?""" if tags is None: # for mock tags = pep425tags.get_supported() return bool(set(tags).intersection(self.file_tags)) def _contains_egg_info( s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s)) class WheelBuilder(object): """Build wheels from a RequirementSet.""" def __init__( self, finder, # type: PackageFinder preparer, # type: RequirementPreparer wheel_cache, # type: WheelCache build_options=None, # type: Optional[List[str]] global_options=None, # type: Optional[List[str]] no_clean=False # type: bool ): # type: (...) -> None self.finder = finder self.preparer = preparer self.wheel_cache = wheel_cache self._wheel_dir = preparer.wheel_download_dir self.build_options = build_options or [] self.global_options = global_options or [] self.no_clean = no_clean def _build_one(self, req, output_dir, python_tag=None): """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ # Install build deps into temporary directory (PEP 518) with req.build_env: return self._build_one_inside_env(req, output_dir, python_tag=python_tag) def _build_one_inside_env(self, req, output_dir, python_tag=None): with TempDirectory(kind="wheel") as temp_dir: if req.use_pep517: builder = self._build_one_pep517 else: builder = self._build_one_legacy if builder(req, temp_dir.path, python_tag=python_tag): try: wheel_name = os.listdir(temp_dir.path)[0] wheel_path = os.path.join(output_dir, wheel_name) shutil.move( os.path.join(temp_dir.path, wheel_name), wheel_path ) logger.info('Stored in directory: %s', output_dir) return wheel_path except Exception: pass # Ignore return, we can't do anything else useful. self._clean_one(req) return None def _base_setup_args(self, req): # NOTE: Eventually, we'd want to also -S to the flags here, when we're # isolating. Currently, it breaks Python in virtualenvs, because it # relies on site.py to find parts of the standard library outside the # virtualenv. return [ sys.executable, '-u', '-c', SETUPTOOLS_SHIM % req.setup_py ] + list(self.global_options) def _build_one_pep517(self, req, tempd, python_tag=None): assert req.metadata_directory is not None try: req.spin_message = 'Building wheel for %s (PEP 517)' % (req.name,) logger.debug('Destination directory: %s', tempd) wheelname = req.pep517_backend.build_wheel( tempd, metadata_directory=req.metadata_directory ) if python_tag: # General PEP 517 backends don't necessarily support # a "--python-tag" option, so we rename the wheel # file directly. newname = replace_python_tag(wheelname, python_tag) os.rename( os.path.join(tempd, wheelname), os.path.join(tempd, newname) ) return True except Exception: logger.error('Failed building wheel for %s', req.name) return False def _build_one_legacy(self, req, tempd, python_tag=None): base_args = self._base_setup_args(req) spin_message = 'Building wheel for %s (setup.py)' % (req.name,) with open_spinner(spin_message) as spinner: logger.debug('Destination directory: %s', tempd) wheel_args = base_args + ['bdist_wheel', '-d', tempd] \ + self.build_options if python_tag is not None: wheel_args += ["--python-tag", python_tag] try: call_subprocess(wheel_args, cwd=req.setup_py_dir, show_stdout=False, spinner=spinner) return True except Exception: spinner.finish("error") logger.error('Failed building wheel for %s', req.name) return False def _clean_one(self, req): base_args = self._base_setup_args(req) logger.info('Running setup.py clean for %s', req.name) clean_args = base_args + ['clean', '--all'] try: call_subprocess(clean_args, cwd=req.source_dir, show_stdout=False) return True except Exception: logger.error('Failed cleaning build dir for %s', req.name) return False def build( self, requirements, # type: Iterable[InstallRequirement] session, # type: PipSession autobuilding=False # type: bool ): # type: (...) -> List[InstallRequirement] """Build wheels. :param unpack: If True, replace the sdist we built from with the newly built wheel, in preparation for installation. :return: True if all the wheels built correctly. """ buildset = [] format_control = self.finder.format_control for req in requirements: if req.constraint: continue if req.is_wheel: if not autobuilding: logger.info( 'Skipping %s, due to already being wheel.', req.name, ) elif autobuilding and req.editable: pass elif autobuilding and not req.source_dir: pass elif autobuilding and req.link and not req.link.is_artifact: # VCS checkout. Build wheel just for this run. buildset.append((req, True)) else: ephem_cache = False if autobuilding: link = req.link base, ext = link.splitext() if not _contains_egg_info(base): # E.g. local directory. Build wheel just for this run. ephem_cache = True if "binary" not in format_control.get_allowed_formats( canonicalize_name(req.name)): logger.info( "Skipping bdist_wheel for %s, due to binaries " "being disabled for it.", req.name, ) continue buildset.append((req, ephem_cache)) if not buildset: return [] # Is any wheel build not using the ephemeral cache? if any(not ephem_cache for _, ephem_cache in buildset): have_directory_for_build = self._wheel_dir or ( autobuilding and self.wheel_cache.cache_dir ) assert have_directory_for_build # TODO by @pradyunsg # Should break up this method into 2 separate methods. # Build the wheels. logger.info( 'Building wheels for collected packages: %s', ', '.join([req.name for (req, _) in buildset]), ) _cache = self.wheel_cache # shorter name with indent_log(): build_success, build_failure = [], [] for req, ephem in buildset: python_tag = None if autobuilding: python_tag = pep425tags.implementation_tag if ephem: output_dir = _cache.get_ephem_path_for_link(req.link) else: output_dir = _cache.get_path_for_link(req.link) try: ensure_dir(output_dir) except OSError as e: logger.warning("Building wheel for %s failed: %s", req.name, e) build_failure.append(req) continue else: output_dir = self._wheel_dir wheel_file = self._build_one( req, output_dir, python_tag=python_tag, ) if wheel_file: build_success.append(req) if autobuilding: # XXX: This is mildly duplicative with prepare_files, # but not close enough to pull out to a single common # method. # The code below assumes temporary source dirs - # prevent it doing bad things. if req.source_dir and not os.path.exists(os.path.join( req.source_dir, PIP_DELETE_MARKER_FILENAME)): raise AssertionError( "bad source dir - missing marker") # Delete the source we built the wheel from req.remove_temporary_source() # set the build directory again - name is known from # the work prepare_files did. req.source_dir = req.build_location( self.preparer.build_dir ) # Update the link for this. req.link = Link(path_to_url(wheel_file)) assert req.link.is_wheel # extract the wheel into the dir unpack_url( req.link, req.source_dir, None, False, session=session, ) else: build_failure.append(req) # notify success/failure if build_success: logger.info( 'Successfully built %s', ' '.join([req.name for req in build_success]), ) if build_failure: logger.info( 'Failed to build %s', ' '.join([req.name for req in build_failure]), ) # Return a list of requirements that failed to build return build_failure
[]
[]
[ "PATH", "ENSUREPIP_OPTIONS" ]
[]
["PATH", "ENSUREPIP_OPTIONS"]
python
2
0
lldb/packages/Python/lldbsuite/test/test_result.py
""" Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. See https://llvm.org/LICENSE.txt for license information. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception Provides the LLDBTestResult class, which holds information about progress and results of a single test run. """ # System modules import os import traceback # Third-party modules import unittest2 # LLDB Modules from . import configuration from lldbsuite.test_event import build_exception class LLDBTestResult(unittest2.TextTestResult): """ Enforce a singleton pattern to allow introspection of test progress. Overwrite addError(), addFailure(), and addExpectedFailure() methods to enable each test instance to track its failure/error status. It is used in the LLDB test framework to emit detailed trace messages to a log file for easier human inspection of test failures/errors. """ __singleton__ = None __ignore_singleton__ = False @staticmethod def getTerminalSize(): import os env = os.environ def ioctl_GWINSZ(fd): try: import fcntl import termios import struct cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except: return return cr cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except: pass if not cr: cr = (env.get('LINES', 25), env.get('COLUMNS', 80)) return int(cr[1]), int(cr[0]) def __init__(self, *args): if not LLDBTestResult.__ignore_singleton__ and LLDBTestResult.__singleton__: raise Exception("LLDBTestResult instantiated more than once") super(LLDBTestResult, self).__init__(*args) LLDBTestResult.__singleton__ = self # Now put this singleton into the lldb module namespace. configuration.test_result = self # Computes the format string for displaying the counter. counterWidth = len(str(configuration.suite.countTestCases())) self.fmt = "%" + str(counterWidth) + "d: " self.indentation = ' ' * (counterWidth + 2) # This counts from 1 .. suite.countTestCases(). self.counter = 0 (width, height) = LLDBTestResult.getTerminalSize() def _config_string(self, test): compiler = getattr(test, "getCompiler", None) arch = getattr(test, "getArchitecture", None) return "%s-%s" % (compiler() if compiler else "", arch() if arch else "") def _exc_info_to_string(self, err, test): """Overrides superclass TestResult's method in order to append our test config info string to the exception info string.""" if hasattr(test, "getArchitecture") and hasattr(test, "getCompiler"): return '%sConfig=%s-%s' % (super(LLDBTestResult, self)._exc_info_to_string(err, test), test.getArchitecture(), test.getCompiler()) else: return super(LLDBTestResult, self)._exc_info_to_string(err, test) def getDescription(self, test): doc_first_line = test.shortDescription() if self.descriptions and doc_first_line: return '\n'.join((str(test), self.indentation + doc_first_line)) else: return str(test) def _getTestPath(self, test): # Use test.test_filename if the test was created with # lldbinline.MakeInlineTest(). if test is None: return "" elif hasattr(test, "test_filename"): return test.test_filename else: import inspect return inspect.getsourcefile(test.__class__) def _getFileBasedCategories(self, test): """ Returns the list of categories to which this test case belongs by collecting values of "categories" files. We start at the folder the test is in and traverse the hierarchy upwards until the test-suite root directory. """ start_path = self._getTestPath(test) import os.path folder = os.path.dirname(start_path) from lldbsuite import lldb_test_root as test_root if test_root != os.path.commonprefix([folder, test_root]): raise Exception("The test file %s is outside the test root directory" % start_path) categories = set() while not os.path.samefile(folder, test_root): categories_file_name = os.path.join(folder, "categories") if os.path.exists(categories_file_name): categories_file = open(categories_file_name, 'r') categories_str = categories_file.readline().strip() categories_file.close() categories.update(categories_str.split(',')) folder = os.path.dirname(folder) return list(categories) def getCategoriesForTest(self, test): """ Gets all the categories for the currently running test method in test case """ test_categories = [] test_method = getattr(test, test._testMethodName) if test_method is not None and hasattr(test_method, "categories"): test_categories.extend(test_method.categories) test_categories.extend(self._getFileBasedCategories(test)) return test_categories def hardMarkAsSkipped(self, test): getattr(test, test._testMethodName).__func__.__unittest_skip__ = True getattr( test, test._testMethodName).__func__.__unittest_skip_why__ = "test case does not fall in any category of interest for this run" def checkExclusion(self, exclusion_list, name): if exclusion_list: import re for item in exclusion_list: if re.search(item, name): return True return False def checkCategoryExclusion(self, exclusion_list, test): return not set(exclusion_list).isdisjoint( self.getCategoriesForTest(test)) def startTest(self, test): if configuration.shouldSkipBecauseOfCategories( self.getCategoriesForTest(test)): self.hardMarkAsSkipped(test) if self.checkExclusion( configuration.skip_tests, test.id()): self.hardMarkAsSkipped(test) self.counter += 1 test.test_number = self.counter if self.showAll: self.stream.write(self.fmt % self.counter) super(LLDBTestResult, self).startTest(test) def addSuccess(self, test): if (self.checkExclusion( configuration.xfail_tests, test.id()) or self.checkCategoryExclusion( configuration.xfail_categories, test)): self.addUnexpectedSuccess(test, None) return super(LLDBTestResult, self).addSuccess(test) self.stream.write( "PASS: LLDB (%s) :: %s\n" % (self._config_string(test), str(test))) def _isBuildError(self, err_tuple): exception = err_tuple[1] return isinstance(exception, build_exception.BuildError) def _saveBuildErrorTuple(self, test, err): # Adjust the error description so it prints the build command and build error # rather than an uninformative Python backtrace. build_error = err[1] error_description = "{}\nTest Directory:\n{}".format( str(build_error), os.path.dirname(self._getTestPath(test))) self.errors.append((test, error_description)) self._mirrorOutput = True def addError(self, test, err): configuration.sdir_has_content = True if self._isBuildError(err): self._saveBuildErrorTuple(test, err) else: super(LLDBTestResult, self).addError(test, err) method = getattr(test, "markError", None) if method: method() self.stream.write( "FAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test))) def addCleanupError(self, test, err): configuration.sdir_has_content = True super(LLDBTestResult, self).addCleanupError(test, err) method = getattr(test, "markCleanupError", None) if method: method() self.stream.write( "CLEANUP ERROR: LLDB (%s) :: %s\n%s\n" % (self._config_string(test), str(test), traceback.format_exc())) def addFailure(self, test, err): if (self.checkExclusion( configuration.xfail_tests, test.id()) or self.checkCategoryExclusion( configuration.xfail_categories, test)): self.addExpectedFailure(test, err, None) return configuration.sdir_has_content = True super(LLDBTestResult, self).addFailure(test, err) method = getattr(test, "markFailure", None) if method: method() self.stream.write( "FAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test))) if configuration.use_categories: test_categories = self.getCategoriesForTest(test) for category in test_categories: if category in configuration.failures_per_category: configuration.failures_per_category[ category] = configuration.failures_per_category[category] + 1 else: configuration.failures_per_category[category] = 1 def addExpectedFailure(self, test, err, bugnumber): configuration.sdir_has_content = True super(LLDBTestResult, self).addExpectedFailure(test, err, bugnumber) method = getattr(test, "markExpectedFailure", None) if method: method(err, bugnumber) self.stream.write( "XFAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test))) def addSkip(self, test, reason): configuration.sdir_has_content = True super(LLDBTestResult, self).addSkip(test, reason) method = getattr(test, "markSkippedTest", None) if method: method() self.stream.write( "UNSUPPORTED: LLDB (%s) :: %s (%s) \n" % (self._config_string(test), str(test), reason)) def addUnexpectedSuccess(self, test, bugnumber): configuration.sdir_has_content = True super(LLDBTestResult, self).addUnexpectedSuccess(test, bugnumber) method = getattr(test, "markUnexpectedSuccess", None) if method: method(bugnumber) self.stream.write( "XPASS: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
[]
[]
[]
[]
[]
python
0
0
ci/docs/__init__.py
# -*- coding: utf-8 -*- import copy import os import subprocess from pathlib import Path from typing import Optional import cookiecutter from deepdiff import DeepHash from pydoc_markdown.main import RenderSession from bring.defaults import bring_app_dirs as project_dirs CACHE_DIR = os.path.join(project_dirs.user_cache_dir, "doc_gen") if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR) os_env_vars = copy.copy(os.environ) os_env_vars["CONSOLE_WIDTH"] = "100" def define_env(env): """ This is the hook for defining variables, macros and filters - variables: the dictionary that contains the environment variables - macro: a decorator function, to declare a macro. """ # env.variables["baz"] = "John Doe" @env.macro def cli( *command, print_command: bool = True, code_block: bool = True, max_height: Optional[int] = None, ): hashes = DeepHash(command) hash_str = hashes[command] cache_file: Path = Path(os.path.join(CACHE_DIR, hash_str)) if cache_file.is_file(): stdout = cache_file.read_text() else: try: result = subprocess.check_output(command, env=os_env_vars) stdout = result.decode() cache_file.write_text(stdout) except subprocess.CalledProcessError as e: print("stdout:") print(e.stdout) print("stderr:") print(e.stderr) raise e if print_command: stdout = f"> {' '.join(command)}\n{stdout}" if code_block: stdout = "``` console\n" + stdout + "\n```\n" if max_height is not None and max_height > 0: stdout = f"<div style='max-height:{max_height}px;overflow:auto'>\n{stdout}\n</div>" return stdout @env.macro def inline_file_as_codeblock(path, format: str = ""): f = Path(path) return f"```{format}\n{f.read_text()}\n```" def build_api_docs(*args, **kwargs): root_dir = os.path.join(os.path.dirname(__file__), "..", "..") config = os.path.join(root_dir, "pydoc-markdown.yml") session = RenderSession(config) pydocmd = session.load() session.render(pydocmd)
[]
[]
[]
[]
[]
python
0
0
appengine-compat/exported_appengine_sdk/google/appengine/tools/devappserver2/devappserver2.py
#!/usr/bin/env python # # Copyright 2007 Google 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. # """The main entry point for the new development server.""" import logging import os import sys import time import portpicker from google.appengine.api import request_info from google.appengine.tools.devappserver2 import api_server from google.appengine.tools.devappserver2 import application_configuration from google.appengine.tools.devappserver2 import cli_parser from google.appengine.tools.devappserver2 import constants from google.appengine.tools.devappserver2 import dispatcher from google.appengine.tools.devappserver2 import metrics from google.appengine.tools.devappserver2 import runtime_config_pb2 from google.appengine.tools.devappserver2 import shutdown from google.appengine.tools.devappserver2 import update_checker from google.appengine.tools.devappserver2 import wsgi_request_info from google.appengine.tools.devappserver2.admin import admin_server # Initialize logging early -- otherwise some library packages may # pre-empt our log formatting. NOTE: the level is provisional; it may # be changed in main() based on the --dev_appserver_log_level flag. logging.basicConfig( level=logging.INFO, format='%(levelname)-8s %(asctime)s %(filename)s:%(lineno)s] %(message)s') PARSER = cli_parser.create_command_line_parser( cli_parser.DEV_APPSERVER_CONFIGURATION) def _setup_environ(app_id): """Sets up the os.environ dictionary for the front-end server and API server. This function should only be called once. Args: app_id: The id of the application. """ os.environ['APPLICATION_ID'] = app_id class DevelopmentServer(object): """Encapsulates the logic for the development server. Only a single instance of the class may be created per process. See _setup_environ. """ def __init__(self): # A list of servers that are currently running. self._running_modules = [] self._module_to_port = {} self._dispatcher = None self._options = None def module_to_address(self, module_name, instance=None): """Returns the address of a module.""" if module_name is None: return self._dispatcher.dispatch_address return self._dispatcher.get_hostname( module_name, self._dispatcher.get_default_version(module_name), instance) def start(self, options): """Start devappserver2 servers based on the provided command line arguments. Args: options: An argparse.Namespace containing the command line arguments. """ self._options = options logging.getLogger().setLevel( constants.LOG_LEVEL_TO_PYTHON_CONSTANT[options.dev_appserver_log_level]) parsed_env_variables = dict(options.env_variables or []) configuration = application_configuration.ApplicationConfiguration( config_paths=options.config_paths, app_id=options.app_id, runtime=options.runtime, env_variables=parsed_env_variables) if options.google_analytics_client_id: metrics_logger = metrics.GetMetricsLogger() metrics_logger.Start( options.google_analytics_client_id, options.google_analytics_user_agent, {module.runtime for module in configuration.modules}, {module.env or 'standard' for module in configuration.modules}) if options.skip_sdk_update_check: logging.info('Skipping SDK update check.') else: update_checker.check_for_updates(configuration) # There is no good way to set the default encoding from application code # (it needs to be done during interpreter initialization in site.py or # sitecustomize.py) so just warn developers if they have a different # encoding than production. if sys.getdefaultencoding() != constants.PROD_DEFAULT_ENCODING: logging.warning( 'The default encoding of your local Python interpreter is set to %r ' 'while App Engine\'s production environment uses %r; as a result ' 'your code may behave differently when deployed.', sys.getdefaultencoding(), constants.PROD_DEFAULT_ENCODING) if options.port == 0: logging.warn('DEFAULT_VERSION_HOSTNAME will not be set correctly with ' '--port=0') _setup_environ(configuration.app_id) # grpc_proxy is only needed for python2 because remote_api_stub.py is # imported in local python runtime sandbox. For more details, see # grpc_proxy_util.py. grpc_proxy_port = portpicker.PickUnusedPort() self._dispatcher = dispatcher.Dispatcher( configuration, options.host, options.port, options.auth_domain, constants.LOG_LEVEL_TO_RUNTIME_CONSTANT[options.log_level], self._create_php_config(options), self._create_python_config(options, grpc_proxy_port), self._create_java_config(options), self._create_go_config(options), self._create_custom_config(options), self._create_cloud_sql_config(options), self._create_vm_config(options), self._create_module_to_setting(options.max_module_instances, configuration, '--max_module_instances'), options.use_mtime_file_watcher, options.watcher_ignore_re, options.automatic_restart, options.allow_skipped_files, self._create_module_to_setting( options.threadsafe_override, configuration, '--threadsafe_override'), options.external_port) wsgi_request_info_ = wsgi_request_info.WSGIRequestInfo(self._dispatcher) storage_path = api_server.get_storage_path( options.storage_path, configuration.app_id) datastore_emulator_host = ( parsed_env_variables['DATASTORE_EMULATOR_HOST'] if 'DATASTORE_EMULATOR_HOST' in parsed_env_variables else None) apiserver = api_server.create_api_server( wsgi_request_info_, storage_path, options, configuration.app_id, configuration.modules[0].application_root, datastore_emulator_host) apiserver.start() self._running_modules.append(apiserver) if options.grpc_apis: grpc_apiserver = api_server.GRPCAPIServer(options.grpc_api_port) grpc_apiserver.start() self._running_modules.append(grpc_apiserver) # We declare grpc_proxy_util as global, otherwise it cannot be accessed # from outside of this function. global grpc_proxy_util # pylint: disable=g-import-not-at-top # We lazy import here because grpc binaries are not always present. from google.appengine.tools.devappserver2 import grpc_proxy_util grpc_proxy = grpc_proxy_util.GrpcProxyServer(grpc_proxy_port) grpc_proxy.start() self._running_modules.append(grpc_proxy) self._dispatcher.start( options.api_host, apiserver.port, wsgi_request_info_, options.grpc_apis) xsrf_path = os.path.join(storage_path, 'xsrf') admin = admin_server.AdminServer(options.admin_host, options.admin_port, self._dispatcher, configuration, xsrf_path) admin.start() self._running_modules.append(admin) try: default = self._dispatcher.get_module_by_name('default') apiserver.set_balanced_address(default.balanced_address) except request_info.ModuleDoesNotExistError: logging.warning('No default module found. Ignoring.') def stop(self): """Stops all running devappserver2 modules and report metrics.""" while self._running_modules: self._running_modules.pop().quit() if self._dispatcher: self._dispatcher.quit() if self._options.google_analytics_client_id: kwargs = {} watcher_results = (self._dispatcher.get_watcher_results() if self._dispatcher else None) # get_watcher_results() only returns results for modules that have at # least one record of file change. Hence avoiding divide by zero error # when computing avg_time. if watcher_results: zipped = zip(*watcher_results) total_time = sum(zipped[0]) total_changes = sum(zipped[1]) # Google Analytics Event value cannot be float numbers, so we round the # value into integers, and measure in microseconds to ensure accuracy. avg_time = int(1000000*total_time/total_changes) # watcher_class is same on all modules. watcher_class = zipped[2][0] kwargs = { metrics.GOOGLE_ANALYTICS_DIMENSIONS['FileWatcherType']: watcher_class, metrics.GOOGLE_ANALYTICS_METRICS['FileChangeDetectionAverageTime']: avg_time, metrics.GOOGLE_ANALYTICS_METRICS['FileChangeEventCount']: total_changes } metrics.GetMetricsLogger().Stop(**kwargs) @staticmethod def _create_php_config(options): php_config = runtime_config_pb2.PhpConfig() if options.php_executable_path: php_config.php_executable_path = os.path.abspath( options.php_executable_path) php_config.enable_debugger = options.php_remote_debugging if options.php_gae_extension_path: php_config.gae_extension_path = os.path.abspath( options.php_gae_extension_path) if options.php_xdebug_extension_path: php_config.xdebug_extension_path = os.path.abspath( options.php_xdebug_extension_path) return php_config @staticmethod def _create_python_config(options, grpc_proxy_port=None): python_config = runtime_config_pb2.PythonConfig() if options.python_startup_script: python_config.startup_script = os.path.abspath( options.python_startup_script) if options.python_startup_args: python_config.startup_args = options.python_startup_args if grpc_proxy_port: python_config.grpc_proxy_port = grpc_proxy_port return python_config @staticmethod def _create_java_config(options): java_config = runtime_config_pb2.JavaConfig() if options.jvm_flag: java_config.jvm_args.extend(options.jvm_flag) return java_config @staticmethod def _create_go_config(options): go_config = runtime_config_pb2.GoConfig() if options.go_work_dir: go_config.work_dir = options.go_work_dir if options.enable_watching_go_path: go_config.enable_watching_go_path = True return go_config @staticmethod def _create_custom_config(options): custom_config = runtime_config_pb2.CustomConfig() custom_config.custom_entrypoint = options.custom_entrypoint custom_config.runtime = options.runtime return custom_config @staticmethod def _create_cloud_sql_config(options): cloud_sql_config = runtime_config_pb2.CloudSQL() cloud_sql_config.mysql_host = options.mysql_host cloud_sql_config.mysql_port = options.mysql_port cloud_sql_config.mysql_user = options.mysql_user cloud_sql_config.mysql_password = options.mysql_password if options.mysql_socket: cloud_sql_config.mysql_socket = options.mysql_socket return cloud_sql_config @staticmethod def _create_vm_config(options): vm_config = runtime_config_pb2.VMConfig() vm_config.enable_logs = options.enable_mvm_logs return vm_config @staticmethod def _create_module_to_setting(setting, configuration, option): """Create a per-module dictionary configuration. Creates a dictionary that maps a module name to a configuration setting. Used in conjunction with parse_per_module_option. Args: setting: a value that can be None, a dict of str->type or a single value. configuration: an ApplicationConfiguration object. option: the option name the setting came from. Returns: A dict of str->type. """ if setting is None: return {} module_names = [module_configuration.module_name for module_configuration in configuration.modules] if isinstance(setting, dict): # Warn and remove a setting if the module name is unknown. module_to_setting = {} for module_name, value in setting.items(): if module_name in module_names: module_to_setting[module_name] = value else: logging.warning('Unknown module %r for %r', module_name, option) return module_to_setting # Create a dict with an entry for every module. return {module_name: setting for module_name in module_names} def main(): shutdown.install_signal_handlers() # The timezone must be set in the devappserver2 process rather than just in # the runtime so printed log timestamps are consistent and the taskqueue stub # expects the timezone to be UTC. The runtime inherits the environment. os.environ['TZ'] = 'UTC' if hasattr(time, 'tzset'): # time.tzet() should be called on Unix, but doesn't exist on Windows. time.tzset() options = PARSER.parse_args() dev_server = DevelopmentServer() try: dev_server.start(options) shutdown.wait_until_shutdown() except: # pylint: disable=bare-except metrics.GetMetricsLogger().LogOnceOnStop( metrics.DEVAPPSERVER_CATEGORY, metrics.ERROR_ACTION, label=metrics.GetErrorDetails()) raise finally: dev_server.stop() if __name__ == '__main__': main()
[]
[]
[ "TZ", "APPLICATION_ID" ]
[]
["TZ", "APPLICATION_ID"]
python
2
0
simulation_ws/src/rl-agent/markov/rover_agent.py
""" This is single machine training worker. It starts a local training and stores the model in S3. """ import argparse import copy from markov.s3_boto_data_store import S3BotoDataStore, S3BotoDataStoreParameters from rl_coach.base_parameters import TaskParameters, Frameworks from rl_coach.utils import short_dynamic_import import imp import markov from markov import utils import markov.environments import markov.presets import os MARKOV_DIRECTORY = os.path.dirname(markov.__file__) CUSTOM_FILES_PATH = "./custom_files" if not os.path.exists(CUSTOM_FILES_PATH): os.makedirs(CUSTOM_FILES_PATH) def start_graph(graph_manager: 'GraphManager', task_parameters: 'TaskParameters'): graph_manager.create_graph(task_parameters) # save randomly initialized graph checkpoint # OR restore last save checkpoint graph_manager.save_checkpoint() # comment out this line if using restore # graph_manager.restore_checkpoint() # comment out this line if using save # Start the training graph_manager.improve() def add_items_to_dict(target_dict, source_dict): updated_task_parameters = copy.copy(source_dict) updated_task_parameters.update(target_dict) return updated_task_parameters def should_stop_training_based_on_evaluation(): return False def main(): parser = argparse.ArgumentParser() parser.add_argument('--markov-preset-file', help="(string) Name of a preset file to run in Markov's preset directory.", type=str, default=os.environ.get("MARKOV_PRESET_FILE", "mars_presets.py")) parser.add_argument('-c', '--local_model_directory', help='(string) Path to a folder containing a checkpoint to restore the model from.', type=str, default=os.environ.get("LOCAL_MODEL_DIRECTORY", "./checkpoint")) parser.add_argument('-n', '--num_workers', help="(int) Number of workers for multi-process based agents, e.g. A3C", default=1, type=int) parser.add_argument('--model-s3-bucket', help='(string) S3 bucket where trained models are stored. It contains model checkpoints.', type=str, default=os.environ.get("MODEL_S3_BUCKET")) parser.add_argument('--model-s3-prefix', help='(string) S3 prefix where trained models are stored. It contains model checkpoints.', type=str, default=os.environ.get("MODEL_S3_PREFIX")) parser.add_argument('--aws-region', help='(string) AWS region', type=str, default=os.environ.get("ROS_AWS_REGION", "us-west-1")) parser.add_argument('--checkpoint-save-secs', help="(int) Time period in second between 2 checkpoints", type=int, default=600) parser.add_argument('--save-frozen-graph', help="(bool) True if we need to store the frozen graph", type=bool, default=True) args = parser.parse_args() if args.markov_preset_file: markov_path = imp.find_module("markov")[1] preset_location = os.path.join(markov_path, "presets", args.markov_preset_file) path_and_module = preset_location + ":graph_manager" graph_manager = short_dynamic_import(path_and_module, ignore_module_case=True) else: raise ValueError("Unable to determine preset file") # TODO: support other frameworks task_parameters = TaskParameters(framework_type=Frameworks.tensorflow, checkpoint_save_secs=args.checkpoint_save_secs) task_parameters.__dict__['checkpoint_save_dir'] = args.local_model_directory task_parameters.__dict__ = add_items_to_dict(task_parameters.__dict__, args.__dict__) data_store_params_instance = S3BotoDataStoreParameters(bucket_name=args.model_s3_bucket, s3_folder=args.model_s3_prefix, checkpoint_dir=args.local_model_directory, aws_region=args.aws_region) data_store = S3BotoDataStore(data_store_params_instance) if args.save_frozen_graph: data_store.graph_manager = graph_manager graph_manager.data_store_params = data_store_params_instance graph_manager.data_store = data_store graph_manager.should_stop = should_stop_training_based_on_evaluation start_graph(graph_manager=graph_manager, task_parameters=task_parameters) if __name__ == '__main__': main()
[]
[]
[ "MODEL_S3_BUCKET", "LOCAL_MODEL_DIRECTORY", "MODEL_S3_PREFIX", "MARKOV_PRESET_FILE", "ROS_AWS_REGION" ]
[]
["MODEL_S3_BUCKET", "LOCAL_MODEL_DIRECTORY", "MODEL_S3_PREFIX", "MARKOV_PRESET_FILE", "ROS_AWS_REGION"]
python
5
0
qriter/noxfile.py
"""sessions for running tasks to build docs and packages nox -s docs """ import os import nox CI = "GITHUB_ACTION" in os.environ or "READTHEDOCS" in os.environ @nox.session(reuse_venv=True, python=False if CI else "3.8") def docs(session): session.install(*"""-rworks/requirements-docs.txt --ignore-installed""".split()) session.run(*"""doit build_docs""".split()) @nox.session(reuse_venv=True, python=False if CI else "3.8", venv_backend="conda") def pdf(session): session.conda_install( *"""jupyter-book[sphinx,pdflatex] texlive-core -cconda-forge""".split() ) session.install("bindep") session.run("bindep") session.run(*"jb build . --toc qww/toc.yml --config qww/config.yml".split()) session.run(*"jb build . --toc qww/toc.yml --config qww/config.yml --builder pdflatex".split())
[]
[]
[]
[]
[]
python
0
0
autotest/gdrivers/netcdf_cf.py
#!/usr/bin/env python ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test NetCDF driver support. # Author: Frank Warmerdam <[email protected]> # ############################################################################### # Copyright (c) 2007, Frank Warmerdam <[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. ############################################################################### import os import sys from osgeo import gdal from osgeo import osr from gdalconst import * sys.path.append( '../pymod' ) import gdaltest import imp # for netcdf_cf_setup() import netcdf from netcdf import netcdf_setup, netcdf_test_copy ############################################################################### # Netcdf CF compliance Functions ############################################################################### ############################################################################### #check for necessary files and software def netcdf_cf_setup(): #global vars gdaltest.netcdf_cf_method = None gdaltest.netcdf_cf_files = None gdaltest.netcdf_cf_check_error = '' #if netcdf is not supported, skip detection if gdaltest.netcdf_drv is None: return 'skip' #skip if on windows if os.name != 'posix': print('NOTICE: will skip CF checks because OS is not posix!') return 'skip' #try local method cdms2_installed = False try: imp.find_module( 'cdms2' ) cdms2_installed = True except ImportError: print( 'NOTICE: cdms2 not installed!' ) print( ' see installation notes at http://pypi.python.org/pypi/cfchecker' ) pass if cdms2_installed: xml_dir = './data/netcdf_cf_xml' tmp_dir = './tmp/cache' files = dict() files['a'] = xml_dir+'/area-type-table.xml' files['s'] = tmp_dir+'/cf-standard-name-table-v18.xml' #either find udunits path in UDUNITS_PATH, or based on location of udunits app, or copy all .xml files to data #opt_u = '/home/soft/share/udunits/udunits2.xml' files['u'] = xml_dir+'/udunits2.xml' #look for xml files if not ( os.path.exists(files['a']) and os.path.exists(files['s']) and os.path.exists(files['u']) ): print('NOTICE: cdms2 installed, but necessary xml files are not found!') print(' the following files must exist:') print(' '+xml_dir+'/area-type-table.xml from http://cf-pcmdi.llnl.gov/documents/cf-standard-names/area-type-table/1/area-type-table.xml') print(' '+tmp_dir+'/cf-standard-name-table-v18.xml - http://cf-pcmdi.llnl.gov/documents/cf-standard-names/standard-name-table/18/cf-standard-name-table.xml') print(' '+xml_dir+'/udunits2*.xml from a UDUNITS2 install') #try to get cf-standard-name-table if not os.path.exists(files['s']): #print ' downloading cf-standard-name-table.xml (v18) from http://cf-pcmdi.llnl.gov ...' if not gdaltest.download_file('http://cf-pcmdi.llnl.gov/documents/cf-standard-names/standard-name-table/18/cf-standard-name-table.xml', 'cf-standard-name-table-v18.xml'): print(' Failed to download, please get it and try again.') if os.path.exists(files['a']) and os.path.exists(files['s']) and os.path.exists(files['u']): gdaltest.netcdf_cf_method = 'local' gdaltest.netcdf_cf_files = files print('NOTICE: netcdf CF compliance checks: using local checker script') return 'success' #skip http method if GDAL_DOWNLOAD_TEST_DATA and GDAL_RUN_SLOW_TESTS are not defined if not 'GDAL_DOWNLOAD_TEST_DATA' in os.environ: print('NOTICE: skipping netcdf CF compliance checks') print('to enable remote http checker script, define GDAL_DOWNLOAD_TEST_DATA') return 'success' if not gdaltest.run_slow_tests(): print('NOTICE: skipping netcdf CF compliance checks') return 'success' #http method with curl, should use python module but easier for now success = False try: (ret, err) = gdaltest.runexternal_out_and_err('curl') except : print('no curl executable') else: #make sure script is responding handle = gdaltest.gdalurlopen("http://puma.nerc.ac.uk/cgi-bin/cf-checker.pl") if handle is not None: success = True else: print('script not responding') if success: gdaltest.netcdf_cf_method = 'http' print('NOTICE: netcdf CF compliance ckecks: using remote http checker script, consider installing cdms2 locally') return 'success' if gdaltest.netcdf_cf_method is None: print('NOTICE: skipping netcdf CF compliance checks') return 'success' ############################################################################### #build a command used to check ifile def netcdf_cf_get_command(ifile, version='auto'): command = '' #fetch method obtained previously method = gdaltest.netcdf_cf_method if method is not None: if method is 'local': command = './netcdf_cfchecks.py -a ' + gdaltest.netcdf_cf_files['a'] \ + ' -s ' + gdaltest.netcdf_cf_files['s'] \ + ' -u ' + gdaltest.netcdf_cf_files['u'] \ + ' -v ' + version +' ' + ifile elif method is 'http': #command = shlex.split( 'curl --form cfversion="1.5" --form upload=@' + ifile + ' --form submit=\"Check file\" "http://puma.nerc.ac.uk/cgi-bin/cf-checker.pl"' ) #switch to 1.5 as driver now supports, and auto when it becomes available version = '1.5' command = 'curl --form cfversion=' + version + ' --form upload=@' + ifile + ' --form submit=\"Check file\" "http://puma.nerc.ac.uk/cgi-bin/cf-checker.pl"' return command ############################################################################### # Check a file for CF compliance def netcdf_cf_check_file(ifile,version='auto', silent=True): #if not silent: # print 'checking file ' + ifile gdaltest.netcdf_cf_check_error = '' if ( not os.path.exists(ifile) ): return 'skip' output_all = '' command = netcdf_cf_get_command(ifile, version='auto') if command is None or command=='': gdaltest.post_reason('no suitable method found, skipping') return 'skip' try: if gdaltest.netcdf_cf_method == 'http': print('calling ' + command) (ret, err) = gdaltest.runexternal_out_and_err(command) except : gdaltest.post_reason('ERROR with command - ' + command) return 'fail' output_all = ret output_err = '' output_warn = '' for line in output_all.splitlines( ): #optimize this with regex if 'ERROR' in line and not 'ERRORS' in line: output_err = output_err + '\n' + line elif 'WARNING' in line and not 'WARNINGS' in line: output_warn = output_warn + '\n' + line result = 'success' if output_err != '': result = 'fail' if output_err != '': gdaltest.netcdf_cf_check_error += output_err.strip() if not silent: print('=> CF check ERRORS for file ' + ifile + ' : ' + output_err) if output_warn != '': if not silent: print('CF check WARNINGS for file ' + ifile + ' : ' + output_warn) return result ############################################################################### # Netcdf CF projection Functions and data ############################################################################### ############################################################################### # Definitions to test projections that are supported by CF # Tuple structure: # 0: Short code (eg AEA) - (no GDAL significance, just for filenames etc) # 1: official name from CF-1 conventions # 2: EPSG code, or WKT, to tell GDAL to do reprojection # 3: Actual attribute official name of grid mapping # 4: List of required attributes to define projection # 5: List of required coordinate variable standard name attributes netcdf_cfproj_tuples = [ ("AEA", "Albers Equal Area", "EPSG:3577", "albers_conical_equal_area", ['standard_parallel', 'longitude_of_central_meridian', 'latitude_of_projection_origin', 'false_easting', 'false_northing'], ['projection_x_coordinate','projection_y_coordinate']), ("AZE", "Azimuthal Equidistant", #Didn't have EPSG suitable for AU "+proj=aeqd +lat_0=-37 +lon_0=145 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", "azimuthal_equidistant", ['longitude_of_projection_origin', 'latitude_of_projection_origin', 'false_easting', 'false_northing'], ['projection_x_coordinate','projection_y_coordinate']), ("LAZEA", "Lambert azimuthal equal area", #Specify proj4 since no approp LAZEA for AU #"+proj=laea +lat_0=0 +lon_0=134 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs", "+proj=laea +lat_0=-37 +lon_0=145 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", "lambert_azimuthal_equal_area", ['longitude_of_projection_origin', 'latitude_of_projection_origin', 'false_easting', 'false_northing'], ['projection_x_coordinate','projection_y_coordinate']), ("LC_2SP", "Lambert conformal", "EPSG:3112", "lambert_conformal_conic", ['standard_parallel', 'longitude_of_central_meridian', 'latitude_of_projection_origin', 'false_easting', 'false_northing'], ['projection_x_coordinate','projection_y_coordinate']), # TODO: Test LCC with 1SP ("LCEA", "Lambert Cylindrical Equal Area", "+proj=cea +lat_ts=-37 +lon_0=145 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", "lambert_cylindrical_equal_area", ['longitude_of_central_meridian', 'standard_parallel', # TODO: OR 'scale_factor_at_projection_origin' 'false_easting', 'false_northing'], ['projection_x_coordinate','projection_y_coordinate']), # 2 entries for Mercator, since attribs different for 1SP or 2SP ("M-1SP", "Mercator", "+proj=merc +lon_0=145 +k_0=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", "mercator", ['longitude_of_projection_origin', 'scale_factor_at_projection_origin', 'false_easting', 'false_northing'], ['projection_x_coordinate','projection_y_coordinate']), # Commented out as it seems GDAL itself's support of Mercator with 2SP # is a bit dodgy ("M-2SP", "Mercator", "+proj=merc +lat_ts=-37 +lon_0=145 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", # Trying with full WKT: #"""PROJCS["unnamed", GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0], UNIT["degree",0.0174532925199433], AUTHORITY["EPSG","4326"]], PROJECTION["Mercator_2SP"], PARAMETER["central_meridian",146], PARAMETER["standard_parallel_1",-37], PARAMETER["latitude_of_origin",0], PARAMETER["false_easting",0], PARAMETER["false_northing",0], UNIT["metre",1, AUTHORITY["EPSG","9001"]]]""", "mercator", ['longitude_of_projection_origin', 'standard_parallel', 'false_easting', 'false_northing'], ['projection_x_coordinate','projection_y_coordinate']), ("Ortho", "Orthographic", "+proj=ortho +lat_0=-37 +lon_0=145 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", "orthographic", ['longitude_of_projection_origin', 'latitude_of_projection_origin', 'false_easting', 'false_northing'], ['projection_x_coordinate', 'projection_y_coordinate']), # Seems GDAL may have problems with Polar stereographic, as it # considers these "local coordinate systems" ("PSt", "Polar stereographic", "+proj=stere +lat_ts=-37 +lat_0=-90 +lon_0=145 +k_0=1.0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", "polar_stereographic", ['straight_vertical_longitude_from_pole', 'latitude_of_projection_origin', 'standard_parallel', 'false_easting', 'false_northing'], ['projection_x_coordinate', 'projection_y_coordinate']), ("St", "Stereographic", "+proj=stere +lat_0=-37 +lon_0=145 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs", #'PROJCS["unnamed", GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0], UNIT["degree",0.0174532925199433], AUTHORITY["EPSG","4326"]], PROJECTION["Stereographic"], PARAMETER["latitude_of_origin",-37.5], PARAMETER["central_meridian",145], PARAMETER["scale_factor",1], PARAMETER["false_easting",0], PARAMETER["false_northing",0], UNIT["metre",1, AUTHORITY["EPSG","9001"]]]', "stereographic", ['longitude_of_projection_origin', 'latitude_of_projection_origin', 'scale_factor_at_projection_origin', 'false_easting', 'false_northing'], ['projection_x_coordinate', 'projection_y_coordinate']), #Note: Rotated Pole not in this list, as seems not GDAL-supported ("TM", "Transverse Mercator", "EPSG:32655", #UTM Zone 55N "transverse_mercator", [ 'scale_factor_at_central_meridian', 'longitude_of_central_meridian', 'latitude_of_projection_origin', 'false_easting', 'false_northing'], ['projection_x_coordinate','projection_y_coordinate']) ] #By default, we will use GeoTiff as the 'intermediate' raster format # for gdalwarp'ing into before gdal_translate to NetCDF. # But since GeoTiff can't act as a storage format for certain projections # (eg Mercator-2SP), we will choose other intermediate formats for certain # projection. # The following array maps projection short code, to driver format to use netcdf_cfproj_def_int_format = "GTiff" netcdf_cfproj_int_fmt_maps = { "M-2SP":'HFA' } netcdf_cfproj_format_fnames = {"HFA":"img", "GTiff":"tif", "NITF":"nitf", "ERS":"ers"} ############################################################################### # Check support for given projection tuple definitions # For each projection, warp the original file and then create a netcdf def netcdf_cfproj_testcopy(projTuples, origTiff, interFormats, inPath, outPath, resFilename): """Test a Geotiff file can be converted to NetCDF, and projection in CF-1 conventions can be successfully maintained. Save results to file. :arg: projTuples - list of tuples :arg: interFormats - dict of intermediate format overrides :arg: outPath - path to save output :arg: resFilename - results filename to write to. """ silent = True gdaltest.netcdf_drv_silent = True bWriteGdalTags="YES" #silent = False gdaltest.netcdf_drv_silent = False # bWriteGdalTags="NO" result = 'success' # Test if ncdump is available try: (ret, err) = gdaltest.runexternal_out_and_err('ncdump -h') except: #nothing is supported as ncdump not found print('NOTICE: netcdf version not found') return 'skip' i = err.find('netcdf library version ') #version not found if i == -1: print('NOTICE: netcdf version not found') return 'skip' if not os.path.exists(outPath): os.makedirs(outPath) resFile = open(os.path.join(outPath, resFilename), "w") if not os.path.exists(outPath): os.makedirs(outPath) heading = "Testing GDAL translation results to NetCDF\n" resFile.write(heading) resFile.write(len(heading)*"="+"\n") # now = datetime.datetime.now() # resFile.write("*Date/time:* %s\n" % (now.strftime("%Y-%m-%d %H:%M"))) resFile.write("\n") resPerProj = {} dsTiff = gdal.Open( os.path.join(inPath, origTiff), GA_ReadOnly ); s_srs_wkt = dsTiff.GetProjection() #objects to hold the various tests i_t = 0 tst = {} tst_res = {} for proj in projTuples: try: intFmt = interFormats[proj[0]] except KeyError: intFmt = netcdf_cfproj_def_int_format intExt = netcdf_cfproj_format_fnames[intFmt] # Our little results data structures if not silent: print("") print("Testing %s (%s) translation:" % (proj[0], proj[1])) if not silent: print("About to create raster in chosen SRS") projVrt = os.path.join(outPath, "%s_%s.vrt" % \ (origTiff.rstrip('.tif'), proj[0] )) projRaster = os.path.join(outPath, "%s_%s.%s" % \ (origTiff.rstrip('.tif'), proj[0], intExt )) srs = osr.SpatialReference() srs.SetFromUserInput(proj[2]) t_srs_wkt = srs.ExportToWkt() if not silent: print("going to warp file "+origTiff+"\n" + s_srs_wkt + "\ninto file "+projRaster + "\n" + t_srs_wkt) dswarp = gdal.AutoCreateWarpedVRT( dsTiff, s_srs_wkt, t_srs_wkt, GRA_NearestNeighbour, 0 ); drv_inter = gdal.GetDriverByName(intFmt); drv_netcdf = gdal.GetDriverByName("netcdf"); dsw = drv_inter.CreateCopy(projRaster, dswarp, 0) if not silent: print("Warped %s to %s" % (proj[0], projRaster)) projNc = os.path.join(outPath, "%s_%s.nc" % \ (origTiff.rstrip('.tif'), proj[0] )) #Force GDAL tags to be written to make testing easier, with preserved datum etc ncCoOpts = "-co WRITE_GDAL_TAGS=yes" if not silent: print("About to translate to NetCDF") dst = drv_netcdf.CreateCopy(projNc, dsw, 0, [ 'WRITE_GDAL_TAGS='+bWriteGdalTags ]) #For drivers like HFA, line below ESSENTIAL so that all info is # saved to new raster file - which we'll reopen later and want # to be fully updated. dsw = None dst = None if not silent: print("Translated to %s" % (projNc)) transWorked, resDetails = netcdf_cfproj_test_cf(proj, projNc) resPerProj[proj[0]] = resDetails resFile.write("%s (%s): " % (proj[0], proj[1])) if transWorked: resFile.write("OK\n") else: resFile.write("BAD\n") if 'missingProjName' in resPerProj[proj[0]]: resFile.write("\tMissing proj name '%s'\n" % \ (resPerProj[proj[0]]['missingProjName'])) for attrib in resPerProj[proj[0]]['missingAttrs']: resFile.write("\tMissing attrib '%s'\n" % (attrib)) for cVarStdName in resPerProj[proj[0]]['missingCoordVarStdNames']: resFile.write("\tMissing coord var with std name '%s'\n" \ % (cVarStdName)) if 'cfcheck_error' in resPerProj[proj[0]]: resFile.write("\tFailed cf check: %s\n" % \ (resPerProj[proj[0]]['cfcheck_error'])) # test file copy # We now copy to a new file, just to be safe projNc2 = projNc.rstrip('.nc') + '2.nc' projRaster2 = os.path.join(outPath, "%s_%s2.%s" % \ (origTiff.rstrip('.tif'), proj[0], intExt )) tst_res[i_t+1] = netcdf_test_copy( projRaster, 1, None, projNc2, [], 'NETCDF' ) tst_res[i_t+2] = netcdf_test_copy( projNc2, 1, None, projRaster2, [], intFmt ) if tst_res[i_t+1] == 'fail' or tst_res[i_t+2] == 'fail': result = 'fail' i_t = i_t + 2 resFile.close() if not silent: print("\n" + "*" * 80) print("Saved results to file %s" % (os.path.join(outPath, resFilename))) #result = 'success' resFile = open(os.path.join(outPath, resFilename), "r") resStr = resFile.read() if resStr.find('BAD') != -1: print('\nCF projection tests failed, here is the output (stored in file %s)\n' % \ (os.path.join(outPath, resFilename))) print(resStr) result = 'fail' return result ############################################################################### # Test an NC file has valid conventions according to passed-in proj tuple # Note: current testing strategy is a fairly simple attribute search. # this could use gdal netcdf driver for getting attribs instead... def netcdf_cfproj_test_cf(proj, projNc): transWorked = True command = 'ncdump -h ' + projNc (ret, err) = gdaltest.runexternal_out_and_err(command) if err != '': print(err) dumpStr = ret resDetails = {} resDetails['missingAttrs'] = [] resDetails['missingCoordVarStdNames'] = [] if (':grid_mapping_name = "%s"' % (proj[3])) not in dumpStr: transWorked = False resDetails['missingProjName'] = proj[3] # Check attributes in the projection are included for attrib in proj[4]: # The ':' prefix and ' ' suffix is to help check for exact name, # eg to catch the standard_parallel_1 and 2 issue. if (":"+attrib+" ") not in dumpStr: transWorked = False resDetails['missingAttrs'].append(attrib) # print "**Error for proj '%s': CF-1 attrib '%s' not found.**" % \ # (proj[0], attrib) # Now we check the required X and Y attributes are included (e.g. Rotated Pole # has special names required here. for coordVarStdName in proj[5]: if coordVarStdName not in dumpStr: transWorked = False resDetails['missingCoordVarStdNames'].append(coordVarStdName) #Final check use the cf-checker result_cf = netcdf_cf_check_file( projNc,'auto',True ) if result_cf == 'fail': resDetails['cfcheck_error'] = gdaltest.netcdf_cf_check_error transWorked = False return transWorked, resDetails ############################################################################### # Netcdf CF Tests ############################################################################### ############################################################################### #test copy and CF compliance for lat/lon (no datum, no GEOGCS) file, tif->nc->tif def netcdf_cf_1(): #setup netcdf and netcdf_cf environment netcdf_setup() netcdf_cf_setup() if gdaltest.netcdf_drv is None: return 'skip' #tst1 = gdaltest.GDALTest( 'NETCDF', 'trmm.tif', 1, 14 ) #result = tst1.testCreateCopy(check_gt=1, check_srs=1, new_filename='tmp/netcdf_cf_1.nc', delete_copy = 0) result = netcdf_test_copy( 'data/trmm.nc', 1, 14, 'tmp/netcdf_cf_1.nc' ) if result != 'fail': #tst2 = gdaltest.GDALTest( 'GTIFF', '../tmp/netcdf_cf_1.nc', 1, 14 ) #result = tst2.testCreateCopy(check_gt=1, check_srs=1, new_filename='tmp/netcdf_cf_1.tiff', delete_copy = 0) result = netcdf_test_copy( 'tmp/netcdf_cf_1.nc', 1, 14, 'tmp/netcdf_cf_1.tif', [], 'GTIFF' ) result_cf = 'success' if gdaltest.netcdf_cf_method is not None: result_cf = netcdf_cf_check_file( 'tmp/netcdf_18.nc','auto',False ) if result != 'fail' and result_cf != 'fail': return 'success' else: return 'fail' ############################################################################### #test copy and CF compliance for lat/lon (no datum, no GEOGCS) file, nc->nc def netcdf_cf_2(): if gdaltest.netcdf_drv is None: return 'skip' result = netcdf_test_copy( 'data/trmm.nc', 1, 14, 'tmp/netcdf_cf_2.nc' ) result_cf = 'success' if gdaltest.netcdf_cf_method is not None: result_cf = netcdf_cf_check_file( 'tmp/netcdf_cf_2.nc','auto',False ) if result != 'fail' and result_cf != 'fail': return 'success' else: return 'fail' ############################################################################### #test copy and CF compliance for lat/lon (W*S84) file, tif->nc->tif # note: this test fails in trunk (before r23246) def netcdf_cf_3(): if gdaltest.netcdf_drv is None: return 'skip' result = 'success' result_cf = 'success' result = netcdf_test_copy( 'data/trmm-wgs84.tif', 1, 14, 'tmp/netcdf_cf_3.nc' ) if result == 'success': #tst = gdaltest.GDALTest( 'GTIFF', '../tmp/netcdf_cf_3.nc', 1, 14 ) #result = tst.testCreateCopy(check_gt=1, check_srs=1, new_filename='tmp/netcdf_cf_3.tif', delete_copy = 0) result = netcdf_test_copy( 'tmp/netcdf_cf_3.nc', 1, 14, 'tmp/netcdf_cf_3.tif', [], 'GTIFF' ) result_cf = 'success' if gdaltest.netcdf_cf_method is not None: result_cf = netcdf_cf_check_file( 'tmp/netcdf_cf_3.nc','auto',False ) if result != 'fail' and result_cf != 'fail': return 'success' else: return 'fail' ############################################################################### #test support for various CF projections def netcdf_cf_4(): result = netcdf_cfproj_testcopy(netcdf_cfproj_tuples, 'melb-small.tif', netcdf_cfproj_int_fmt_maps, 'data', 'tmp', 'translate_results.txt') # result = netcdf_cfproj_testcopy(netcdf_cfproj_tuples1, 'melb-small.tif', \ # 'data', 'tmp', 'translate_results.txt') return result ############################################################################### #test support for PS variants (bug #2893) def netcdf_cf_5(): if gdaltest.netcdf_drv is None: return 'skip' ifiles = [ 'NETCDF:data/orog_CRCM1.nc:orog', 'NETCDF:data/orog_CRCM2.nc:orog' ] for ifile in ifiles: ds = gdal.Open( ifile ) prj = ds.GetProjection() sr = osr.SpatialReference( ) sr.ImportFromWkt( prj ) lat_origin = sr.GetProjParm( 'latitude_of_origin' ) if lat_origin != 60: gdaltest.post_reason( 'Latitude of origin in %s does not match expected: %f' % (ifile, lat_origin) ) return 'fail' return 'success' ############################################################################### gdaltest_list = [ netcdf_cf_1, netcdf_cf_2, netcdf_cf_3, netcdf_cf_4, netcdf_cf_5, None ] if __name__ == '__main__': gdaltest.setup_run( 'netcdf_cf' ) gdaltest.run_tests( gdaltest_list ) #make sure we cleanup gdaltest.clean_tmp() gdaltest.summarize()
[]
[]
[]
[]
[]
python
0
0
RecoLuminosity/LumiDB/python/matplotRender.py
''' Specs: -- We use matplotlib OO class level api, we do not use its high-level helper modules. Favor endured stability over simplicity. -- PNG as default batch file format -- we support http mode by sending string buf via meme type image/png. Sending a premade static plot to webserver is considered a uploading process instead of http dynamic graphical mode. ''' from __future__ import print_function from builtins import range import sys,os import numpy,datetime import matplotlib from RecoLuminosity.LumiDB import CommonUtil,lumiTime,csvReporter batchonly=False if 'DISPLAY' not in os.environ or not os.environ['DISPLAY']: batchonly=True matplotlib.use('Agg',warn=False) else: try: from RecoLuminosity.LumiDB import lumiQTWidget except ImportError: print('unable to import GUI backend, switch to batch only mode') matplotlib.use('Agg',warn=False) batchonly=True from matplotlib.backends.backend_agg import FigureCanvasAgg as CanvasBackend from matplotlib.figure import Figure from matplotlib.font_manager import fontManager,FontProperties matplotlib.rcParams['lines.linewidth']=1.5 matplotlib.rcParams['grid.linewidth']=0.2 matplotlib.rcParams['xtick.labelsize']=11 matplotlib.rcParams['ytick.labelsize']=11 matplotlib.rcParams['legend.fontsize']=10 matplotlib.rcParams['axes.labelsize']=11 matplotlib.rcParams['font.weight']=567 def guessInstLumiUnit(t): ''' input : largest total lumivalue output: (unitstring,denomitor) ''' unitstring='$\mu$b$^{-1}$s$^{-1}$' denomitor=1.0 if t>=1.0e3 and t<1.0e06: denomitor=1.0e3 unitstring='nb$^{-1}$s$^{-1}$' elif t>=1.0e6 and t<1.0e9: denomitor=1.0e6 unitstring='pb$^{-1}$s$^{-1}$' elif t>=1.0e9 and t<1.0e12: denomitor=1.0e9 unitstring='fb$^{-1}$s$^{-1}$' elif t>=1.0e12 and t<1.0e15: denomitor=1.0e12 unitstring='ab$^{-1}$s$^{-1}$' elif t<=1.0e-3 and t>1.0e-6: #left direction denomitor=1.0e-3 unitstring='mb$^{-1}$s$^{-1}$' elif t<=1.0e-6 and t>1.0e-9: denomitor=1.0e-6 unitstring='b$^{-1}$s$^{-1}$' elif t<=1.0e-9 and t>1.0e-12: denomitor=1.0e-9 unitstring='kb$^{-1}$s$^{-1}$' return (unitstring,denomitor) def guessLumiUnit(t): ''' input : largest total lumivalue output: (unitstring,denomitor) ''' unitstring='$\mu$b$^{-1}$' denomitor=1.0 if t>=1.0e3 and t<1.0e06: denomitor=1.0e3 unitstring='nb$^{-1}$' elif t>=1.0e6 and t<1.0e9: denomitor=1.0e6 unitstring='pb$^{-1}$' elif t>=1.0e9 and t<1.0e12: denomitor=1.0e9 unitstring='fb$^{-1}$' elif t>=1.0e12 and t<1.0e15: denomitor=1.0e12 unitstring='ab$^{-1}$' elif t<=1.0e-3 and t>1.0e-6: #left direction denomitor=1.0e-3 unitstring='mb$^{-1}$' elif t<=1.0e-6 and t>1.0e-9: denomitor=1.0e-6 unitstring='b$^{-1}$' elif t<=1.0e-9 and t>1.0e-12: denomitor=1.0e-9 unitstring='kb$^{-1}$' return (unitstring,denomitor) class matplotRender(): def __init__(self,fig): self.__fig=fig self.__canvas='' self.colormap={} self.colormap['Delivered']='r' self.colormap['Recorded']='b' self.colormap['Effective']='g' self.colormap['Max Inst']='r' def plotSumX_Run(self,rawdata={},resultlines=[],minRun=None,maxRun=None,nticks=6,yscale='linear',withannotation=False,referenceLabel='Delivered',labels=['Delivered','Recorded'],textoutput=None): ''' input: rawdata = {'Delivered':[(runnumber,lumiperrun),..],'Recorded':[(runnumber,lumiperrun),..]} resultlines = [[runnumber,dellumiperrun,reclumiperrun],[runnumber,dellumiperrun,reclumiperrun],] minRun : minimal runnumber required maxRun : max runnumber required yscale: linear,log or both withannotation: wheather the boundary points should be annotated referenceLabel: the one variable that decides the total unit and the plot x-axis range labels: labels of the variables to plot textoutput: text output file name. ''' ypoints={} ytotal={} for r in resultlines:#parse old text data runnumber=int(r[0]) if rawdata and runnumber in [t[0] for t in rawdata[referenceLabel]]:continue#use text input only if not in selected data if minRun and runnumber<minRun: continue if maxRun and runnumber>maxRun: continue for i,lab in enumerate(labels) : v=float(r[-(len(labels)-i)-1])#the values to plot are always the last n fields rawdata.setdefault(lab,[]).append((runnumber,v)) if not rawdata: print('[WARNING]: no data to plot , exit') return tot=sum([t[1] for t in rawdata[referenceLabel]]) (unitstring,denomitor)=guessLumiUnit(tot) csvreport=None rows=[] flat=[] for label,yvalues in rawdata.items(): yvalues.sort() flat.append([t[1] for t in yvalues]) ypoints[label]=[] ytotal[label]=0.0 lumivals=[t[1] for t in yvalues] for i,val in enumerate(lumivals): ypoints[label].append(sum(lumivals[0:i+1])/denomitor)#integrated lumi ytotal[label]=sum(lumivals)/denomitor xpoints=[t[0] for t in rawdata[referenceLabel]] ax=self.__fig.add_subplot(111) if yscale=='linear': ax.set_yscale('linear') elif yscale=='log': ax.set_yscale('log') else: raise RuntimeError('unsupported yscale '+yscale) ax.set_xlabel(r'Run',position=(0.95,0)) ax.set_ylabel(r'L '+unitstring,position=(0,0.9)) xticklabels=ax.get_xticklabels() for tx in xticklabels: tx.set_rotation(30) majorLocator=matplotlib.ticker.LinearLocator( nticks ) majorFormatter=matplotlib.ticker.FormatStrFormatter('%d') minorLocator=matplotlib.ticker.LinearLocator(numticks=4*nticks) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) ax.set_xbound(lower=xpoints[0],upper=xpoints[-1]) ax.grid(True) keylist=sorted(ypoints.keys()) keylist.insert(0,keylist.pop(keylist.index(referenceLabel)))#move refereceLabel to front from now on legendlist=[] head=['#Run'] textsummaryhead=['#TotalRun'] textsummaryline=['#'+str(len(xpoints))] for ylabel in keylist: cl='k' if ylabel in self.colormap: cl=self.colormap[ylabel] ax.plot(xpoints,ypoints[ylabel],label=ylabel,color=cl,drawstyle='steps') legendlist.append(ylabel+' '+'%.3f'%(ytotal[ylabel])+' '+unitstring) textsummaryhead.append('Total'+ylabel) textsummaryline.append('%.3f'%(ytotal[ylabel])+' '+unitstring) head.append(ylabel) if textoutput: csvreport=csvReporter.csvReporter(textoutput) csvreport.writeRow(head) allruns=[int(t[0]) for t in rawdata[referenceLabel]] flat.insert(0,allruns) rows=list(zip(*flat)) csvreport.writeRows([list(t) for t in rows]) csvreport.writeRow(textsummaryhead) csvreport.writeRow(textsummaryline) #font=FontProperties(size='medium',weight='demibold') #legend ax.legend(tuple(legendlist),loc='upper left') #adjust self.__fig.subplots_adjust(bottom=0.18,left=0.1) #annotations if withannotation: trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes) ax.text(xpoints[0],1.025,str(xpoints[0]),transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) ax.text(xpoints[-1],1.025,str(xpoints[-1]),transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) def plotSumX_Fill(self,rawdata={},resultlines=[],minFill=None,maxFill=None,nticks=6,yscale='linear',withannotation=False,referenceLabel='Delivered',labels=['Delivered','Recorded'],textoutput=None): ''' input: rawdata = {'Delivered':[(fill,runnumber,lumiperrun)],'Recorded':[(fill,runnumber,lumiperrun)]} resultlines = [[fillnumber,runnumber,dellumiperrun,reclumiperrun],[fillnumber,runnumber,dellumiperrun,reclumiperrun],] minFill : min fill to draw maxFill : max fill to draw yscale: linear,log or both withannotation: wheather the boundary points should be annotated textoutput: text output file name. ''' ytotal={} ypoints={} for r in resultlines: #parse old text data fillnum=int(r[0]) runnum=int(r[1]) if rawdata and (fillnum,runnum) in [(t[0],t[1]) for t in rawdata[referenceLabel]]:continue if minFill and fillnum<minFill:continue if maxFill and fillnum>maxFill:continue for i,lab in enumerate(labels) : v=float(r[-(len(labels)-i)])#the values to plot are always the last n fields rawdata.setdefault(lab,[]).append((fillnum,runnum,v)) #print 'fillrunDict ',fillrunDict if not rawdata: print('[WARNING]: no data, do nothing') return tot=sum([t[2] for t in rawdata[referenceLabel]]) beginfo='' endinfo='' (unitstring,denomitor)=guessLumiUnit(tot) csvreport=None rows=[] flat=[] for label,yvalues in rawdata.items(): yvalues.sort() flat.append([t[2] for t in yvalues]) ypoints[label]=[] ytotal[label]=0.0 lumivals=[t[2] for t in yvalues] for i,val in enumerate(lumivals): ypoints[label].append(sum(lumivals[0:i+1])/denomitor) ytotal[label]=sum(lumivals)/denomitor xpoints=[t[0] for t in rawdata[referenceLabel]]#after sort ax=self.__fig.add_subplot(111) ax.set_xlabel(r'LHC Fill Number',position=(0.84,0)) ax.set_ylabel(r'L '+unitstring,position=(0,0.9)) ax.set_xbound(lower=xpoints[0],upper=xpoints[-1]) if yscale=='linear': ax.set_yscale('linear') elif yscale=='log': ax.set_yscale('log') else: raise RuntimeError('unsupported yscale '+yscale) xticklabels=ax.get_xticklabels() majorLocator=matplotlib.ticker.LinearLocator( nticks ) majorFormatter=matplotlib.ticker.FormatStrFormatter('%d') #minorLocator=matplotlib.ticker.MultipleLocator(sampleinterval) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) #ax.xaxis.set_minor_locator(minorLocator) ax.grid(True) keylist=sorted(ypoints.keys()) keylist.insert(0,keylist.pop(keylist.index(referenceLabel)))#move refereceLabel to front from now on legendlist=[] head=['#fill','run'] textsummaryhead=['#TotalFill'] textsummaryline=['#'+str(len(xpoints))] for ylabel in keylist: cl='k' if ylabel in self.colormap: cl=self.colormap[ylabel] ax.plot(xpoints,ypoints[ylabel],label=ylabel,color=cl,drawstyle='steps') legendlist.append(ylabel+' '+'%.3f'%(ytotal[ylabel])+' '+unitstring) textsummaryhead.append('Total'+ylabel) textsummaryline.append('%.3f'%(ytotal[ylabel])+' '+unitstring) head.append(ylabel) if textoutput: csvreport=csvReporter.csvReporter(textoutput) allfills=[int(t[0]) for t in rawdata[referenceLabel]] allruns=[int(t[1]) for t in rawdata[referenceLabel]] flat.insert(0,allfills) flat.insert(1,allruns) rows=list(zip(*flat)) csvreport.writeRow(head) csvreport.writeRows([list(t) for t in rows]) csvreport.writeRow(textsummaryhead) csvreport.writeRow(textsummaryline) #font=FontProperties(size='medium',weight='demibold') #annotations if withannotation: trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes) ax.text(xpoints[0],1.025,beginfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) ax.text(xpoints[-1],1.025,endinfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) #legend ax.legend(tuple(legendlist),loc='upper left') #adjust self.__fig.subplots_adjust(bottom=0.1,left=0.1) def plotSumX_Time(self,rawdata={},resultlines=[],minTime=None,maxTime=None,nticks=6,yscale='linear',withannotation=False,referenceLabel='Delivered',labels=['Delivered','Recorded'],textoutput=None): ''' input: rawdata = {'Delivered':[(runnumber,starttimestamp,stoptimestamp,lumiperrun)],'Recorded':[(runnumber,starttimestamp,stoptimestamp,lumiperrun)]} resultlines = [[runnumber,starttimestampStr,stoptimestampStr,dellumiperrun,reclumiperrun],[runnumber,starttimestampStr,stoptimestampStr,dellumiperrun,reclumiperrun],] minTime (python DateTime) : min *begin* time to draw: format %m/%d/%y %H:%M:%S maxTime (python DateTime): max *begin* time to draw %m/%d/%y %H:%M:%S yscale: linear,log or both withannotation: wheather the boundary points should be annotated referenceLabel: the one variable that decides the total unit and the plot x-axis range labels: labels of the variables to plot ''' xpoints=[] ypoints={} ytotal={} lut=lumiTime.lumiTime() if not minTime: minTime='03/01/10 00:00:00' minTime=lut.StrToDatetime(minTime,customfm='%m/%d/%y %H:%M:%S') if not maxTime: maxTime=datetime.datetime.utcnow() else: maxTime=lut.StrToDatetime(maxTime,customfm='%m/%d/%y %H:%M:%S') for r in resultlines: runnumber=int(r[0]) starttimeStr=r[1].split('.')[0] starttime=lut.StrToDatetime(starttimeStr,customfm='%Y-%m-%d %H:%M:%S') stoptimeStr=r[2].split('.')[0] stoptime=lut.StrToDatetime(stoptimeStr,customfm='%Y-%m-%d %H:%M:%S') if rawdata and runnumber in [t[0] for t in rawdata[referenceLabel]]:continue if starttime<minTime:continue if starttime>maxTime:continue for i,lab in enumerate(labels): v=float(r[-(len(labels)-i)]) rawdata.setdefault(lab,[]).append((runnumber,starttime,stoptime,v)) if not rawdata: print('[WARNING]: no data, do nothing') return tot=sum([t[3] for t in rawdata[referenceLabel]]) (unitstring,denomitor)=guessLumiUnit(tot) csvreport=None rows=[] flat=[] for label,yvalues in rawdata.items(): yvalues.sort() flat.append([t[3] for t in yvalues]) if label==referenceLabel: minTime=yvalues[0][1] maxTime=yvalues[-1][1] ypoints[label]=[] lumivals=[t[3] for t in yvalues] for i,val in enumerate(lumivals): ypoints[label].append(sum(lumivals[0:i+1])/denomitor) ytotal[label]=sum(lumivals)/denomitor xpoints=[matplotlib.dates.date2num(t[1]) for t in rawdata[referenceLabel]] ax=self.__fig.add_subplot(111) ax.set_yscale(yscale) yearStrMin=minTime.strftime('%Y') yearStrMax=maxTime.strftime('%Y') if yearStrMin==yearStrMax: dateFmt=matplotlib.dates.DateFormatter('%d/%m') else: dateFmt=matplotlib.dates.DateFormatter('%d/%m/%y') majorLoc=matplotlib.ticker.LinearLocator(numticks=nticks) ax.xaxis.set_major_locator(majorLoc) minorLoc=matplotlib.ticker.LinearLocator(numticks=nticks*4) ax.xaxis.set_major_formatter(dateFmt) ax.set_xlabel(r'Date',position=(0.84,0)) ax.set_ylabel(r'L '+unitstring,position=(0,0.9)) ax.xaxis.set_minor_locator(minorLoc) ax.set_xbound(lower=xpoints[0],upper=xpoints[-1]) xticklabels=ax.get_xticklabels() for tx in xticklabels: tx.set_horizontalalignment('left') ax.grid(True) keylist=sorted(ypoints.keys()) keylist.insert(0,keylist.pop(keylist.index(referenceLabel)))#move refereceLabel to front from now on legendlist=[] head=['#Run','StartTime','StopTime'] textsummaryhead=['#TotalRun'] textsummaryline=['#'+str(len(xpoints))] for ylabel in keylist: cl='k' if ylabel in self.colormap: cl=self.colormap[ylabel] ax.plot(xpoints,ypoints[ylabel],label=ylabel,color=cl,drawstyle='steps') legendlist.append(ylabel+' '+'%.3f'%(ytotal[ylabel])+' '+unitstring) textsummaryhead.append('Total'+ylabel) textsummaryline.append('%.3f'%(ytotal[ylabel])+' '+unitstring) head.append(ylabel) if textoutput: csvreport=csvReporter.csvReporter(textoutput) csvreport.writeRow(head) allruns=[int(t[0]) for t in rawdata[referenceLabel]] allstarts=[ lut.DatetimeToStr(t[1],customfm='%Y-%m-%d %H:%M:%S') for t in rawdata[referenceLabel] ] allstops=[ lut.DatetimeToStr(t[2],customfm='%Y-%m-%d %H:%M:%S') for t in rawdata[referenceLabel] ] flat.insert(0,allruns) flat.insert(1,allstarts) flat.insert(2,allstops) rows=list(zip(*flat)) csvreport.writeRows([list(t) for t in rows]) csvreport.writeRow(textsummaryhead) csvreport.writeRow(textsummaryline) #annotations trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes) #print 'run boundary ',runs[0],runs[-1] #print 'xpoints boundary ',xpoints[0],xpoints[-1] #annotation if withannotation: runs=[t[0] for t in rawdata[referenceLabel]] ax.text(xpoints[0],1.025,str(runs[0]),transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) ax.text(xpoints[-1],1.025,str(runs[-1]),transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) if yearStrMin==yearStrMax: firsttimeStr=rawdata[referenceLabel][1][1].strftime('%b %d %H:%M') #time range(start) in the title is the first run beg time lasttimeStr=rawdata[referenceLabel][-1][2].strftime('%b %d %H:%M') #time range(stop) in the tile is the last run stop time #firstimeStr=minTime.strftime('%b %d %H:%M') #lasttimeStr=maxTime.strftime('%b %d %H:%M') #ax.set_title('CMS Total Integrated Luminosity '+yearStrMin+' ('+firstimeStr+' - '+lasttimeStr+' UTC)',size='small',family='fantasy') ax.set_title('CMS Total Integrated Luminosity '+yearStrMin+' ('+firsttimeStr+' - '+lasttimeStr+' UTC)',size='small') else: #ax.set_title('CMS Total Integrated Luminosity '+yearStrMin+'-'+yearStrMax,size='small',family='fantasy') ax.set_title('CMS Total Integrated Luminosity '+yearStrMin+'-'+yearStrMax,size='small') ax.legend(tuple(legendlist),loc='upper left') ax.autoscale_view(tight=True,scalex=True,scaley=False) self.__fig.autofmt_xdate(bottom=0.18,rotation=15,ha='right') self.__fig.subplots_adjust(bottom=0.2,left=0.15) def plotPerdayX_Time(self,rawdata={},resultlines=[],minTime=None,maxTime=None,nticks=6,yscale='linear',withannotation=False,referenceLabel='Delivered',labels=['Delivered','Recorded'],textoutput=None): ''' Input: rawdata={'Delivered':[(day,begrun:ls,endrun:ls,lumi)],'Recorded':[(dayofyear,begrun:ls,endrun:ls,lumi)]} resultlines=[[day,begrun:ls,endrun:ls,deliveredperday,recordedperday],[]] minTime (python DateTime) : min *begin* time to draw: format %m/%d/%y %H:%M:%S maxTime (python DateTime): max *begin* time to draw %m/%d/%y %H:%M:%S withannotation: wheather the boundary points should be annotated referenceLabel: the one variable that decides the total unit and the plot x-axis range labels: labels of the variables to plot ''' xpoints=[] ypoints={} ymax={} lut=lumiTime.lumiTime() if not minTime: minTime='03/01/10 00:00:00' minTime=lut.StrToDatetime(minTime,customfm='%m/%d/%y %H:%M:%S') if not maxTime: maxTime=datetime.datetime.utcnow() else: maxTime=lut.StrToDatetime(maxTime,customfm='%m/%d/%y %H:%M:%S') for r in resultlines: day=int(r[0]) begrunls=r[1] endrunls=r[2] #[begrun,begls]=[int(s) for s in r[1].split(':')] if rawdata and day in [t[0] for t in rawdata[referenceLabel]]:continue if day < minTime.date().toordinal():continue if day > maxTime.date().toordinal():continue for i,lab in enumerate(labels): v=float(r[-(len(labels)-i)-1]) rawdata.setdefault(lab,[]).append((day,begrunls,endrunls,v)) if not rawdata: print('[WARNING]: no data, do nothing') return maxlum=max([t[3] for t in rawdata[referenceLabel]]) minlum=min([t[3] for t in rawdata[referenceLabel] if t[3]>0]) #used only for log scale, fin the non-zero bottom (unitstring,denomitor)=guessLumiUnit(maxlum) csvreport=None rows=[] flat=[] MinDay=minTime.date().toordinal() MaxDay=maxTime.date().toordinal() fulldays=list(range(MinDay,MaxDay+1)) allstarts=[] allstops=[] for label,yvalues in rawdata.items(): yvalues.sort() flat.append([t[3] for t in yvalues]) alldays=[t[0] for t in yvalues] alldates=[str(datetime.date.fromordinal(t)) for t in alldays] ypoints[label]=[] lumivals=[t[3] for t in yvalues] for d in fulldays: if not d in alldays: ypoints[label].append(0.0) else: thisdaylumi=[t[3] for t in yvalues if t[0]==d][0] if yscale=='log': if thisdaylumi<minlum: thisdaylumi=minlum/denomitor else: thisdaylumi=thisdaylumi/denomitor else: thisdaylumi=thisdaylumi/denomitor ypoints[label].append(thisdaylumi) ymax[label]=max(lumivals)/denomitor xpoints=fulldays if textoutput: csvreport=csvReporter.csvReporter(textoutput) head=['#day','begrunls','endrunls','delivered','recorded','date'] csvreport.writeRow(head) flat.insert(0,alldays) allstarts=[ t[1] for t in rawdata[referenceLabel]] allstops=[ t[2] for t in rawdata[referenceLabel]] #print 'allstarts ',allstarts flat.insert(1,allstarts) flat.insert(2,allstops) flat.append(alldates) rows=list(zip(*flat)) csvreport.writeRows([list(t) for t in rows]) yearStrMin=minTime.strftime('%Y') yearStrMax=maxTime.strftime('%Y') if yearStrMin==yearStrMax: dateFmt=matplotlib.dates.DateFormatter('%d/%m') else: dateFmt=matplotlib.dates.DateFormatter('%d/%m/%y') ax=self.__fig.add_subplot(111) if yscale=='linear': ax.set_yscale('linear') elif yscale=='log': ax.set_yscale('log') else: raise RuntimeError('unsupported yscale '+yscale) majorLoc=matplotlib.ticker.LinearLocator(numticks=nticks) minorLoc=matplotlib.ticker.LinearLocator(numticks=nticks*4) ax.xaxis.set_major_formatter(dateFmt) ax.set_xlabel(r'Date',position=(0.84,0)) ax.xaxis.set_major_locator(majorLoc) ax.xaxis.set_minor_locator(minorLoc) xticklabels=ax.get_xticklabels() for tx in xticklabels: tx.set_horizontalalignment('right') ax.grid(True) legendlist=[] ax.set_ylabel(r'L '+unitstring,position=(0,0.9)) textsummaryhead=['#TotalRunningDays'] textsummaryline=['#'+str(len(alldays))] for ylabel in labels: cl='k' if ylabel in self.colormap: cl=self.colormap[ylabel] ax.plot(xpoints,ypoints[ylabel],label=ylabel,color=cl,drawstyle='steps') legendlist.append(ylabel+' Max '+'%.3f'%(ymax[ylabel])+' '+unitstring) textsummaryhead.append('Max'+ylabel) textsummaryline.append('%.3f'%(ymax[ylabel])+' '+unitstring) if textoutput: csvreport.writeRow(textsummaryhead) csvreport.writeRow(textsummaryline) ax.legend(tuple(legendlist),loc='upper left') ax.set_xbound(lower=matplotlib.dates.date2num(minTime),upper=matplotlib.dates.date2num(maxTime)) #if withannotation: # begtime=boundaryInfo[0][0] # beginfo=boundaryInfo[0][1] # endtime=boundaryInfo[1][0] # endinfo=boundaryInfo[1][1] # #annotations # trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes) # ax.text(matplotlib.dates.date2num(begtime),1.025,beginfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) # ax.text(matplotlib.dates.date2num(endtime),1.025,endinfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) firstday=datetime.date.fromordinal(rawdata[referenceLabel][0][0]) lastday=datetime.date.fromordinal(rawdata[referenceLabel][-1][0]) firstdayStr=firstday.strftime('%Y %b %d') lastdayStr=lastday.strftime('%Y %b %d') ax.set_title('CMS Integrated Luminosity/Day ('+firstdayStr+' - '+lastdayStr+')',size='small') #ax.autoscale(tight=True) ax.autoscale_view(tight=True,scalex=True,scaley=False) #ax.set_xmargin(0.015) self.__fig.autofmt_xdate(bottom=0.18,rotation=15,ha='right') self.__fig.subplots_adjust(bottom=0.2,left=0.15) def plotPeakPerday_Time(self,rawdata={},resultlines=[],minTime=None,maxTime=None,nticks=6,withannotation=False,yscale='linear',referenceLabel='Delivered',labels=['Delivered'],textoutput=None): ''' THIS PLOT IS DELIVERED ONLY Input: rawdata={'Delivered':[(day,run,ls,instlumi)]} resultlines=[[day,run,ls,maxinstlum],[]] minTime (python DateTime) : min *begin* time to draw: format %m/%d/%y %H:%M:%S maxTime (python DateTime): max *begin* time to draw %m/%d/%y %H:%M:%S withannotation: wheather the boundary points should be annotated referenceLabel: the one variable that decides the total unit and the plot x-axis range labels: labels of the variables to plot ''' xpoints=[] ypoints={} legendlist=[] maxinfo='' ymax={} lut=lumiTime.lumiTime() if not minTime: minTime='03/01/10 00:00:00' minTime=lut.StrToDatetime(minTime,customfm='%m/%d/%y %H:%M:%S') if not maxTime: maxTime=datetime.datetime.utcnow() else: maxTime=lut.StrToDatetime(maxTime,customfm='%m/%d/%y %H:%M:%S') for r in resultlines: day=int(r[0]) runnumber=int(r[1]) lsnum=int(r[2].split('.')[0]) if rawdata and day in [int(t[0]) for t in rawdata[referenceLabel]]:continue if day < minTime.date().toordinal():continue if day > maxTime.date().toordinal():continue for i,lab in enumerate(labels): v=float(r[-(len(labels)-i)-1]) rawdata.setdefault(lab,[]).append((day,runnumber,lsnum,v)) if not rawdata: print('[WARNING]: no data, do nothing') return maxlum=max([t[3] for t in rawdata[referenceLabel]]) minlum=min([t[3] for t in rawdata[referenceLabel] if t[3]>0]) #used only for log scale, fin the non-zero bottom (unitstring,denomitor)=guessInstLumiUnit(maxlum) csvreport=None rows=[] flat=[] MinDay=minTime.date().toordinal() MaxDay=maxTime.date().toordinal() fulldays=list(range(MinDay,MaxDay+1)) for label in rawdata.keys(): yvalues=sorted(rawdata[label]) alldays=[t[0] for t in yvalues] alldates=[str(datetime.date.fromordinal(t)) for t in alldays] ypoints[label]=[] lumivals=[t[3] for t in yvalues] flat.append(lumivals) for d in fulldays: if not d in alldays: ypoints[label].append(0.0) else: thisdaylumi=[t[3] for t in yvalues if t[0]==d][0] if yscale=='log': if thisdaylumi<minlum: thisdaylumi=minlum/denomitor else: thisdaylumi=thisdaylumi/denomitor else: thisdaylumi=thisdaylumi/denomitor ypoints[label].append(thisdaylumi) ymax[label]=max(lumivals)/denomitor 'ymax ',max(lumivals) xpoints=fulldays if textoutput: csvreport=csvReporter.csvReporter(textoutput) head=['#day','run','lsnum','maxinstlumi','date'] csvreport.writeRow(head) flat.insert(0,alldays) allruns=[ t[1] for t in rawdata[referenceLabel]] allls=[ t[2] for t in rawdata[referenceLabel]] flat.insert(1,allruns) flat.insert(2,allls) flat.append(alldates) rows=list(zip(*flat)) csvreport.writeRows([list(t) for t in rows]) yearStrMin=minTime.strftime('%Y') yearStrMax=maxTime.strftime('%Y') if yearStrMin==yearStrMax: dateFmt=matplotlib.dates.DateFormatter('%d/%m') else: dateFmt=matplotlib.dates.DateFormatter('%d/%m/%y') ax=self.__fig.add_subplot(111) if yscale=='linear': ax.set_yscale('linear') elif yscale=='log': ax.set_yscale('log') else: raise RuntimeError('unsupported yscale '+yscale) majorLoc=matplotlib.ticker.LinearLocator(numticks=nticks) minorLoc=matplotlib.ticker.LinearLocator(numticks=nticks*4) ax.xaxis.set_major_formatter(dateFmt) ax.set_xlabel(r'Date',position=(0.84,0)) ax.set_ylabel(r'L '+unitstring,position=(0,0.9)) ax.xaxis.set_major_locator(majorLoc) ax.xaxis.set_minor_locator(minorLoc) xticklabels=ax.get_xticklabels() for tx in xticklabels: tx.set_horizontalalignment('right') ax.grid(True) cl=self.colormap['Max Inst'] textsummaryhead=['#TotalRunningDays'] textsummaryline=['#'+str(len(alldays))] for ylabel in labels: cl='k' if ylabel in self.colormap: cl=self.colormap[ylabel] ax.plot(xpoints,ypoints[ylabel],label='Max Inst',color=cl,drawstyle='steps') legendlist.append('Max Inst %.3f'%(ymax[ylabel])+' '+unitstring) textsummaryhead.append('Max Inst'+ylabel) textsummaryline.append('%.3f'%(ymax[ylabel])+' '+unitstring) if textoutput: csvreport.writeRow(textsummaryhead) csvreport.writeRow(textsummaryline) ax.legend(tuple(legendlist),loc='upper left') ax.set_xbound(lower=matplotlib.dates.date2num(minTime),upper=matplotlib.dates.date2num(maxTime)) if withannotation: #annotations trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes) ax.text(xpoints[0],1.025,beginfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) ax.text(xpoints[-1],1.025,endinfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) ax.annotate(maxinfo,xy=(xmax,ymax),xycoords='data',xytext=(0,13),textcoords='offset points',arrowprops=dict(facecolor='green',shrink=0.05),size='x-small',horizontalalignment='center',color='green',bbox=dict(facecolor='white')) firstday=datetime.date.fromordinal(rawdata[referenceLabel][0][0]) lastday=datetime.date.fromordinal(rawdata[referenceLabel][-1][0]) firstdayStr=firstday.strftime('%Y %b %d') lastdayStr=lastday.strftime('%Y %b %d') ax.set_title('CMS Peak Luminosity/Day ('+firstdayStr+' - '+lastdayStr+')',size='small') #ax.autoscale(tight=True) ax.autoscale_view(tight=True,scalex=True,scaley=False) #ax.set_xmargin(0.015) self.__fig.autofmt_xdate(bottom=0.18,rotation=15,ha='right') self.__fig.subplots_adjust(bottom=0.2,left=0.15) def plotInst_RunLS(self,rawxdata,rawydata,nticks=6,textoutput=None): ''' Input: rawxdata [run,fill,starttime,stoptime,totalls,ncmsls] rawydata {label:[lumi]} ''' lslength=23.357 lut=lumiTime.lumiTime() runnum=rawxdata[0] fill=rawxdata[1] starttime=lut.DatetimeToStr(rawxdata[2],customfm='%m/%d/%y %H:%M:%S') stoptime=lut.DatetimeToStr(rawxdata[3],customfm='%m/%d/%y %H:%M:%S') totalls=rawxdata[-2] ncmsls=rawxdata[-1] peakinst=max(rawydata['Delivered'])/lslength totaldelivered=sum(rawydata['Delivered']) totalrecorded=sum(rawydata['Recorded']) xpoints=list(range(1,totalls+1)) #print len(xpoints) ypoints={} ymax={} for ylabel,yvalue in rawydata.items(): ypoints[ylabel]=[y/lslength for y in yvalue] ymax[ylabel]=max(yvalue)/lslength left=0.15 width=0.7 bottom=0.1 height=0.65 bottom_h=bottom+height rect_scatter=[left,bottom,width,height] rect_table=[left,bottom_h,width,0.25] nullfmt=matplotlib.ticker.NullFormatter() nullloc=matplotlib.ticker.NullLocator() axtab=self.__fig.add_axes(rect_table,frameon=False) axtab.set_axis_off() axtab.xaxis.set_major_formatter(nullfmt) axtab.yaxis.set_major_formatter(nullfmt) axtab.xaxis.set_major_locator(nullloc) axtab.yaxis.set_major_locator(nullloc) ax=self.__fig.add_axes(rect_scatter) majorLoc=matplotlib.ticker.LinearLocator(numticks=nticks) minorLoc=matplotlib.ticker.LinearLocator(numticks=nticks*4) ax.set_xlabel(r'LS',position=(0.96,0)) ax.set_ylabel(r'L $\mu$b$^{-1}$s$^{-1}$',position=(0,0.9)) ax.xaxis.set_major_locator(majorLoc) ax.xaxis.set_minor_locator(minorLoc) ax.set_xbound(lower=xpoints[0],upper=xpoints[-1]) xticklabels=ax.get_xticklabels() for tx in xticklabels: tx.set_horizontalalignment('right') ax.grid(True) keylist=sorted(ypoints.keys()) legendlist=[] for ylabel in keylist: cl='k' if ylabel in self.colormap: cl=self.colormap[ylabel] ax.plot(xpoints,ypoints[ylabel],'.',label=ylabel,color=cl) legendlist.append(ylabel) #ax.axhline(0,color='green',linewidth=0.2) ax.axvline(xpoints[ncmsls-1],color='green',linewidth=0.2) (unitstring,denomitor)=guessLumiUnit(totaldelivered) colLabels=('run','fill','max inst(/$\mu$b/s)','delivered('+unitstring+')','recorded('+unitstring+')') cellText=[[str(runnum),str(fill),'%.3f'%(peakinst),'%.3f'%(totaldelivered/denomitor),'%.3f'%(totalrecorded/denomitor)]] sumtable=axtab.table(cellText=cellText,colLabels=colLabels,colWidths=[0.12,0.1,0.27,0.27,0.27],cellLoc='center',loc='center') trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes) axtab.add_table(sumtable) ax.text(xpoints[0],1.02,starttime[0:17],transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) ax.text(xpoints[ncmsls-1],1.02,stoptime[0:17],transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white')) ax.legend(tuple(legendlist),loc='upper right',numpoints=1) def drawHTTPstring(self): self.__canvas=CanvasBackend(self.__fig) cherrypy.response.headers['Content-Type']='image/png' buf=StringIO() self.__canvas.print_png(buf) return buf.getvalue() def drawPNG(self,filename): self.__canvas=CanvasBackend(self.__fig) self.__canvas.print_figure(filename) def drawInteractive(self): if batchonly: print('interactive mode is not available for your setup, exit') sys.exit() aw=lumiQTWidget.ApplicationWindow(fig=self.__fig) aw.show() aw.destroy() if __name__=='__main__': import csv print('=====testing plotSumX_Run======') f=open('/afs/cern.ch/cms/lumi/www/plots/operation/totallumivsrun-2011.csv','r') reader=csv.reader(f,delimiter=',') resultlines=[] for row in reader: if not row[0].isdigit():continue resultlines.append(row) #print resultlines fig=Figure(figsize=(7.2,5.4),dpi=120) m=matplotRender(fig) m.plotSumX_Run(rawdata={},resultlines=resultlines,minRun=None,maxRun=None,nticks=6,yscale='linear',withannotation=False) #m.drawPNG('totallumivsrun-2011test.png') m.drawInteractive() print('DONE') ''' print '=====testing plotSumX_Fill======' f=open('/afs/cern.ch/cms/lumi/www/plots/operation/totallumivsfill-2011.csv','r') reader=csv.reader(f,delimiter=',') resultlines=[] for row in reader: if not row[0].isdigit():continue resultlines.append(row) #print resultlines fig=Figure(figsize=(7.2,5.4),dpi=120) m=matplotRender(fig) m.plotSumX_Fill(rawdata={},resultlines=resultlines,minFill=None,maxFill=None,nticks=6,yscale='linear',withannotation=True) m.drawPNG('totallumivsfill-2011test.png') print 'DONE' print '=====testing plotSumX_Time======' f=open('/afs/cern.ch/cms/lumi/www/publicplots/totallumivstime-2011.csv','r') reader=csv.reader(f,delimiter=',') resultlines=[] for row in reader: if not row[0].isdigit():continue resultlines.append(row) #print resultlines fig=Figure(figsize=(7.25,5.4),dpi=120) m=matplotRender(fig) m.plotSumX_Time(rawdata={},resultlines=resultlines,minTime="03/14/11 09:00:00",maxTime=None,nticks=6,yscale='linear',withannotation=False) m.drawPNG('totallumivstime-2011test.png') print 'DONE' print '=====testing plotPerdayX_Time======' f=open('/afs/cern.ch/cms/lumi/www/publicplots/lumiperday-2011.csv','r') reader=csv.reader(f,delimiter=',') resultlines=[] for row in reader: if not row[0].isdigit():continue resultlines.append(row) #print resultlines fig=Figure(figsize=(7.25,5.4),dpi=120) m=matplotRender(fig) m.plotPerdayX_Time(rawdata={},resultlines=resultlines,minTime="03/14/11 09:00:00",maxTime=None,nticks=6,yscale='linear',withannotation=False) m.drawPNG('lumiperday-2011test.png') print 'DONE' print '=====testing plotPeakPerday_Time======' f=open('/afs/cern.ch/cms/lumi/www/publicplots/lumipeak-2011.csv','r') reader=csv.reader(f,delimiter=',') resultlines=[] for row in reader: if not row[0].isdigit():continue resultlines.append(row) #print resultlines fig=Figure(figsize=(7.25,5.4),dpi=120) m=matplotRender(fig) m.plotPeakPerday_Time(rawdata={},resultlines=resultlines,minTime="03/14/11 09:00:00",maxTime=None,nticks=6,yscale='linear',withannotation=False) m.drawPNG('lumipeak-2011test.png') print 'DONE' '''
[]
[]
[ "DISPLAY" ]
[]
["DISPLAY"]
python
1
0
ssh/example_test.go
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh_test import ( "bufio" "bytes" "fmt" "io/ioutil" "log" "net" "net/http" "os" "path/filepath" "strings" "github.com/ProtonMail/go-crypto/ssh" "github.com/ProtonMail/go-crypto/ssh/terminal" ) func ExampleNewServerConn() { // Public key authentication is done by comparing // the public key of a received connection // with the entries in the authorized_keys file. authorizedKeysBytes, err := ioutil.ReadFile("authorized_keys") if err != nil { log.Fatalf("Failed to load authorized_keys, err: %v", err) } authorizedKeysMap := map[string]bool{} for len(authorizedKeysBytes) > 0 { pubKey, _, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes) if err != nil { log.Fatal(err) } authorizedKeysMap[string(pubKey.Marshal())] = true authorizedKeysBytes = rest } // An SSH server is represented by a ServerConfig, which holds // certificate details and handles authentication of ServerConns. config := &ssh.ServerConfig{ // Remove to disable password auth. PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { // Should use constant-time compare (or better, salt+hash) in // a production setting. if c.User() == "testuser" && string(pass) == "tiger" { return nil, nil } return nil, fmt.Errorf("password rejected for %q", c.User()) }, // Remove to disable public key auth. PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) { if authorizedKeysMap[string(pubKey.Marshal())] { return &ssh.Permissions{ // Record the public key used for authentication. Extensions: map[string]string{ "pubkey-fp": ssh.FingerprintSHA256(pubKey), }, }, nil } return nil, fmt.Errorf("unknown public key for %q", c.User()) }, } privateBytes, err := ioutil.ReadFile("id_rsa") if err != nil { log.Fatal("Failed to load private key: ", err) } private, err := ssh.ParsePrivateKey(privateBytes) if err != nil { log.Fatal("Failed to parse private key: ", err) } config.AddHostKey(private) // Once a ServerConfig has been configured, connections can be // accepted. listener, err := net.Listen("tcp", "0.0.0.0:2022") if err != nil { log.Fatal("failed to listen for connection: ", err) } nConn, err := listener.Accept() if err != nil { log.Fatal("failed to accept incoming connection: ", err) } // Before use, a handshake must be performed on the incoming // net.Conn. conn, chans, reqs, err := ssh.NewServerConn(nConn, config) if err != nil { log.Fatal("failed to handshake: ", err) } log.Printf("logged in with key %s", conn.Permissions.Extensions["pubkey-fp"]) // The incoming Request channel must be serviced. go ssh.DiscardRequests(reqs) // Service the incoming Channel channel. for newChannel := range chans { // Channels have a type, depending on the application level // protocol intended. In the case of a shell, the type is // "session" and ServerShell may be used to present a simple // terminal interface. if newChannel.ChannelType() != "session" { newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") continue } channel, requests, err := newChannel.Accept() if err != nil { log.Fatalf("Could not accept channel: %v", err) } // Sessions have out-of-band requests such as "shell", // "pty-req" and "env". Here we handle only the // "shell" request. go func(in <-chan *ssh.Request) { for req := range in { req.Reply(req.Type == "shell", nil) } }(requests) term := terminal.NewTerminal(channel, "> ") go func() { defer channel.Close() for { line, err := term.ReadLine() if err != nil { break } fmt.Println(line) } }() } } func ExampleClientConfig_HostKeyCallback() { // Every client must provide a host key check. Here is a // simple-minded parse of OpenSSH's known_hosts file host := "hostname" file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts")) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) var hostKey ssh.PublicKey for scanner.Scan() { fields := strings.Split(scanner.Text(), " ") if len(fields) != 3 { continue } if strings.Contains(fields[0], host) { var err error hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes()) if err != nil { log.Fatalf("error parsing %q: %v", fields[2], err) } break } } if hostKey == nil { log.Fatalf("no hostkey for %s", host) } config := ssh.ClientConfig{ User: os.Getenv("USER"), HostKeyCallback: ssh.FixedHostKey(hostKey), } _, err = ssh.Dial("tcp", host+":22", &config) log.Println(err) } func ExampleDial() { var hostKey ssh.PublicKey // An SSH client is represented with a ClientConn. // // To authenticate with the remote server you must pass at least one // implementation of AuthMethod via the Auth field in ClientConfig, // and provide a HostKeyCallback. config := &ssh.ClientConfig{ User: "username", Auth: []ssh.AuthMethod{ ssh.Password("yourpassword"), }, HostKeyCallback: ssh.FixedHostKey(hostKey), } client, err := ssh.Dial("tcp", "yourserver.com:22", config) if err != nil { log.Fatal("Failed to dial: ", err) } defer client.Close() // Each ClientConn can support multiple interactive sessions, // represented by a Session. session, err := client.NewSession() if err != nil { log.Fatal("Failed to create session: ", err) } defer session.Close() // Once a Session is created, you can execute a single command on // the remote side using the Run method. var b bytes.Buffer session.Stdout = &b if err := session.Run("/usr/bin/whoami"); err != nil { log.Fatal("Failed to run: " + err.Error()) } fmt.Println(b.String()) } func ExamplePublicKeys() { var hostKey ssh.PublicKey // A public key may be used to authenticate against the remote // server by using an unencrypted PEM-encoded private key file. // // If you have an encrypted private key, the crypto/x509 package // can be used to decrypt it. key, err := ioutil.ReadFile("/home/user/.ssh/id_rsa") if err != nil { log.Fatalf("unable to read private key: %v", err) } // Create the Signer for this private key. signer, err := ssh.ParsePrivateKey(key) if err != nil { log.Fatalf("unable to parse private key: %v", err) } config := &ssh.ClientConfig{ User: "user", Auth: []ssh.AuthMethod{ // Use the PublicKeys method for remote authentication. ssh.PublicKeys(signer), }, HostKeyCallback: ssh.FixedHostKey(hostKey), } // Connect to the remote server and perform the SSH handshake. client, err := ssh.Dial("tcp", "host.com:22", config) if err != nil { log.Fatalf("unable to connect: %v", err) } defer client.Close() } func ExampleClient_Listen() { var hostKey ssh.PublicKey config := &ssh.ClientConfig{ User: "username", Auth: []ssh.AuthMethod{ ssh.Password("password"), }, HostKeyCallback: ssh.FixedHostKey(hostKey), } // Dial your ssh server. conn, err := ssh.Dial("tcp", "localhost:22", config) if err != nil { log.Fatal("unable to connect: ", err) } defer conn.Close() // Request the remote side to open port 8080 on all interfaces. l, err := conn.Listen("tcp", "0.0.0.0:8080") if err != nil { log.Fatal("unable to register tcp forward: ", err) } defer l.Close() // Serve HTTP with your SSH server acting as a reverse proxy. http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { fmt.Fprintf(resp, "Hello world!\n") })) } func ExampleSession_RequestPty() { var hostKey ssh.PublicKey // Create client config config := &ssh.ClientConfig{ User: "username", Auth: []ssh.AuthMethod{ ssh.Password("password"), }, HostKeyCallback: ssh.FixedHostKey(hostKey), } // Connect to ssh server conn, err := ssh.Dial("tcp", "localhost:22", config) if err != nil { log.Fatal("unable to connect: ", err) } defer conn.Close() // Create a session session, err := conn.NewSession() if err != nil { log.Fatal("unable to create session: ", err) } defer session.Close() // Set up terminal modes modes := ssh.TerminalModes{ ssh.ECHO: 0, // disable echoing ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud } // Request pseudo terminal if err := session.RequestPty("xterm", 40, 80, modes); err != nil { log.Fatal("request for pseudo terminal failed: ", err) } // Start remote shell if err := session.Shell(); err != nil { log.Fatal("failed to start shell: ", err) } }
[ "\"HOME\"", "\"USER\"" ]
[]
[ "USER", "HOME" ]
[]
["USER", "HOME"]
go
2
0
BaseTools/Source/Python/build/build.py
## @file # build a platform or a module # # Copyright (c) 2014, Hewlett-Packard Development Company, L.P.<BR> # Copyright (c) 2007 - 2021, Intel Corporation. All rights reserved.<BR> # Copyright (c) 2018, Hewlett Packard Enterprise Development, L.P.<BR> # Copyright (c) 2020, ARM Limited. All rights reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent # ## # Import Modules # from __future__ import print_function from __future__ import absolute_import import os.path as path import sys import os import re import glob import time import platform import traceback import multiprocessing from threading import Thread,Event,BoundedSemaphore import threading from linecache import getlines from subprocess import Popen,PIPE, STDOUT from collections import OrderedDict, defaultdict from AutoGen.PlatformAutoGen import PlatformAutoGen from AutoGen.ModuleAutoGen import ModuleAutoGen from AutoGen.WorkspaceAutoGen import WorkspaceAutoGen from AutoGen.AutoGenWorker import AutoGenWorkerInProcess,AutoGenManager,\ LogAgent from AutoGen import GenMake from Common import Misc as Utils from Common.TargetTxtClassObject import TargetTxtDict from Common.ToolDefClassObject import ToolDefDict from buildoptions import MyOptionParser from Common.Misc import PathClass,SaveFileOnChange,RemoveDirectory from Common.StringUtils import NormPath from Common.MultipleWorkspace import MultipleWorkspace as mws from Common.BuildToolError import * from Common.DataType import * import Common.EdkLogger as EdkLogger from Workspace.WorkspaceDatabase import BuildDB from BuildReport import BuildReport from GenPatchPcdTable.GenPatchPcdTable import PeImageClass,parsePcdInfoFromMapFile from PatchPcdValue.PatchPcdValue import PatchBinaryFile import Common.GlobalData as GlobalData from GenFds.GenFds import GenFds, GenFdsApi import multiprocessing as mp from multiprocessing import Manager from AutoGen.DataPipe import MemoryDataPipe from AutoGen.ModuleAutoGenHelper import WorkSpaceInfo, PlatformInfo from GenFds.FdfParser import FdfParser from AutoGen.IncludesAutoGen import IncludesAutoGen from GenFds.GenFds import resetFdsGlobalVariable from AutoGen.AutoGen import CalculatePriorityValue ## standard targets of build command gSupportedTarget = ['all', 'genc', 'genmake', 'modules', 'libraries', 'fds', 'clean', 'cleanall', 'cleanlib', 'run'] ## build configuration file gBuildConfiguration = "target.txt" gToolsDefinition = "tools_def.txt" TemporaryTablePattern = re.compile(r'^_\d+_\d+_[a-fA-F0-9]+$') TmpTableDict = {} ## Check environment PATH variable to make sure the specified tool is found # # If the tool is found in the PATH, then True is returned # Otherwise, False is returned # def IsToolInPath(tool): if 'PATHEXT' in os.environ: extns = os.environ['PATHEXT'].split(os.path.pathsep) else: extns = ('',) for pathDir in os.environ['PATH'].split(os.path.pathsep): for ext in extns: if os.path.exists(os.path.join(pathDir, tool + ext)): return True return False ## Check environment variables # # Check environment variables that must be set for build. Currently they are # # WORKSPACE The directory all packages/platforms start from # EDK_TOOLS_PATH The directory contains all tools needed by the build # PATH $(EDK_TOOLS_PATH)/Bin/<sys> must be set in PATH # # If any of above environment variable is not set or has error, the build # will be broken. # def CheckEnvVariable(): # check WORKSPACE if "WORKSPACE" not in os.environ: EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found", ExtraData="WORKSPACE") WorkspaceDir = os.path.normcase(os.path.normpath(os.environ["WORKSPACE"])) if not os.path.exists(WorkspaceDir): EdkLogger.error("build", FILE_NOT_FOUND, "WORKSPACE doesn't exist", ExtraData=WorkspaceDir) elif ' ' in WorkspaceDir: EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "No space is allowed in WORKSPACE path", ExtraData=WorkspaceDir) os.environ["WORKSPACE"] = WorkspaceDir # set multiple workspace PackagesPath = os.getenv("PACKAGES_PATH") mws.setWs(WorkspaceDir, PackagesPath) if mws.PACKAGES_PATH: for Path in mws.PACKAGES_PATH: if not os.path.exists(Path): EdkLogger.error("build", FILE_NOT_FOUND, "One Path in PACKAGES_PATH doesn't exist", ExtraData=Path) elif ' ' in Path: EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "No space is allowed in PACKAGES_PATH", ExtraData=Path) os.environ["EDK_TOOLS_PATH"] = os.path.normcase(os.environ["EDK_TOOLS_PATH"]) # check EDK_TOOLS_PATH if "EDK_TOOLS_PATH" not in os.environ: EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found", ExtraData="EDK_TOOLS_PATH") # check PATH if "PATH" not in os.environ: EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "Environment variable not found", ExtraData="PATH") GlobalData.gWorkspace = WorkspaceDir GlobalData.gGlobalDefines["WORKSPACE"] = WorkspaceDir GlobalData.gGlobalDefines["EDK_TOOLS_PATH"] = os.environ["EDK_TOOLS_PATH"] ## Get normalized file path # # Convert the path to be local format, and remove the WORKSPACE path at the # beginning if the file path is given in full path. # # @param FilePath File path to be normalized # @param Workspace Workspace path which the FilePath will be checked against # # @retval string The normalized file path # def NormFile(FilePath, Workspace): # check if the path is absolute or relative if os.path.isabs(FilePath): FileFullPath = os.path.normpath(FilePath) else: FileFullPath = os.path.normpath(mws.join(Workspace, FilePath)) Workspace = mws.getWs(Workspace, FilePath) # check if the file path exists or not if not os.path.isfile(FileFullPath): EdkLogger.error("build", FILE_NOT_FOUND, ExtraData="\t%s (Please give file in absolute path or relative to WORKSPACE)" % FileFullPath) # remove workspace directory from the beginning part of the file path if Workspace[-1] in ["\\", "/"]: return FileFullPath[len(Workspace):] else: return FileFullPath[(len(Workspace) + 1):] ## Get the output of an external program # # This is the entrance method of thread reading output of an external program and # putting them in STDOUT/STDERR of current program. # # @param From The stream message read from # @param To The stream message put on # @param ExitFlag The flag used to indicate stopping reading # def ReadMessage(From, To, ExitFlag,MemTo=None): while True: # read one line a time Line = From.readline() # empty string means "end" if Line is not None and Line != b"": LineStr = Line.rstrip().decode(encoding='utf-8', errors='ignore') if MemTo is not None: if "Note: including file:" == LineStr.lstrip()[:21]: MemTo.append(LineStr) else: To(LineStr) MemTo.append(LineStr) else: To(LineStr) else: break if ExitFlag.isSet(): break class MakeSubProc(Popen): def __init__(self,*args, **argv): super(MakeSubProc,self).__init__(*args, **argv) self.ProcOut = [] ## Launch an external program # # This method will call subprocess.Popen to execute an external program with # given options in specified directory. Because of the dead-lock issue during # redirecting output of the external program, threads are used to to do the # redirection work. # # @param Command A list or string containing the call of the program # @param WorkingDir The directory in which the program will be running # def LaunchCommand(Command, WorkingDir,ModuleAuto = None): BeginTime = time.time() # if working directory doesn't exist, Popen() will raise an exception if not os.path.isdir(WorkingDir): EdkLogger.error("build", FILE_NOT_FOUND, ExtraData=WorkingDir) # Command is used as the first Argument in following Popen(). # It could be a string or sequence. We find that if command is a string in following Popen(), # ubuntu may fail with an error message that the command is not found. # So here we may need convert command from string to list instance. if platform.system() != 'Windows': if not isinstance(Command, list): Command = Command.split() Command = ' '.join(Command) Proc = None EndOfProcedure = None try: # launch the command Proc = MakeSubProc(Command, stdout=PIPE, stderr=STDOUT, env=os.environ, cwd=WorkingDir, bufsize=-1, shell=True) # launch two threads to read the STDOUT and STDERR EndOfProcedure = Event() EndOfProcedure.clear() if Proc.stdout: StdOutThread = Thread(target=ReadMessage, args=(Proc.stdout, EdkLogger.info, EndOfProcedure,Proc.ProcOut)) StdOutThread.setName("STDOUT-Redirector") StdOutThread.setDaemon(False) StdOutThread.start() # waiting for program exit Proc.wait() except: # in case of aborting # terminate the threads redirecting the program output EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc()) if EndOfProcedure is not None: EndOfProcedure.set() if Proc is None: if not isinstance(Command, type("")): Command = " ".join(Command) EdkLogger.error("build", COMMAND_FAILURE, "Failed to start command", ExtraData="%s [%s]" % (Command, WorkingDir)) if Proc.stdout: StdOutThread.join() # check the return code of the program if Proc.returncode != 0: if not isinstance(Command, type("")): Command = " ".join(Command) # print out the Response file and its content when make failure RespFile = os.path.join(WorkingDir, 'OUTPUT', 'respfilelist.txt') if os.path.isfile(RespFile): f = open(RespFile) RespContent = f.read() f.close() EdkLogger.info(RespContent) EdkLogger.error("build", COMMAND_FAILURE, ExtraData="%s [%s]" % (Command, WorkingDir)) if ModuleAuto: iau = IncludesAutoGen(WorkingDir,ModuleAuto) if ModuleAuto.ToolChainFamily == TAB_COMPILER_MSFT: iau.CreateDepsFileForMsvc(Proc.ProcOut) else: iau.UpdateDepsFileforNonMsvc() iau.UpdateDepsFileforTrim() iau.CreateModuleDeps() iau.CreateDepsInclude() iau.CreateDepsTarget() return "%dms" % (int(round((time.time() - BeginTime) * 1000))) ## The smallest unit that can be built in multi-thread build mode # # This is the base class of build unit. The "Obj" parameter must provide # __str__(), __eq__() and __hash__() methods. Otherwise there could be build units # missing build. # # Currently the "Obj" should be only ModuleAutoGen or PlatformAutoGen objects. # class BuildUnit: ## The constructor # # @param self The object pointer # @param Obj The object the build is working on # @param Target The build target name, one of gSupportedTarget # @param Dependency The BuildUnit(s) which must be completed in advance # @param WorkingDir The directory build command starts in # def __init__(self, Obj, BuildCommand, Target, Dependency, WorkingDir="."): self.BuildObject = Obj self.Dependency = Dependency self.WorkingDir = WorkingDir self.Target = Target self.BuildCommand = BuildCommand if not BuildCommand: EdkLogger.error("build", OPTION_MISSING, "No build command found for this module. " "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." % (Obj.BuildTarget, Obj.ToolChain, Obj.Arch), ExtraData=str(Obj)) ## str() method # # It just returns the string representation of self.BuildObject # # @param self The object pointer # def __str__(self): return str(self.BuildObject) ## "==" operator method # # It just compares self.BuildObject with "Other". So self.BuildObject must # provide its own __eq__() method. # # @param self The object pointer # @param Other The other BuildUnit object compared to # def __eq__(self, Other): return Other and self.BuildObject == Other.BuildObject \ and Other.BuildObject \ and self.BuildObject.Arch == Other.BuildObject.Arch ## hash() method # # It just returns the hash value of self.BuildObject which must be hashable. # # @param self The object pointer # def __hash__(self): return hash(self.BuildObject) + hash(self.BuildObject.Arch) def __repr__(self): return repr(self.BuildObject) ## The smallest module unit that can be built by nmake/make command in multi-thread build mode # # This class is for module build by nmake/make build system. The "Obj" parameter # must provide __str__(), __eq__() and __hash__() methods. Otherwise there could # be make units missing build. # # Currently the "Obj" should be only ModuleAutoGen object. # class ModuleMakeUnit(BuildUnit): ## The constructor # # @param self The object pointer # @param Obj The ModuleAutoGen object the build is working on # @param Target The build target name, one of gSupportedTarget # def __init__(self, Obj, BuildCommand,Target): Dependency = [ModuleMakeUnit(La, BuildCommand,Target) for La in Obj.LibraryAutoGenList] BuildUnit.__init__(self, Obj, BuildCommand, Target, Dependency, Obj.MakeFileDir) if Target in [None, "", "all"]: self.Target = "tbuild" ## The smallest platform unit that can be built by nmake/make command in multi-thread build mode # # This class is for platform build by nmake/make build system. The "Obj" parameter # must provide __str__(), __eq__() and __hash__() methods. Otherwise there could # be make units missing build. # # Currently the "Obj" should be only PlatformAutoGen object. # class PlatformMakeUnit(BuildUnit): ## The constructor # # @param self The object pointer # @param Obj The PlatformAutoGen object the build is working on # @param Target The build target name, one of gSupportedTarget # def __init__(self, Obj, BuildCommand, Target): Dependency = [ModuleMakeUnit(Lib, BuildCommand, Target) for Lib in self.BuildObject.LibraryAutoGenList] Dependency.extend([ModuleMakeUnit(Mod, BuildCommand,Target) for Mod in self.BuildObject.ModuleAutoGenList]) BuildUnit.__init__(self, Obj, BuildCommand, Target, Dependency, Obj.MakeFileDir) ## The class representing the task of a module build or platform build # # This class manages the build tasks in multi-thread build mode. Its jobs include # scheduling thread running, catching thread error, monitor the thread status, etc. # class BuildTask: # queue for tasks waiting for schedule _PendingQueue = OrderedDict() _PendingQueueLock = threading.Lock() # queue for tasks ready for running _ReadyQueue = OrderedDict() _ReadyQueueLock = threading.Lock() # queue for run tasks _RunningQueue = OrderedDict() _RunningQueueLock = threading.Lock() # queue containing all build tasks, in case duplicate build _TaskQueue = OrderedDict() # flag indicating error occurs in a running thread _ErrorFlag = threading.Event() _ErrorFlag.clear() _ErrorMessage = "" # BoundedSemaphore object used to control the number of running threads _Thread = None # flag indicating if the scheduler is started or not _SchedulerStopped = threading.Event() _SchedulerStopped.set() ## Start the task scheduler thread # # @param MaxThreadNumber The maximum thread number # @param ExitFlag Flag used to end the scheduler # @staticmethod def StartScheduler(MaxThreadNumber, ExitFlag): SchedulerThread = Thread(target=BuildTask.Scheduler, args=(MaxThreadNumber, ExitFlag)) SchedulerThread.setName("Build-Task-Scheduler") SchedulerThread.setDaemon(False) SchedulerThread.start() # wait for the scheduler to be started, especially useful in Linux while not BuildTask.IsOnGoing(): time.sleep(0.01) ## Scheduler method # # @param MaxThreadNumber The maximum thread number # @param ExitFlag Flag used to end the scheduler # @staticmethod def Scheduler(MaxThreadNumber, ExitFlag): BuildTask._SchedulerStopped.clear() try: # use BoundedSemaphore to control the maximum running threads BuildTask._Thread = BoundedSemaphore(MaxThreadNumber) # # scheduling loop, which will exits when no pending/ready task and # indicated to do so, or there's error in running thread # while (len(BuildTask._PendingQueue) > 0 or len(BuildTask._ReadyQueue) > 0 \ or not ExitFlag.isSet()) and not BuildTask._ErrorFlag.isSet(): EdkLogger.debug(EdkLogger.DEBUG_8, "Pending Queue (%d), Ready Queue (%d)" % (len(BuildTask._PendingQueue), len(BuildTask._ReadyQueue))) # get all pending tasks BuildTask._PendingQueueLock.acquire() BuildObjectList = list(BuildTask._PendingQueue.keys()) # # check if their dependency is resolved, and if true, move them # into ready queue # for BuildObject in BuildObjectList: Bt = BuildTask._PendingQueue[BuildObject] if Bt.IsReady(): BuildTask._ReadyQueue[BuildObject] = BuildTask._PendingQueue.pop(BuildObject) BuildTask._PendingQueueLock.release() # launch build thread until the maximum number of threads is reached while not BuildTask._ErrorFlag.isSet(): # empty ready queue, do nothing further if len(BuildTask._ReadyQueue) == 0: break # wait for active thread(s) exit BuildTask._Thread.acquire(True) # start a new build thread Bo, Bt = BuildTask._ReadyQueue.popitem() # move into running queue BuildTask._RunningQueueLock.acquire() BuildTask._RunningQueue[Bo] = Bt BuildTask._RunningQueueLock.release() Bt.Start() # avoid tense loop time.sleep(0.01) # avoid tense loop time.sleep(0.01) # wait for all running threads exit if BuildTask._ErrorFlag.isSet(): EdkLogger.quiet("\nWaiting for all build threads exit...") # while not BuildTask._ErrorFlag.isSet() and \ while len(BuildTask._RunningQueue) > 0: EdkLogger.verbose("Waiting for thread ending...(%d)" % len(BuildTask._RunningQueue)) EdkLogger.debug(EdkLogger.DEBUG_8, "Threads [%s]" % ", ".join(Th.getName() for Th in threading.enumerate())) # avoid tense loop time.sleep(0.1) except BaseException as X: # # TRICK: hide the output of threads left running, so that the user can # catch the error message easily # EdkLogger.SetLevel(EdkLogger.ERROR) BuildTask._ErrorFlag.set() BuildTask._ErrorMessage = "build thread scheduler error\n\t%s" % str(X) BuildTask._PendingQueue.clear() BuildTask._ReadyQueue.clear() BuildTask._RunningQueue.clear() BuildTask._TaskQueue.clear() BuildTask._SchedulerStopped.set() ## Wait for all running method exit # @staticmethod def WaitForComplete(): BuildTask._SchedulerStopped.wait() ## Check if the scheduler is running or not # @staticmethod def IsOnGoing(): return not BuildTask._SchedulerStopped.isSet() ## Abort the build @staticmethod def Abort(): if BuildTask.IsOnGoing(): BuildTask._ErrorFlag.set() BuildTask.WaitForComplete() ## Check if there's error in running thread # # Since the main thread cannot catch exceptions in other thread, we have to # use threading.Event to communicate this formation to main thread. # @staticmethod def HasError(): return BuildTask._ErrorFlag.isSet() ## Get error message in running thread # # Since the main thread cannot catch exceptions in other thread, we have to # use a static variable to communicate this message to main thread. # @staticmethod def GetErrorMessage(): return BuildTask._ErrorMessage ## Factory method to create a BuildTask object # # This method will check if a module is building or has been built. And if # true, just return the associated BuildTask object in the _TaskQueue. If # not, create and return a new BuildTask object. The new BuildTask object # will be appended to the _PendingQueue for scheduling later. # # @param BuildItem A BuildUnit object representing a build object # @param Dependency The dependent build object of BuildItem # @staticmethod def New(BuildItem, Dependency=None): if BuildItem in BuildTask._TaskQueue: Bt = BuildTask._TaskQueue[BuildItem] return Bt Bt = BuildTask() Bt._Init(BuildItem, Dependency) BuildTask._TaskQueue[BuildItem] = Bt BuildTask._PendingQueueLock.acquire() BuildTask._PendingQueue[BuildItem] = Bt BuildTask._PendingQueueLock.release() return Bt ## The real constructor of BuildTask # # @param BuildItem A BuildUnit object representing a build object # @param Dependency The dependent build object of BuildItem # def _Init(self, BuildItem, Dependency=None): self.BuildItem = BuildItem self.DependencyList = [] if Dependency is None: Dependency = BuildItem.Dependency else: Dependency.extend(BuildItem.Dependency) self.AddDependency(Dependency) # flag indicating build completes, used to avoid unnecessary re-build self.CompleteFlag = False ## Check if all dependent build tasks are completed or not # def IsReady(self): ReadyFlag = True for Dep in self.DependencyList: if Dep.CompleteFlag == True: continue ReadyFlag = False break return ReadyFlag ## Add dependent build task # # @param Dependency The list of dependent build objects # def AddDependency(self, Dependency): for Dep in Dependency: if not Dep.BuildObject.IsBinaryModule and not Dep.BuildObject.CanSkipbyCache(GlobalData.gModuleCacheHit): self.DependencyList.append(BuildTask.New(Dep)) # BuildTask list ## The thread wrapper of LaunchCommand function # # @param Command A list or string contains the call of the command # @param WorkingDir The directory in which the program will be running # def _CommandThread(self, Command, WorkingDir): try: self.BuildItem.BuildObject.BuildTime = LaunchCommand(Command, WorkingDir,self.BuildItem.BuildObject) self.CompleteFlag = True # Run hash operation post dependency to account for libs # Run if --hash or --binary-destination if GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: self.BuildItem.BuildObject.GenModuleHash() if GlobalData.gBinCacheDest: self.BuildItem.BuildObject.GenCMakeHash() except: # # TRICK: hide the output of threads left running, so that the user can # catch the error message easily # if not BuildTask._ErrorFlag.isSet(): GlobalData.gBuildingModule = "%s [%s, %s, %s]" % (str(self.BuildItem.BuildObject), self.BuildItem.BuildObject.Arch, self.BuildItem.BuildObject.ToolChain, self.BuildItem.BuildObject.BuildTarget ) EdkLogger.SetLevel(EdkLogger.ERROR) BuildTask._ErrorFlag.set() BuildTask._ErrorMessage = "%s broken\n %s [%s]" % \ (threading.currentThread().getName(), Command, WorkingDir) # indicate there's a thread is available for another build task BuildTask._RunningQueueLock.acquire() BuildTask._RunningQueue.pop(self.BuildItem) BuildTask._RunningQueueLock.release() BuildTask._Thread.release() ## Start build task thread # def Start(self): EdkLogger.quiet("Building ... %s" % repr(self.BuildItem)) Command = self.BuildItem.BuildCommand + [self.BuildItem.Target] self.BuildTread = Thread(target=self._CommandThread, args=(Command, self.BuildItem.WorkingDir)) self.BuildTread.setName("build thread") self.BuildTread.setDaemon(False) self.BuildTread.start() ## The class contains the information related to EFI image # class PeImageInfo(): ## Constructor # # Constructor will load all required image information. # # @param BaseName The full file path of image. # @param Guid The GUID for image. # @param Arch Arch of this image. # @param OutputDir The output directory for image. # @param DebugDir The debug directory for image. # @param ImageClass PeImage Information # def __init__(self, BaseName, Guid, Arch, OutputDir, DebugDir, ImageClass): self.BaseName = BaseName self.Guid = Guid self.Arch = Arch self.OutputDir = OutputDir self.DebugDir = DebugDir self.Image = ImageClass self.Image.Size = (self.Image.Size // 0x1000 + 1) * 0x1000 ## The class implementing the EDK2 build process # # The build process includes: # 1. Load configuration from target.txt and tools_def.txt in $(WORKSPACE)/Conf # 2. Parse DSC file of active platform # 3. Parse FDF file if any # 4. Establish build database, including parse all other files (module, package) # 5. Create AutoGen files (C code file, depex file, makefile) if necessary # 6. Call build command # class Build(): ## Constructor # # Constructor will load all necessary configurations, parse platform, modules # and packages and the establish a database for AutoGen. # # @param Target The build command target, one of gSupportedTarget # @param WorkspaceDir The directory of workspace # @param BuildOptions Build options passed from command line # def __init__(self, Target, WorkspaceDir, BuildOptions,log_q): self.WorkspaceDir = WorkspaceDir self.Target = Target self.PlatformFile = BuildOptions.PlatformFile self.ModuleFile = BuildOptions.ModuleFile self.ArchList = BuildOptions.TargetArch self.ToolChainList = BuildOptions.ToolChain self.BuildTargetList= BuildOptions.BuildTarget self.Fdf = BuildOptions.FdfFile self.FdList = BuildOptions.RomImage self.FvList = BuildOptions.FvImage self.CapList = BuildOptions.CapName self.SilentMode = BuildOptions.SilentMode self.ThreadNumber = 1 self.SkipAutoGen = BuildOptions.SkipAutoGen self.Reparse = BuildOptions.Reparse self.SkuId = BuildOptions.SkuId if self.SkuId: GlobalData.gSKUID_CMD = self.SkuId self.ConfDirectory = BuildOptions.ConfDirectory self.SpawnMode = True self.BuildReport = BuildReport(BuildOptions.ReportFile, BuildOptions.ReportType) self.AutoGenTime = 0 self.MakeTime = 0 self.GenFdsTime = 0 self.MakeFileName = "" TargetObj = TargetTxtDict() ToolDefObj = ToolDefDict((os.path.join(os.getenv("WORKSPACE"),"Conf"))) self.TargetTxt = TargetObj.Target self.ToolDef = ToolDefObj.ToolDef GlobalData.BuildOptionPcd = BuildOptions.OptionPcd if BuildOptions.OptionPcd else [] #Set global flag for build mode GlobalData.gIgnoreSource = BuildOptions.IgnoreSources GlobalData.gUseHashCache = BuildOptions.UseHashCache GlobalData.gBinCacheDest = BuildOptions.BinCacheDest GlobalData.gBinCacheSource = BuildOptions.BinCacheSource GlobalData.gEnableGenfdsMultiThread = not BuildOptions.NoGenfdsMultiThread GlobalData.gDisableIncludePathCheck = BuildOptions.DisableIncludePathCheck if GlobalData.gBinCacheDest and not GlobalData.gUseHashCache: EdkLogger.error("build", OPTION_NOT_SUPPORTED, ExtraData="--binary-destination must be used together with --hash.") if GlobalData.gBinCacheSource and not GlobalData.gUseHashCache: EdkLogger.error("build", OPTION_NOT_SUPPORTED, ExtraData="--binary-source must be used together with --hash.") if GlobalData.gBinCacheDest and GlobalData.gBinCacheSource: EdkLogger.error("build", OPTION_NOT_SUPPORTED, ExtraData="--binary-destination can not be used together with --binary-source.") if GlobalData.gBinCacheSource: BinCacheSource = os.path.normpath(GlobalData.gBinCacheSource) if not os.path.isabs(BinCacheSource): BinCacheSource = mws.join(self.WorkspaceDir, BinCacheSource) GlobalData.gBinCacheSource = BinCacheSource else: if GlobalData.gBinCacheSource is not None: EdkLogger.error("build", OPTION_VALUE_INVALID, ExtraData="Invalid value of option --binary-source.") if GlobalData.gBinCacheDest: BinCacheDest = os.path.normpath(GlobalData.gBinCacheDest) if not os.path.isabs(BinCacheDest): BinCacheDest = mws.join(self.WorkspaceDir, BinCacheDest) GlobalData.gBinCacheDest = BinCacheDest else: if GlobalData.gBinCacheDest is not None: EdkLogger.error("build", OPTION_VALUE_INVALID, ExtraData="Invalid value of option --binary-destination.") GlobalData.gDatabasePath = os.path.normpath(os.path.join(GlobalData.gConfDirectory, GlobalData.gDatabasePath)) if not os.path.exists(os.path.join(GlobalData.gConfDirectory, '.cache')): os.makedirs(os.path.join(GlobalData.gConfDirectory, '.cache')) self.Db = BuildDB self.BuildDatabase = self.Db.BuildObject self.Platform = None self.ToolChainFamily = None self.LoadFixAddress = 0 self.UniFlag = BuildOptions.Flag self.BuildModules = [] self.HashSkipModules = [] self.Db_Flag = False self.LaunchPrebuildFlag = False self.PlatformBuildPath = os.path.join(GlobalData.gConfDirectory, '.cache', '.PlatformBuild') if BuildOptions.CommandLength: GlobalData.gCommandMaxLength = BuildOptions.CommandLength # print dot character during doing some time-consuming work self.Progress = Utils.Progressor() # print current build environment and configuration EdkLogger.quiet("%-16s = %s" % ("WORKSPACE", os.environ["WORKSPACE"])) if "PACKAGES_PATH" in os.environ: # WORKSPACE env has been converted before. Print the same path style with WORKSPACE env. EdkLogger.quiet("%-16s = %s" % ("PACKAGES_PATH", os.path.normcase(os.path.normpath(os.environ["PACKAGES_PATH"])))) EdkLogger.quiet("%-16s = %s" % ("EDK_TOOLS_PATH", os.environ["EDK_TOOLS_PATH"])) if "EDK_TOOLS_BIN" in os.environ: # Print the same path style with WORKSPACE env. EdkLogger.quiet("%-16s = %s" % ("EDK_TOOLS_BIN", os.path.normcase(os.path.normpath(os.environ["EDK_TOOLS_BIN"])))) EdkLogger.quiet("%-16s = %s" % ("CONF_PATH", GlobalData.gConfDirectory)) if "PYTHON3_ENABLE" in os.environ: PYTHON3_ENABLE = os.environ["PYTHON3_ENABLE"] if PYTHON3_ENABLE != "TRUE": PYTHON3_ENABLE = "FALSE" EdkLogger.quiet("%-16s = %s" % ("PYTHON3_ENABLE", PYTHON3_ENABLE)) if "PYTHON_COMMAND" in os.environ: EdkLogger.quiet("%-16s = %s" % ("PYTHON_COMMAND", os.environ["PYTHON_COMMAND"])) self.InitPreBuild() self.InitPostBuild() if self.Prebuild: EdkLogger.quiet("%-16s = %s" % ("PREBUILD", self.Prebuild)) if self.Postbuild: EdkLogger.quiet("%-16s = %s" % ("POSTBUILD", self.Postbuild)) if self.Prebuild: self.LaunchPrebuild() TargetObj = TargetTxtDict() ToolDefObj = ToolDefDict((os.path.join(os.getenv("WORKSPACE"), "Conf"))) self.TargetTxt = TargetObj.Target self.ToolDef = ToolDefObj.ToolDef if not (self.LaunchPrebuildFlag and os.path.exists(self.PlatformBuildPath)): self.InitBuild() self.AutoGenMgr = None EdkLogger.info("") os.chdir(self.WorkspaceDir) self.log_q = log_q GlobalData.file_lock = mp.Lock() # Init cache data for local only GlobalData.gPackageHashFile = dict() GlobalData.gModulePreMakeCacheStatus = dict() GlobalData.gModuleMakeCacheStatus = dict() GlobalData.gHashChainStatus = dict() GlobalData.gCMakeHashFile = dict() GlobalData.gModuleHashFile = dict() GlobalData.gFileHashDict = dict() GlobalData.gModuleAllCacheStatus = set() GlobalData.gModuleCacheHit = set() def StartAutoGen(self,mqueue, DataPipe,SkipAutoGen,PcdMaList,cqueue): try: if SkipAutoGen: return True,0 feedback_q = mp.Queue() error_event = mp.Event() FfsCmd = DataPipe.Get("FfsCommand") if FfsCmd is None: FfsCmd = {} GlobalData.FfsCmd = FfsCmd auto_workers = [AutoGenWorkerInProcess(mqueue,DataPipe.dump_file,feedback_q,GlobalData.file_lock,cqueue,self.log_q,error_event) for _ in range(self.ThreadNumber)] self.AutoGenMgr = AutoGenManager(auto_workers,feedback_q,error_event) self.AutoGenMgr.start() for w in auto_workers: w.start() if PcdMaList is not None: for PcdMa in PcdMaList: # SourceFileList calling sequence impact the makefile string sequence. # Create cached SourceFileList here to unify its calling sequence for both # CanSkipbyPreMakeCache and CreateCodeFile/CreateMakeFile. RetVal = PcdMa.SourceFileList # Force cache miss for PCD driver if GlobalData.gUseHashCache and not GlobalData.gBinCacheDest and self.Target in [None, "", "all"]: cqueue.put((PcdMa.MetaFile.Path, PcdMa.Arch, "PreMakeCache", False)) PcdMa.CreateCodeFile(False) PcdMa.CreateMakeFile(False,GenFfsList = DataPipe.Get("FfsCommand").get((PcdMa.MetaFile.Path, PcdMa.Arch),[])) PcdMa.CreateAsBuiltInf() # Force cache miss for PCD driver if GlobalData.gBinCacheSource and self.Target in [None, "", "all"]: cqueue.put((PcdMa.MetaFile.Path, PcdMa.Arch, "MakeCache", False)) self.AutoGenMgr.join() rt = self.AutoGenMgr.Status err = 0 if not rt: err = UNKNOWN_ERROR return rt, err except FatalError as e: return False, e.args[0] except: return False, UNKNOWN_ERROR ## Add TOOLCHAIN and FAMILY declared in DSC [BuildOptions] to ToolsDefTxtDatabase. # # Loop through the set of build targets, tool chains, and archs provided on either # the command line or in target.txt to discover FAMILY and TOOLCHAIN delclarations # in [BuildOptions] sections that may be within !if expressions that may use # $(TARGET), $(TOOLCHAIN), $(TOOLCHAIN_TAG), or $(ARCH) operands. # def GetToolChainAndFamilyFromDsc (self, File): SavedGlobalDefines = GlobalData.gGlobalDefines.copy() for BuildTarget in self.BuildTargetList: GlobalData.gGlobalDefines['TARGET'] = BuildTarget for BuildToolChain in self.ToolChainList: GlobalData.gGlobalDefines['TOOLCHAIN'] = BuildToolChain GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = BuildToolChain for BuildArch in self.ArchList: GlobalData.gGlobalDefines['ARCH'] = BuildArch dscobj = self.BuildDatabase[File, BuildArch] for KeyFamily, Key, KeyCodeBase in dscobj.BuildOptions: try: Target, ToolChain, Arch, Tool, Attr = Key.split('_') except: continue if ToolChain == TAB_STAR or Attr != TAB_TOD_DEFINES_FAMILY: continue try: Family = dscobj.BuildOptions[(KeyFamily, Key, KeyCodeBase)] Family = Family.strip().strip('=').strip() except: continue if TAB_TOD_DEFINES_FAMILY not in self.ToolDef.ToolsDefTxtDatabase: self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_FAMILY] = {} if ToolChain not in self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_FAMILY]: self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_FAMILY][ToolChain] = Family if TAB_TOD_DEFINES_BUILDRULEFAMILY not in self.ToolDef.ToolsDefTxtDatabase: self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_BUILDRULEFAMILY] = {} if ToolChain not in self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_BUILDRULEFAMILY]: self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_BUILDRULEFAMILY][ToolChain] = Family if TAB_TOD_DEFINES_TOOL_CHAIN_TAG not in self.ToolDef.ToolsDefTxtDatabase: self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_TOOL_CHAIN_TAG] = [] if ToolChain not in self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_TOOL_CHAIN_TAG]: self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_TOOL_CHAIN_TAG].append(ToolChain) GlobalData.gGlobalDefines = SavedGlobalDefines ## Load configuration # # This method will parse target.txt and get the build configurations. # def LoadConfiguration(self): # if no ARCH given in command line, get it from target.txt if not self.ArchList: self.ArchList = self.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_TARGET_ARCH] self.ArchList = tuple(self.ArchList) # if no build target given in command line, get it from target.txt if not self.BuildTargetList: self.BuildTargetList = self.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_TARGET] # if no tool chain given in command line, get it from target.txt if not self.ToolChainList: self.ToolChainList = self.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_TOOL_CHAIN_TAG] if self.ToolChainList is None or len(self.ToolChainList) == 0: EdkLogger.error("build", RESOURCE_NOT_AVAILABLE, ExtraData="No toolchain given. Don't know how to build.\n") if not self.PlatformFile: PlatformFile = self.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_ACTIVE_PLATFORM] if not PlatformFile: # Try to find one in current directory WorkingDirectory = os.getcwd() FileList = glob.glob(os.path.normpath(os.path.join(WorkingDirectory, '*.dsc'))) FileNum = len(FileList) if FileNum >= 2: EdkLogger.error("build", OPTION_MISSING, ExtraData="There are %d DSC files in %s. Use '-p' to specify one.\n" % (FileNum, WorkingDirectory)) elif FileNum == 1: PlatformFile = FileList[0] else: EdkLogger.error("build", RESOURCE_NOT_AVAILABLE, ExtraData="No active platform specified in target.txt or command line! Nothing can be built.\n") self.PlatformFile = PathClass(NormFile(PlatformFile, self.WorkspaceDir), self.WorkspaceDir) self.GetToolChainAndFamilyFromDsc (self.PlatformFile) # check if the tool chains are defined or not NewToolChainList = [] for ToolChain in self.ToolChainList: if ToolChain not in self.ToolDef.ToolsDefTxtDatabase[TAB_TOD_DEFINES_TOOL_CHAIN_TAG]: EdkLogger.warn("build", "Tool chain [%s] is not defined" % ToolChain) else: NewToolChainList.append(ToolChain) # if no tool chain available, break the build if len(NewToolChainList) == 0: EdkLogger.error("build", RESOURCE_NOT_AVAILABLE, ExtraData="[%s] not defined. No toolchain available for build!\n" % ", ".join(self.ToolChainList)) else: self.ToolChainList = NewToolChainList ToolChainFamily = [] ToolDefinition = self.ToolDef.ToolsDefTxtDatabase for Tool in self.ToolChainList: if TAB_TOD_DEFINES_FAMILY not in ToolDefinition or Tool not in ToolDefinition[TAB_TOD_DEFINES_FAMILY] \ or not ToolDefinition[TAB_TOD_DEFINES_FAMILY][Tool]: EdkLogger.warn("build", "No tool chain family found in configuration for %s. Default to MSFT." % Tool) ToolChainFamily.append(TAB_COMPILER_MSFT) else: ToolChainFamily.append(ToolDefinition[TAB_TOD_DEFINES_FAMILY][Tool]) self.ToolChainFamily = ToolChainFamily self.ThreadNumber = ThreadNum() ## Initialize build configuration # # This method will parse DSC file and merge the configurations from # command line and target.txt, then get the final build configurations. # def InitBuild(self): # parse target.txt, tools_def.txt, and platform file self.LoadConfiguration() # Allow case-insensitive for those from command line or configuration file ErrorCode, ErrorInfo = self.PlatformFile.Validate(".dsc", False) if ErrorCode != 0: EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo) def InitPreBuild(self): self.LoadConfiguration() ErrorCode, ErrorInfo = self.PlatformFile.Validate(".dsc", False) if ErrorCode != 0: EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo) if self.BuildTargetList: GlobalData.gGlobalDefines['TARGET'] = self.BuildTargetList[0] if self.ArchList: GlobalData.gGlobalDefines['ARCH'] = self.ArchList[0] if self.ToolChainList: GlobalData.gGlobalDefines['TOOLCHAIN'] = self.ToolChainList[0] GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = self.ToolChainList[0] if self.ToolChainFamily: GlobalData.gGlobalDefines['FAMILY'] = self.ToolChainFamily[0] if 'PREBUILD' in GlobalData.gCommandLineDefines: self.Prebuild = GlobalData.gCommandLineDefines.get('PREBUILD') else: self.Db_Flag = True Platform = self.Db.MapPlatform(str(self.PlatformFile)) self.Prebuild = str(Platform.Prebuild) if self.Prebuild: PrebuildList = [] # # Evaluate all arguments and convert arguments that are WORKSPACE # relative paths to absolute paths. Filter arguments that look like # flags or do not follow the file/dir naming rules to avoid false # positives on this conversion. # for Arg in self.Prebuild.split(): # # Do not modify Arg if it looks like a flag or an absolute file path # if Arg.startswith('-') or os.path.isabs(Arg): PrebuildList.append(Arg) continue # # Do not modify Arg if it does not look like a Workspace relative # path that starts with a valid package directory name # if not Arg[0].isalpha() or os.path.dirname(Arg) == '': PrebuildList.append(Arg) continue # # If Arg looks like a WORKSPACE relative path, then convert to an # absolute path and check to see if the file exists. # Temp = mws.join(self.WorkspaceDir, Arg) if os.path.isfile(Temp): Arg = Temp PrebuildList.append(Arg) self.Prebuild = ' '.join(PrebuildList) self.Prebuild += self.PassCommandOption(self.BuildTargetList, self.ArchList, self.ToolChainList, self.PlatformFile, self.Target) def InitPostBuild(self): if 'POSTBUILD' in GlobalData.gCommandLineDefines: self.Postbuild = GlobalData.gCommandLineDefines.get('POSTBUILD') else: Platform = self.Db.MapPlatform(str(self.PlatformFile)) self.Postbuild = str(Platform.Postbuild) if self.Postbuild: PostbuildList = [] # # Evaluate all arguments and convert arguments that are WORKSPACE # relative paths to absolute paths. Filter arguments that look like # flags or do not follow the file/dir naming rules to avoid false # positives on this conversion. # for Arg in self.Postbuild.split(): # # Do not modify Arg if it looks like a flag or an absolute file path # if Arg.startswith('-') or os.path.isabs(Arg): PostbuildList.append(Arg) continue # # Do not modify Arg if it does not look like a Workspace relative # path that starts with a valid package directory name # if not Arg[0].isalpha() or os.path.dirname(Arg) == '': PostbuildList.append(Arg) continue # # If Arg looks like a WORKSPACE relative path, then convert to an # absolute path and check to see if the file exists. # Temp = mws.join(self.WorkspaceDir, Arg) if os.path.isfile(Temp): Arg = Temp PostbuildList.append(Arg) self.Postbuild = ' '.join(PostbuildList) self.Postbuild += self.PassCommandOption(self.BuildTargetList, self.ArchList, self.ToolChainList, self.PlatformFile, self.Target) def PassCommandOption(self, BuildTarget, TargetArch, ToolChain, PlatformFile, Target): BuildStr = '' if GlobalData.gCommand and isinstance(GlobalData.gCommand, list): BuildStr += ' ' + ' '.join(GlobalData.gCommand) TargetFlag = False ArchFlag = False ToolChainFlag = False PlatformFileFlag = False if GlobalData.gOptions and not GlobalData.gOptions.BuildTarget: TargetFlag = True if GlobalData.gOptions and not GlobalData.gOptions.TargetArch: ArchFlag = True if GlobalData.gOptions and not GlobalData.gOptions.ToolChain: ToolChainFlag = True if GlobalData.gOptions and not GlobalData.gOptions.PlatformFile: PlatformFileFlag = True if TargetFlag and BuildTarget: if isinstance(BuildTarget, list) or isinstance(BuildTarget, tuple): BuildStr += ' -b ' + ' -b '.join(BuildTarget) elif isinstance(BuildTarget, str): BuildStr += ' -b ' + BuildTarget if ArchFlag and TargetArch: if isinstance(TargetArch, list) or isinstance(TargetArch, tuple): BuildStr += ' -a ' + ' -a '.join(TargetArch) elif isinstance(TargetArch, str): BuildStr += ' -a ' + TargetArch if ToolChainFlag and ToolChain: if isinstance(ToolChain, list) or isinstance(ToolChain, tuple): BuildStr += ' -t ' + ' -t '.join(ToolChain) elif isinstance(ToolChain, str): BuildStr += ' -t ' + ToolChain if PlatformFileFlag and PlatformFile: if isinstance(PlatformFile, list) or isinstance(PlatformFile, tuple): BuildStr += ' -p ' + ' -p '.join(PlatformFile) elif isinstance(PlatformFile, str): BuildStr += ' -p' + PlatformFile BuildStr += ' --conf=' + GlobalData.gConfDirectory if Target: BuildStr += ' ' + Target return BuildStr def LaunchPrebuild(self): if self.Prebuild: EdkLogger.info("\n- Prebuild Start -\n") self.LaunchPrebuildFlag = True # # The purpose of .PrebuildEnv file is capture environment variable settings set by the prebuild script # and preserve them for the rest of the main build step, because the child process environment will # evaporate as soon as it exits, we cannot get it in build step. # PrebuildEnvFile = os.path.join(GlobalData.gConfDirectory, '.cache', '.PrebuildEnv') if os.path.isfile(PrebuildEnvFile): os.remove(PrebuildEnvFile) if os.path.isfile(self.PlatformBuildPath): os.remove(self.PlatformBuildPath) if sys.platform == "win32": args = ' && '.join((self.Prebuild, 'set > ' + PrebuildEnvFile)) Process = Popen(args, stdout=PIPE, stderr=PIPE, shell=True) else: args = ' && '.join((self.Prebuild, 'env > ' + PrebuildEnvFile)) Process = Popen(args, stdout=PIPE, stderr=PIPE, shell=True) # launch two threads to read the STDOUT and STDERR EndOfProcedure = Event() EndOfProcedure.clear() if Process.stdout: StdOutThread = Thread(target=ReadMessage, args=(Process.stdout, EdkLogger.info, EndOfProcedure)) StdOutThread.setName("STDOUT-Redirector") StdOutThread.setDaemon(False) StdOutThread.start() if Process.stderr: StdErrThread = Thread(target=ReadMessage, args=(Process.stderr, EdkLogger.quiet, EndOfProcedure)) StdErrThread.setName("STDERR-Redirector") StdErrThread.setDaemon(False) StdErrThread.start() # waiting for program exit Process.wait() if Process.stdout: StdOutThread.join() if Process.stderr: StdErrThread.join() if Process.returncode != 0 : EdkLogger.error("Prebuild", PREBUILD_ERROR, 'Prebuild process is not success!') if os.path.exists(PrebuildEnvFile): f = open(PrebuildEnvFile) envs = f.readlines() f.close() envs = [l.split("=", 1) for l in envs ] envs = [[I.strip() for I in item] for item in envs if len(item) == 2] os.environ.update(dict(envs)) EdkLogger.info("\n- Prebuild Done -\n") def LaunchPostbuild(self): if self.Postbuild: EdkLogger.info("\n- Postbuild Start -\n") if sys.platform == "win32": Process = Popen(self.Postbuild, stdout=PIPE, stderr=PIPE, shell=True) else: Process = Popen(self.Postbuild, stdout=PIPE, stderr=PIPE, shell=True) # launch two threads to read the STDOUT and STDERR EndOfProcedure = Event() EndOfProcedure.clear() if Process.stdout: StdOutThread = Thread(target=ReadMessage, args=(Process.stdout, EdkLogger.info, EndOfProcedure)) StdOutThread.setName("STDOUT-Redirector") StdOutThread.setDaemon(False) StdOutThread.start() if Process.stderr: StdErrThread = Thread(target=ReadMessage, args=(Process.stderr, EdkLogger.quiet, EndOfProcedure)) StdErrThread.setName("STDERR-Redirector") StdErrThread.setDaemon(False) StdErrThread.start() # waiting for program exit Process.wait() if Process.stdout: StdOutThread.join() if Process.stderr: StdErrThread.join() if Process.returncode != 0 : EdkLogger.error("Postbuild", POSTBUILD_ERROR, 'Postbuild process is not success!') EdkLogger.info("\n- Postbuild Done -\n") ## Build a module or platform # # Create autogen code and makefile for a module or platform, and the launch # "make" command to build it # # @param Target The target of build command # @param Platform The platform file # @param Module The module file # @param BuildTarget The name of build target, one of "DEBUG", "RELEASE" # @param ToolChain The name of toolchain to build # @param Arch The arch of the module/platform # @param CreateDepModuleCodeFile Flag used to indicate creating code # for dependent modules/Libraries # @param CreateDepModuleMakeFile Flag used to indicate creating makefile # for dependent modules/Libraries # def _BuildPa(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMakeFile=True, BuildModule=False, FfsCommand=None, PcdMaList=None): if AutoGenObject is None: return False if FfsCommand is None: FfsCommand = {} # skip file generation for cleanxxx targets, run and fds target if Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']: # for target which must generate AutoGen code and makefile mqueue = mp.Queue() for m in AutoGenObject.GetAllModuleInfo: mqueue.put(m) mqueue.put((None,None,None,None,None,None,None)) AutoGenObject.DataPipe.DataContainer = {"CommandTarget": self.Target} AutoGenObject.DataPipe.DataContainer = {"Workspace_timestamp": AutoGenObject.Workspace._SrcTimeStamp} AutoGenObject.CreateLibModuelDirs() AutoGenObject.DataPipe.DataContainer = {"LibraryBuildDirectoryList":AutoGenObject.LibraryBuildDirectoryList} AutoGenObject.DataPipe.DataContainer = {"ModuleBuildDirectoryList":AutoGenObject.ModuleBuildDirectoryList} AutoGenObject.DataPipe.DataContainer = {"FdsCommandDict": AutoGenObject.Workspace.GenFdsCommandDict} self.Progress.Start("Generating makefile and code") data_pipe_file = os.path.join(AutoGenObject.BuildDir, "GlobalVar_%s_%s.bin" % (str(AutoGenObject.Guid),AutoGenObject.Arch)) AutoGenObject.DataPipe.dump(data_pipe_file) cqueue = mp.Queue() autogen_rt,errorcode = self.StartAutoGen(mqueue, AutoGenObject.DataPipe, self.SkipAutoGen, PcdMaList, cqueue) AutoGenIdFile = os.path.join(GlobalData.gConfDirectory,".AutoGenIdFile.txt") with open(AutoGenIdFile,"w") as fw: fw.write("Arch=%s\n" % "|".join((AutoGenObject.Workspace.ArchList))) fw.write("BuildDir=%s\n" % AutoGenObject.Workspace.BuildDir) fw.write("PlatformGuid=%s\n" % str(AutoGenObject.Guid)) self.Progress.Stop("done!") if not autogen_rt: self.AutoGenMgr.TerminateWorkers() self.AutoGenMgr.join(1) raise FatalError(errorcode) AutoGenObject.CreateCodeFile(False) AutoGenObject.CreateMakeFile(False) else: # always recreate top/platform makefile when clean, just in case of inconsistency AutoGenObject.CreateCodeFile(True) AutoGenObject.CreateMakeFile(True) if EdkLogger.GetLevel() == EdkLogger.QUIET: EdkLogger.quiet("Building ... %s" % repr(AutoGenObject)) BuildCommand = AutoGenObject.BuildCommand if BuildCommand is None or len(BuildCommand) == 0: EdkLogger.error("build", OPTION_MISSING, "No build command found for this module. " "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." % (AutoGenObject.BuildTarget, AutoGenObject.ToolChain, AutoGenObject.Arch), ExtraData=str(AutoGenObject)) # run if Target == 'run': return True # build modules if BuildModule: BuildCommand = BuildCommand + [Target] LaunchCommand(BuildCommand, AutoGenObject.MakeFileDir) if GlobalData.gBinCacheDest: self.GenDestCache() elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: # Only for --hash # Update PreMakeCacheChain files self.GenLocalPreMakeCache() self.BuildModules = [] return True # build library if Target == 'libraries': DirList = [] for Lib in AutoGenObject.LibraryAutoGenList: if not Lib.IsBinaryModule: DirList.append((os.path.join(AutoGenObject.BuildDir, Lib.BuildDir),Lib)) for Lib, LibAutoGen in DirList: NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Lib, self.MakeFileName)), 'pbuild'] LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir,LibAutoGen) return True # build module if Target == 'modules': DirList = [] for Lib in AutoGenObject.LibraryAutoGenList: if not Lib.IsBinaryModule: DirList.append((os.path.join(AutoGenObject.BuildDir, Lib.BuildDir),Lib)) for Lib, LibAutoGen in DirList: NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Lib, self.MakeFileName)), 'pbuild'] LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir,LibAutoGen) DirList = [] for ModuleAutoGen in AutoGenObject.ModuleAutoGenList: if not ModuleAutoGen.IsBinaryModule: DirList.append((os.path.join(AutoGenObject.BuildDir, ModuleAutoGen.BuildDir),ModuleAutoGen)) for Mod,ModAutoGen in DirList: NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Mod, self.MakeFileName)), 'pbuild'] LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir,ModAutoGen) self.CreateAsBuiltInf() if GlobalData.gBinCacheDest: self.GenDestCache() elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: # Only for --hash # Update PreMakeCacheChain files self.GenLocalPreMakeCache() self.BuildModules = [] return True # cleanlib if Target == 'cleanlib': for Lib in AutoGenObject.LibraryBuildDirectoryList: LibMakefile = os.path.normpath(os.path.join(Lib, self.MakeFileName)) if os.path.exists(LibMakefile): NewBuildCommand = BuildCommand + ['-f', LibMakefile, 'cleanall'] LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir) return True # clean if Target == 'clean': for Mod in AutoGenObject.ModuleBuildDirectoryList: ModMakefile = os.path.normpath(os.path.join(Mod, self.MakeFileName)) if os.path.exists(ModMakefile): NewBuildCommand = BuildCommand + ['-f', ModMakefile, 'cleanall'] LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir) for Lib in AutoGenObject.LibraryBuildDirectoryList: LibMakefile = os.path.normpath(os.path.join(Lib, self.MakeFileName)) if os.path.exists(LibMakefile): NewBuildCommand = BuildCommand + ['-f', LibMakefile, 'cleanall'] LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir) return True # cleanall if Target == 'cleanall': try: #os.rmdir(AutoGenObject.BuildDir) RemoveDirectory(AutoGenObject.BuildDir, True) except WindowsError as X: EdkLogger.error("build", FILE_DELETE_FAILURE, ExtraData=str(X)) return True ## Build a module or platform # # Create autogen code and makefile for a module or platform, and the launch # "make" command to build it # # @param Target The target of build command # @param Platform The platform file # @param Module The module file # @param BuildTarget The name of build target, one of "DEBUG", "RELEASE" # @param ToolChain The name of toolchain to build # @param Arch The arch of the module/platform # @param CreateDepModuleCodeFile Flag used to indicate creating code # for dependent modules/Libraries # @param CreateDepModuleMakeFile Flag used to indicate creating makefile # for dependent modules/Libraries # def _Build(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMakeFile=True, BuildModule=False): if AutoGenObject is None: return False # skip file generation for cleanxxx targets, run and fds target if Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']: # for target which must generate AutoGen code and makefile if not self.SkipAutoGen or Target == 'genc': self.Progress.Start("Generating code") AutoGenObject.CreateCodeFile(CreateDepsCodeFile) self.Progress.Stop("done!") if Target == "genc": return True if not self.SkipAutoGen or Target == 'genmake': self.Progress.Start("Generating makefile") AutoGenObject.CreateMakeFile(CreateDepsMakeFile) #AutoGenObject.CreateAsBuiltInf() self.Progress.Stop("done!") if Target == "genmake": return True else: # always recreate top/platform makefile when clean, just in case of inconsistency AutoGenObject.CreateCodeFile(True) AutoGenObject.CreateMakeFile(True) if EdkLogger.GetLevel() == EdkLogger.QUIET: EdkLogger.quiet("Building ... %s" % repr(AutoGenObject)) BuildCommand = AutoGenObject.BuildCommand if BuildCommand is None or len(BuildCommand) == 0: EdkLogger.error("build", OPTION_MISSING, "No build command found for this module. " "Please check your setting of %s_%s_%s_MAKE_PATH in Conf/tools_def.txt file." % (AutoGenObject.BuildTarget, AutoGenObject.ToolChain, AutoGenObject.Arch), ExtraData=str(AutoGenObject)) # build modules if BuildModule: if Target != 'fds': BuildCommand = BuildCommand + [Target] AutoGenObject.BuildTime = LaunchCommand(BuildCommand, AutoGenObject.MakeFileDir) self.CreateAsBuiltInf() if GlobalData.gBinCacheDest: self.GenDestCache() elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: # Only for --hash # Update PreMakeCacheChain files self.GenLocalPreMakeCache() self.BuildModules = [] return True # genfds if Target == 'fds': if GenFdsApi(AutoGenObject.GenFdsCommandDict, self.Db): EdkLogger.error("build", COMMAND_FAILURE) Threshold = self.GetFreeSizeThreshold() if Threshold: self.CheckFreeSizeThreshold(Threshold, AutoGenObject.FvDir) return True # run if Target == 'run': return True # build library if Target == 'libraries': pass # not build modules # cleanall if Target == 'cleanall': try: #os.rmdir(AutoGenObject.BuildDir) RemoveDirectory(AutoGenObject.BuildDir, True) except WindowsError as X: EdkLogger.error("build", FILE_DELETE_FAILURE, ExtraData=str(X)) return True ## Rebase module image and Get function address for the input module list. # def _RebaseModule (self, MapBuffer, BaseAddress, ModuleList, AddrIsOffset = True, ModeIsSmm = False): if ModeIsSmm: AddrIsOffset = False for InfFile in ModuleList: sys.stdout.write (".") sys.stdout.flush() ModuleInfo = ModuleList[InfFile] ModuleName = ModuleInfo.BaseName ModuleOutputImage = ModuleInfo.Image.FileName ModuleDebugImage = os.path.join(ModuleInfo.DebugDir, ModuleInfo.BaseName + '.efi') ## for SMM module in SMRAM, the SMRAM will be allocated from base to top. if not ModeIsSmm: BaseAddress = BaseAddress - ModuleInfo.Image.Size # # Update Image to new BaseAddress by GenFw tool # LaunchCommand(["GenFw", "--rebase", str(BaseAddress), "-r", ModuleOutputImage], ModuleInfo.OutputDir) LaunchCommand(["GenFw", "--rebase", str(BaseAddress), "-r", ModuleDebugImage], ModuleInfo.DebugDir) else: # # Set new address to the section header only for SMM driver. # LaunchCommand(["GenFw", "--address", str(BaseAddress), "-r", ModuleOutputImage], ModuleInfo.OutputDir) LaunchCommand(["GenFw", "--address", str(BaseAddress), "-r", ModuleDebugImage], ModuleInfo.DebugDir) # # Collect function address from Map file # ImageMapTable = ModuleOutputImage.replace('.efi', '.map') FunctionList = [] if os.path.exists(ImageMapTable): OrigImageBaseAddress = 0 ImageMap = open(ImageMapTable, 'r') for LinStr in ImageMap: if len (LinStr.strip()) == 0: continue # # Get the preferred address set on link time. # if LinStr.find ('Preferred load address is') != -1: StrList = LinStr.split() OrigImageBaseAddress = int (StrList[len(StrList) - 1], 16) StrList = LinStr.split() if len (StrList) > 4: if StrList[3] == 'f' or StrList[3] == 'F': Name = StrList[1] RelativeAddress = int (StrList[2], 16) - OrigImageBaseAddress FunctionList.append ((Name, RelativeAddress)) ImageMap.close() # # Add general information. # if ModeIsSmm: MapBuffer.append('\n\n%s (Fixed SMRAM Offset, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint)) elif AddrIsOffset: MapBuffer.append('\n\n%s (Fixed Memory Offset, BaseAddress=-0x%010X, EntryPoint=-0x%010X)\n' % (ModuleName, 0 - BaseAddress, 0 - (BaseAddress + ModuleInfo.Image.EntryPoint))) else: MapBuffer.append('\n\n%s (Fixed Memory Address, BaseAddress=0x%010X, EntryPoint=0x%010X)\n' % (ModuleName, BaseAddress, BaseAddress + ModuleInfo.Image.EntryPoint)) # # Add guid and general seciton section. # TextSectionAddress = 0 DataSectionAddress = 0 for SectionHeader in ModuleInfo.Image.SectionHeaderList: if SectionHeader[0] == '.text': TextSectionAddress = SectionHeader[1] elif SectionHeader[0] in ['.data', '.sdata']: DataSectionAddress = SectionHeader[1] if AddrIsOffset: MapBuffer.append('(GUID=%s, .textbaseaddress=-0x%010X, .databaseaddress=-0x%010X)\n' % (ModuleInfo.Guid, 0 - (BaseAddress + TextSectionAddress), 0 - (BaseAddress + DataSectionAddress))) else: MapBuffer.append('(GUID=%s, .textbaseaddress=0x%010X, .databaseaddress=0x%010X)\n' % (ModuleInfo.Guid, BaseAddress + TextSectionAddress, BaseAddress + DataSectionAddress)) # # Add debug image full path. # MapBuffer.append('(IMAGE=%s)\n\n' % (ModuleDebugImage)) # # Add function address # for Function in FunctionList: if AddrIsOffset: MapBuffer.append(' -0x%010X %s\n' % (0 - (BaseAddress + Function[1]), Function[0])) else: MapBuffer.append(' 0x%010X %s\n' % (BaseAddress + Function[1], Function[0])) ImageMap.close() # # for SMM module in SMRAM, the SMRAM will be allocated from base to top. # if ModeIsSmm: BaseAddress = BaseAddress + ModuleInfo.Image.Size ## Collect MAP information of all FVs # def _CollectFvMapBuffer (self, MapBuffer, Wa, ModuleList): if self.Fdf: # First get the XIP base address for FV map file. GuidPattern = re.compile("[-a-fA-F0-9]+") GuidName = re.compile(r"\(GUID=[-a-fA-F0-9]+") for FvName in Wa.FdfProfile.FvDict: FvMapBuffer = os.path.join(Wa.FvDir, FvName + '.Fv.map') if not os.path.exists(FvMapBuffer): continue FvMap = open(FvMapBuffer, 'r') #skip FV size information FvMap.readline() FvMap.readline() FvMap.readline() FvMap.readline() for Line in FvMap: MatchGuid = GuidPattern.match(Line) if MatchGuid is not None: # # Replace GUID with module name # GuidString = MatchGuid.group() if GuidString.upper() in ModuleList: Line = Line.replace(GuidString, ModuleList[GuidString.upper()].Name) MapBuffer.append(Line) # # Add the debug image full path. # MatchGuid = GuidName.match(Line) if MatchGuid is not None: GuidString = MatchGuid.group().split("=")[1] if GuidString.upper() in ModuleList: MapBuffer.append('(IMAGE=%s)\n' % (os.path.join(ModuleList[GuidString.upper()].DebugDir, ModuleList[GuidString.upper()].Name + '.efi'))) FvMap.close() ## Collect MAP information of all modules # def _CollectModuleMapBuffer (self, MapBuffer, ModuleList): sys.stdout.write ("Generate Load Module At Fix Address Map") sys.stdout.flush() PatchEfiImageList = [] PeiModuleList = {} BtModuleList = {} RtModuleList = {} SmmModuleList = {} PeiSize = 0 BtSize = 0 RtSize = 0 # reserve 4K size in SMRAM to make SMM module address not from 0. SmmSize = 0x1000 for ModuleGuid in ModuleList: Module = ModuleList[ModuleGuid] GlobalData.gProcessingFile = "%s [%s, %s, %s]" % (Module.MetaFile, Module.Arch, Module.ToolChain, Module.BuildTarget) OutputImageFile = '' for ResultFile in Module.CodaTargetList: if str(ResultFile.Target).endswith('.efi'): # # module list for PEI, DXE, RUNTIME and SMM # OutputImageFile = os.path.join(Module.OutputDir, Module.Name + '.efi') ImageClass = PeImageClass (OutputImageFile) if not ImageClass.IsValid: EdkLogger.error("build", FILE_PARSE_FAILURE, ExtraData=ImageClass.ErrorInfo) ImageInfo = PeImageInfo(Module.Name, Module.Guid, Module.Arch, Module.OutputDir, Module.DebugDir, ImageClass) if Module.ModuleType in [SUP_MODULE_PEI_CORE, SUP_MODULE_PEIM, EDK_COMPONENT_TYPE_COMBINED_PEIM_DRIVER, EDK_COMPONENT_TYPE_PIC_PEIM, EDK_COMPONENT_TYPE_RELOCATABLE_PEIM, SUP_MODULE_DXE_CORE]: PeiModuleList[Module.MetaFile] = ImageInfo PeiSize += ImageInfo.Image.Size elif Module.ModuleType in [EDK_COMPONENT_TYPE_BS_DRIVER, SUP_MODULE_DXE_DRIVER, SUP_MODULE_UEFI_DRIVER]: BtModuleList[Module.MetaFile] = ImageInfo BtSize += ImageInfo.Image.Size elif Module.ModuleType in [SUP_MODULE_DXE_RUNTIME_DRIVER, EDK_COMPONENT_TYPE_RT_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, EDK_COMPONENT_TYPE_SAL_RT_DRIVER]: RtModuleList[Module.MetaFile] = ImageInfo RtSize += ImageInfo.Image.Size elif Module.ModuleType in [SUP_MODULE_SMM_CORE, SUP_MODULE_DXE_SMM_DRIVER, SUP_MODULE_MM_STANDALONE, SUP_MODULE_MM_CORE_STANDALONE]: SmmModuleList[Module.MetaFile] = ImageInfo SmmSize += ImageInfo.Image.Size if Module.ModuleType == SUP_MODULE_DXE_SMM_DRIVER: PiSpecVersion = Module.Module.Specification.get('PI_SPECIFICATION_VERSION', '0x00000000') # for PI specification < PI1.1, DXE_SMM_DRIVER also runs as BOOT time driver. if int(PiSpecVersion, 16) < 0x0001000A: BtModuleList[Module.MetaFile] = ImageInfo BtSize += ImageInfo.Image.Size break # # EFI image is final target. # Check EFI image contains patchable FixAddress related PCDs. # if OutputImageFile != '': ModuleIsPatch = False for Pcd in Module.ModulePcdList: if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE and Pcd.TokenCName in TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SET: ModuleIsPatch = True break if not ModuleIsPatch: for Pcd in Module.LibraryPcdList: if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE and Pcd.TokenCName in TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SET: ModuleIsPatch = True break if not ModuleIsPatch: continue # # Module includes the patchable load fix address PCDs. # It will be fixed up later. # PatchEfiImageList.append (OutputImageFile) # # Get Top Memory address # ReservedRuntimeMemorySize = 0 TopMemoryAddress = 0 if self.LoadFixAddress == 0xFFFFFFFFFFFFFFFF: TopMemoryAddress = 0 else: TopMemoryAddress = self.LoadFixAddress if TopMemoryAddress < RtSize + BtSize + PeiSize: EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS is too low to load driver") # # Patch FixAddress related PCDs into EFI image # for EfiImage in PatchEfiImageList: EfiImageMap = EfiImage.replace('.efi', '.map') if not os.path.exists(EfiImageMap): continue # # Get PCD offset in EFI image by GenPatchPcdTable function # PcdTable = parsePcdInfoFromMapFile(EfiImageMap, EfiImage) # # Patch real PCD value by PatchPcdValue tool # for PcdInfo in PcdTable: ReturnValue = 0 if PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE: ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE_DATA_TYPE, str (PeiSize // 0x1000)) elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_DXE_PAGE_SIZE: ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_DXE_PAGE_SIZE_DATA_TYPE, str (BtSize // 0x1000)) elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_RUNTIME_PAGE_SIZE: ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_RUNTIME_PAGE_SIZE_DATA_TYPE, str (RtSize // 0x1000)) elif PcdInfo[0] == TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SMM_PAGE_SIZE and len (SmmModuleList) > 0: ReturnValue, ErrorInfo = PatchBinaryFile (EfiImage, PcdInfo[1], TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SMM_PAGE_SIZE_DATA_TYPE, str (SmmSize // 0x1000)) if ReturnValue != 0: EdkLogger.error("build", PARAMETER_INVALID, "Patch PCD value failed", ExtraData=ErrorInfo) MapBuffer.append('PEI_CODE_PAGE_NUMBER = 0x%x\n' % (PeiSize // 0x1000)) MapBuffer.append('BOOT_CODE_PAGE_NUMBER = 0x%x\n' % (BtSize // 0x1000)) MapBuffer.append('RUNTIME_CODE_PAGE_NUMBER = 0x%x\n' % (RtSize // 0x1000)) if len (SmmModuleList) > 0: MapBuffer.append('SMM_CODE_PAGE_NUMBER = 0x%x\n' % (SmmSize // 0x1000)) PeiBaseAddr = TopMemoryAddress - RtSize - BtSize BtBaseAddr = TopMemoryAddress - RtSize RtBaseAddr = TopMemoryAddress - ReservedRuntimeMemorySize self._RebaseModule (MapBuffer, PeiBaseAddr, PeiModuleList, TopMemoryAddress == 0) self._RebaseModule (MapBuffer, BtBaseAddr, BtModuleList, TopMemoryAddress == 0) self._RebaseModule (MapBuffer, RtBaseAddr, RtModuleList, TopMemoryAddress == 0) self._RebaseModule (MapBuffer, 0x1000, SmmModuleList, AddrIsOffset=False, ModeIsSmm=True) MapBuffer.append('\n\n') sys.stdout.write ("\n") sys.stdout.flush() ## Save platform Map file # def _SaveMapFile (self, MapBuffer, Wa): # # Map file path is got. # MapFilePath = os.path.join(Wa.BuildDir, Wa.Name + '.map') # # Save address map into MAP file. # SaveFileOnChange(MapFilePath, ''.join(MapBuffer), False) if self.LoadFixAddress != 0: sys.stdout.write ("\nLoad Module At Fix Address Map file can be found at %s\n" % (MapFilePath)) sys.stdout.flush() ## Build active platform for different build targets and different tool chains # def _BuildPlatform(self): SaveFileOnChange(self.PlatformBuildPath, '# DO NOT EDIT \n# FILE auto-generated\n', False) for BuildTarget in self.BuildTargetList: GlobalData.gGlobalDefines['TARGET'] = BuildTarget index = 0 for ToolChain in self.ToolChainList: GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain GlobalData.gGlobalDefines['FAMILY'] = self.ToolChainFamily[index] index += 1 Wa = WorkspaceAutoGen( self.WorkspaceDir, self.PlatformFile, BuildTarget, ToolChain, self.ArchList, self.BuildDatabase, self.TargetTxt, self.ToolDef, self.Fdf, self.FdList, self.FvList, self.CapList, self.SkuId, self.UniFlag, self.Progress ) self.Fdf = Wa.FdfFile self.LoadFixAddress = Wa.Platform.LoadFixAddress self.BuildReport.AddPlatformReport(Wa) self.Progress.Stop("done!") # Add ffs build to makefile CmdListDict = {} if GlobalData.gEnableGenfdsMultiThread and self.Fdf: CmdListDict = self._GenFfsCmd(Wa.ArchList) for Arch in Wa.ArchList: PcdMaList = [] GlobalData.gGlobalDefines['ARCH'] = Arch Pa = PlatformAutoGen(Wa, self.PlatformFile, BuildTarget, ToolChain, Arch) for Module in Pa.Platform.Modules: # Get ModuleAutoGen object to generate C code file and makefile Ma = ModuleAutoGen(Wa, Module, BuildTarget, ToolChain, Arch, self.PlatformFile,Pa.DataPipe) if Ma is None: continue if Ma.PcdIsDriver: Ma.PlatformInfo = Pa Ma.Workspace = Wa PcdMaList.append(Ma) self.BuildModules.append(Ma) Pa.DataPipe.DataContainer = {"FfsCommand":CmdListDict} Pa.DataPipe.DataContainer = {"Workspace_timestamp": Wa._SrcTimeStamp} self._BuildPa(self.Target, Pa, FfsCommand=CmdListDict,PcdMaList=PcdMaList) # Create MAP file when Load Fix Address is enabled. if self.Target in ["", "all", "fds"]: for Arch in Wa.ArchList: GlobalData.gGlobalDefines['ARCH'] = Arch # # Check whether the set fix address is above 4G for 32bit image. # if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000: EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS can't be set to larger than or equal to 4G for the platform with IA32 or ARM arch modules") # # Get Module List # ModuleList = {} for Pa in Wa.AutoGenObjectList: for Ma in Pa.ModuleAutoGenList: if Ma is None: continue if not Ma.IsLibrary: ModuleList[Ma.Guid.upper()] = Ma MapBuffer = [] if self.LoadFixAddress != 0: # # Rebase module to the preferred memory address before GenFds # self._CollectModuleMapBuffer(MapBuffer, ModuleList) if self.Fdf: # # create FDS again for the updated EFI image # self._Build("fds", Wa) # # Create MAP file for all platform FVs after GenFds. # self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList) # # Save MAP buffer into MAP file. # self._SaveMapFile (MapBuffer, Wa) self.CreateGuidedSectionToolsFile(Wa) ## Build active module for different build targets, different tool chains and different archs # def _BuildModule(self): for BuildTarget in self.BuildTargetList: GlobalData.gGlobalDefines['TARGET'] = BuildTarget index = 0 for ToolChain in self.ToolChainList: WorkspaceAutoGenTime = time.time() GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain GlobalData.gGlobalDefines['FAMILY'] = self.ToolChainFamily[index] index += 1 # # module build needs platform build information, so get platform # AutoGen first # Wa = WorkspaceAutoGen( self.WorkspaceDir, self.PlatformFile, BuildTarget, ToolChain, self.ArchList, self.BuildDatabase, self.TargetTxt, self.ToolDef, self.Fdf, self.FdList, self.FvList, self.CapList, self.SkuId, self.UniFlag, self.Progress, self.ModuleFile ) self.Fdf = Wa.FdfFile self.LoadFixAddress = Wa.Platform.LoadFixAddress Wa.CreateMakeFile(False) # Add ffs build to makefile CmdListDict = None if GlobalData.gEnableGenfdsMultiThread and self.Fdf: CmdListDict = self._GenFfsCmd(Wa.ArchList) GlobalData.file_lock = mp.Lock() GlobalData.FfsCmd = CmdListDict self.Progress.Stop("done!") MaList = [] ExitFlag = threading.Event() ExitFlag.clear() self.AutoGenTime += int(round((time.time() - WorkspaceAutoGenTime))) for Arch in Wa.ArchList: AutoGenStart = time.time() GlobalData.gGlobalDefines['ARCH'] = Arch Pa = PlatformAutoGen(Wa, self.PlatformFile, BuildTarget, ToolChain, Arch) for Module in Pa.Platform.Modules: if self.ModuleFile.Dir == Module.Dir and self.ModuleFile.Name == Module.Name: Ma = ModuleAutoGen(Wa, Module, BuildTarget, ToolChain, Arch, self.PlatformFile,Pa.DataPipe) if Ma is None: continue if Ma.PcdIsDriver: Ma.PlatformInfo = Pa Ma.Workspace = Wa MaList.append(Ma) if GlobalData.gUseHashCache and not GlobalData.gBinCacheDest and self.Target in [None, "", "all"]: if Ma.CanSkipbyPreMakeCache(): continue else: self.PreMakeCacheMiss.add(Ma) # Not to auto-gen for targets 'clean', 'cleanlib', 'cleanall', 'run', 'fds' if self.Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']: # for target which must generate AutoGen code and makefile if not self.SkipAutoGen or self.Target == 'genc': self.Progress.Start("Generating code") Ma.CreateCodeFile(True) self.Progress.Stop("done!") if self.Target == "genc": return True if not self.SkipAutoGen or self.Target == 'genmake': self.Progress.Start("Generating makefile") if CmdListDict and self.Fdf and (Module.Path, Arch) in CmdListDict: Ma.CreateMakeFile(True, CmdListDict[Module.Path, Arch]) del CmdListDict[Module.Path, Arch] else: Ma.CreateMakeFile(True) self.Progress.Stop("done!") if self.Target == "genmake": return True if GlobalData.gBinCacheSource and self.Target in [None, "", "all"]: if Ma.CanSkipbyMakeCache(): continue else: self.MakeCacheMiss.add(Ma) self.BuildModules.append(Ma) self.AutoGenTime += int(round((time.time() - AutoGenStart))) MakeStart = time.time() for Ma in self.BuildModules: if not Ma.IsBinaryModule: Bt = BuildTask.New(ModuleMakeUnit(Ma, Pa.BuildCommand,self.Target)) # Break build if any build thread has error if BuildTask.HasError(): # we need a full version of makefile for platform ExitFlag.set() BuildTask.WaitForComplete() Pa.CreateMakeFile(False) EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) # Start task scheduler if not BuildTask.IsOnGoing(): BuildTask.StartScheduler(self.ThreadNumber, ExitFlag) # in case there's an interruption. we need a full version of makefile for platform Pa.CreateMakeFile(False) if BuildTask.HasError(): EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) self.MakeTime += int(round((time.time() - MakeStart))) MakeContiue = time.time() ExitFlag.set() BuildTask.WaitForComplete() self.CreateAsBuiltInf() if GlobalData.gBinCacheDest: self.GenDestCache() elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: # Only for --hash # Update PreMakeCacheChain files self.GenLocalPreMakeCache() self.BuildModules = [] self.MakeTime += int(round((time.time() - MakeContiue))) if BuildTask.HasError(): EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) self.BuildReport.AddPlatformReport(Wa, MaList) if MaList == []: EdkLogger.error( 'build', BUILD_ERROR, "Module for [%s] is not a component of active platform."\ " Please make sure that the ARCH and inf file path are"\ " given in the same as in [%s]" % \ (', '.join(Wa.ArchList), self.PlatformFile), ExtraData=self.ModuleFile ) # Create MAP file when Load Fix Address is enabled. if self.Target == "fds" and self.Fdf: for Arch in Wa.ArchList: # # Check whether the set fix address is above 4G for 32bit image. # if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000: EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS can't be set to larger than or equal to 4G for the platorm with IA32 or ARM arch modules") # # Get Module List # ModuleList = {} for Pa in Wa.AutoGenObjectList: for Ma in Pa.ModuleAutoGenList: if Ma is None: continue if not Ma.IsLibrary: ModuleList[Ma.Guid.upper()] = Ma MapBuffer = [] if self.LoadFixAddress != 0: # # Rebase module to the preferred memory address before GenFds # self._CollectModuleMapBuffer(MapBuffer, ModuleList) # # create FDS again for the updated EFI image # GenFdsStart = time.time() self._Build("fds", Wa) self.GenFdsTime += int(round((time.time() - GenFdsStart))) # # Create MAP file for all platform FVs after GenFds. # self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList) # # Save MAP buffer into MAP file. # self._SaveMapFile (MapBuffer, Wa) def _GenFfsCmd(self,ArchList): # convert dictionary of Cmd:(Inf,Arch) # to a new dictionary of (Inf,Arch):Cmd,Cmd,Cmd... CmdSetDict = defaultdict(set) GenFfsDict = GenFds.GenFfsMakefile('', GlobalData.gFdfParser, self, ArchList, GlobalData) for Cmd in GenFfsDict: tmpInf, tmpArch = GenFfsDict[Cmd] CmdSetDict[tmpInf, tmpArch].add(Cmd) return CmdSetDict def VerifyAutoGenFiles(self): AutoGenIdFile = os.path.join(GlobalData.gConfDirectory,".AutoGenIdFile.txt") try: with open(AutoGenIdFile) as fd: lines = fd.readlines() except: return None for line in lines: if "Arch" in line: ArchList = line.strip().split("=")[1].split("|") if "BuildDir" in line: BuildDir = line.split("=")[1].strip() if "PlatformGuid" in line: PlatformGuid = line.split("=")[1].strip() GlobalVarList = [] for arch in ArchList: global_var = os.path.join(BuildDir, "GlobalVar_%s_%s.bin" % (str(PlatformGuid),arch)) if not os.path.exists(global_var): return None GlobalVarList.append(global_var) for global_var in GlobalVarList: data_pipe = MemoryDataPipe() data_pipe.load(global_var) target = data_pipe.Get("P_Info").get("Target") toolchain = data_pipe.Get("P_Info").get("ToolChain") archlist = data_pipe.Get("P_Info").get("ArchList") Arch = data_pipe.Get("P_Info").get("Arch") active_p = data_pipe.Get("P_Info").get("ActivePlatform") workspacedir = data_pipe.Get("P_Info").get("WorkspaceDir") PackagesPath = os.getenv("PACKAGES_PATH") mws.setWs(workspacedir, PackagesPath) LibraryBuildDirectoryList = data_pipe.Get("LibraryBuildDirectoryList") ModuleBuildDirectoryList = data_pipe.Get("ModuleBuildDirectoryList") for m_build_dir in LibraryBuildDirectoryList: if not os.path.exists(os.path.join(m_build_dir,self.MakeFileName)): return None for m_build_dir in ModuleBuildDirectoryList: if not os.path.exists(os.path.join(m_build_dir,self.MakeFileName)): return None Wa = WorkSpaceInfo( workspacedir,active_p,target,toolchain,archlist ) Pa = PlatformInfo(Wa, active_p, target, toolchain, Arch,data_pipe) Wa.AutoGenObjectList.append(Pa) return Wa def SetupMakeSetting(self,Wa): BuildModules = [] for Pa in Wa.AutoGenObjectList: for m in Pa._MbList: ma = ModuleAutoGen(Wa,m.MetaFile, Pa.BuildTarget, Wa.ToolChain, Pa.Arch, Pa.MetaFile,Pa.DataPipe) BuildModules.append(ma) fdf_file = Wa.FlashDefinition if fdf_file: Fdf = FdfParser(fdf_file.Path) Fdf.ParseFile() GlobalData.gFdfParser = Fdf if Fdf.CurrentFdName and Fdf.CurrentFdName in Fdf.Profile.FdDict: FdDict = Fdf.Profile.FdDict[Fdf.CurrentFdName] for FdRegion in FdDict.RegionList: if str(FdRegion.RegionType) == 'FILE' and self.Platform.VpdToolGuid in str(FdRegion.RegionDataList): if int(FdRegion.Offset) % 8 != 0: EdkLogger.error("build", FORMAT_INVALID, 'The VPD Base Address %s must be 8-byte aligned.' % (FdRegion.Offset)) Wa.FdfProfile = Fdf.Profile self.Fdf = Fdf else: self.Fdf = None return BuildModules ## Build a platform in multi-thread mode # def PerformAutoGen(self,BuildTarget,ToolChain): WorkspaceAutoGenTime = time.time() Wa = WorkspaceAutoGen( self.WorkspaceDir, self.PlatformFile, BuildTarget, ToolChain, self.ArchList, self.BuildDatabase, self.TargetTxt, self.ToolDef, self.Fdf, self.FdList, self.FvList, self.CapList, self.SkuId, self.UniFlag, self.Progress ) self.Fdf = Wa.FdfFile self.LoadFixAddress = Wa.Platform.LoadFixAddress self.BuildReport.AddPlatformReport(Wa) Wa.CreateMakeFile(False) # Add ffs build to makefile CmdListDict = {} if GlobalData.gEnableGenfdsMultiThread and self.Fdf: CmdListDict = self._GenFfsCmd(Wa.ArchList) self.AutoGenTime += int(round((time.time() - WorkspaceAutoGenTime))) BuildModules = [] for Arch in Wa.ArchList: PcdMaList = [] AutoGenStart = time.time() GlobalData.gGlobalDefines['ARCH'] = Arch Pa = PlatformAutoGen(Wa, self.PlatformFile, BuildTarget, ToolChain, Arch) if Pa is None: continue ModuleList = [] for Inf in Pa.Platform.Modules: ModuleList.append(Inf) # Add the INF only list in FDF if GlobalData.gFdfParser is not None: for InfName in GlobalData.gFdfParser.Profile.InfList: Inf = PathClass(NormPath(InfName), self.WorkspaceDir, Arch) if Inf in Pa.Platform.Modules: continue ModuleList.append(Inf) Pa.DataPipe.DataContainer = {"FfsCommand":CmdListDict} Pa.DataPipe.DataContainer = {"Workspace_timestamp": Wa._SrcTimeStamp} Pa.DataPipe.DataContainer = {"CommandTarget": self.Target} Pa.CreateLibModuelDirs() # Fetch the MakeFileName. self.MakeFileName = Pa.MakeFileName if not self.MakeFileName: self.MakeFileName = Pa.MakeFile Pa.DataPipe.DataContainer = {"LibraryBuildDirectoryList":Pa.LibraryBuildDirectoryList} Pa.DataPipe.DataContainer = {"ModuleBuildDirectoryList":Pa.ModuleBuildDirectoryList} Pa.DataPipe.DataContainer = {"FdsCommandDict": Wa.GenFdsCommandDict} # Prepare the cache share data for multiprocessing Pa.DataPipe.DataContainer = {"gPlatformHashFile":GlobalData.gPlatformHashFile} ModuleCodaFile = {} for ma in Pa.ModuleAutoGenList: ModuleCodaFile[(ma.MetaFile.File,ma.MetaFile.Root,ma.Arch,ma.MetaFile.Path)] = [item.Target for item in ma.CodaTargetList] Pa.DataPipe.DataContainer = {"ModuleCodaFile":ModuleCodaFile} # ModuleList contains all driver modules only for Module in ModuleList: # Get ModuleAutoGen object to generate C code file and makefile Ma = ModuleAutoGen(Wa, Module, BuildTarget, ToolChain, Arch, self.PlatformFile,Pa.DataPipe) if Ma is None: continue if Ma.PcdIsDriver: Ma.PlatformInfo = Pa Ma.Workspace = Wa PcdMaList.append(Ma) self.AllDrivers.add(Ma) self.AllModules.add(Ma) mqueue = mp.Queue() cqueue = mp.Queue() for m in Pa.GetAllModuleInfo: mqueue.put(m) module_file,module_root,module_path,module_basename,\ module_originalpath,module_arch,IsLib = m Ma = ModuleAutoGen(Wa, PathClass(module_path, Wa), BuildTarget,\ ToolChain, Arch, self.PlatformFile,Pa.DataPipe) self.AllModules.add(Ma) data_pipe_file = os.path.join(Pa.BuildDir, "GlobalVar_%s_%s.bin" % (str(Pa.Guid),Pa.Arch)) Pa.DataPipe.dump(data_pipe_file) mqueue.put((None,None,None,None,None,None,None)) autogen_rt, errorcode = self.StartAutoGen(mqueue, Pa.DataPipe, self.SkipAutoGen, PcdMaList, cqueue) if not autogen_rt: self.AutoGenMgr.TerminateWorkers() self.AutoGenMgr.join(1) raise FatalError(errorcode) if GlobalData.gUseHashCache: for item in GlobalData.gModuleAllCacheStatus: (MetaFilePath, Arch, CacheStr, Status) = item Ma = ModuleAutoGen(Wa, PathClass(MetaFilePath, Wa), BuildTarget,\ ToolChain, Arch, self.PlatformFile,Pa.DataPipe) if CacheStr == "PreMakeCache" and Status == False: self.PreMakeCacheMiss.add(Ma) if CacheStr == "PreMakeCache" and Status == True: self.PreMakeCacheHit.add(Ma) GlobalData.gModuleCacheHit.add(Ma) if CacheStr == "MakeCache" and Status == False: self.MakeCacheMiss.add(Ma) if CacheStr == "MakeCache" and Status == True: self.MakeCacheHit.add(Ma) GlobalData.gModuleCacheHit.add(Ma) self.AutoGenTime += int(round((time.time() - AutoGenStart))) AutoGenIdFile = os.path.join(GlobalData.gConfDirectory,".AutoGenIdFile.txt") with open(AutoGenIdFile,"w") as fw: fw.write("Arch=%s\n" % "|".join((Wa.ArchList))) fw.write("BuildDir=%s\n" % Wa.BuildDir) fw.write("PlatformGuid=%s\n" % str(Wa.AutoGenObjectList[0].Guid)) if GlobalData.gBinCacheSource: BuildModules.extend(self.MakeCacheMiss) elif GlobalData.gUseHashCache and not GlobalData.gBinCacheDest: BuildModules.extend(self.PreMakeCacheMiss) else: BuildModules.extend(self.AllDrivers) self.Progress.Stop("done!") return Wa, BuildModules def _MultiThreadBuildPlatform(self): SaveFileOnChange(self.PlatformBuildPath, '# DO NOT EDIT \n# FILE auto-generated\n', False) for BuildTarget in self.BuildTargetList: GlobalData.gGlobalDefines['TARGET'] = BuildTarget index = 0 for ToolChain in self.ToolChainList: resetFdsGlobalVariable() GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain GlobalData.gGlobalDefines['FAMILY'] = self.ToolChainFamily[index] index += 1 ExitFlag = threading.Event() ExitFlag.clear() if self.SkipAutoGen: Wa = self.VerifyAutoGenFiles() if Wa is None: self.SkipAutoGen = False Wa, self.BuildModules = self.PerformAutoGen(BuildTarget,ToolChain) else: GlobalData.gAutoGenPhase = True self.BuildModules = self.SetupMakeSetting(Wa) else: Wa, self.BuildModules = self.PerformAutoGen(BuildTarget,ToolChain) Pa = Wa.AutoGenObjectList[0] GlobalData.gAutoGenPhase = False if GlobalData.gBinCacheSource: EdkLogger.quiet("[cache Summary]: Total module num: %s" % len(self.AllModules)) EdkLogger.quiet("[cache Summary]: PreMakecache miss num: %s " % len(self.PreMakeCacheMiss)) EdkLogger.quiet("[cache Summary]: Makecache miss num: %s " % len(self.MakeCacheMiss)) for Arch in Wa.ArchList: MakeStart = time.time() for Ma in set(self.BuildModules): # Generate build task for the module if not Ma.IsBinaryModule: Bt = BuildTask.New(ModuleMakeUnit(Ma, Pa.BuildCommand,self.Target)) # Break build if any build thread has error if BuildTask.HasError(): # we need a full version of makefile for platform ExitFlag.set() BuildTask.WaitForComplete() Pa.CreateMakeFile(False) EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) # Start task scheduler if not BuildTask.IsOnGoing(): BuildTask.StartScheduler(self.ThreadNumber, ExitFlag) # in case there's an interruption. we need a full version of makefile for platform if BuildTask.HasError(): EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) self.MakeTime += int(round((time.time() - MakeStart))) MakeContiue = time.time() # # # All modules have been put in build tasks queue. Tell task scheduler # to exit if all tasks are completed # ExitFlag.set() BuildTask.WaitForComplete() if GlobalData.gBinCacheDest: self.GenDestCache() elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: # Only for --hash # Update PreMakeCacheChain files self.GenLocalPreMakeCache() # # Get Module List # ModuleList = {ma.Guid.upper(): ma for ma in self.BuildModules} self.BuildModules = [] self.MakeTime += int(round((time.time() - MakeContiue))) # # Check for build error, and raise exception if one # has been signaled. # if BuildTask.HasError(): EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) # Create MAP file when Load Fix Address is enabled. if self.Target in ["", "all", "fds"]: for Arch in Wa.ArchList: # # Check whether the set fix address is above 4G for 32bit image. # if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000: EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS can't be set to larger than or equal to 4G for the platorm with IA32 or ARM arch modules") # # Rebase module to the preferred memory address before GenFds # MapBuffer = [] if self.LoadFixAddress != 0: self._CollectModuleMapBuffer(MapBuffer, ModuleList) if self.Fdf: # # Generate FD image if there's a FDF file found # GenFdsStart = time.time() if GenFdsApi(Wa.GenFdsCommandDict, self.Db): EdkLogger.error("build", COMMAND_FAILURE) Threshold = self.GetFreeSizeThreshold() if Threshold: self.CheckFreeSizeThreshold(Threshold, Wa.FvDir) # # Create MAP file for all platform FVs after GenFds. # self._CollectFvMapBuffer(MapBuffer, Wa, ModuleList) self.GenFdsTime += int(round((time.time() - GenFdsStart))) # # Save MAP buffer into MAP file. # self._SaveMapFile(MapBuffer, Wa) self.CreateGuidedSectionToolsFile(Wa) ## GetFreeSizeThreshold() # # @retval int Threshold value # def GetFreeSizeThreshold(self): Threshold = None Threshold_Str = GlobalData.gCommandLineDefines.get('FV_SPARE_SPACE_THRESHOLD') if Threshold_Str: try: if Threshold_Str.lower().startswith('0x'): Threshold = int(Threshold_Str, 16) else: Threshold = int(Threshold_Str) except: EdkLogger.warn("build", 'incorrect value for FV_SPARE_SPACE_THRESHOLD %s.Only decimal or hex format is allowed.' % Threshold_Str) return Threshold def CheckFreeSizeThreshold(self, Threshold=None, FvDir=None): if not isinstance(Threshold, int): return if not isinstance(FvDir, str) or not FvDir: return FdfParserObject = GlobalData.gFdfParser FvRegionNameList = [FvName for FvName in FdfParserObject.Profile.FvDict if FdfParserObject.Profile.FvDict[FvName].FvRegionInFD] for FvName in FdfParserObject.Profile.FvDict: if FvName in FvRegionNameList: FvSpaceInfoFileName = os.path.join(FvDir, FvName.upper() + '.Fv.map') if os.path.exists(FvSpaceInfoFileName): FileLinesList = getlines(FvSpaceInfoFileName) for Line in FileLinesList: NameValue = Line.split('=') if len(NameValue) == 2 and NameValue[0].strip() == 'EFI_FV_SPACE_SIZE': FreeSizeValue = int(NameValue[1].strip(), 0) if FreeSizeValue < Threshold: EdkLogger.error("build", FV_FREESIZE_ERROR, '%s FV free space %d is not enough to meet with the required spare space %d set by -D FV_SPARE_SPACE_THRESHOLD option.' % ( FvName, FreeSizeValue, Threshold)) break ## Generate GuidedSectionTools.txt in the FV directories. # def CreateGuidedSectionToolsFile(self,Wa): for BuildTarget in self.BuildTargetList: for ToolChain in self.ToolChainList: FvDir = Wa.FvDir if not os.path.exists(FvDir): continue for Arch in self.ArchList: guidList = [] tooldefguidList = [] guidAttribs = [] for Platform in Wa.AutoGenObjectList: if Platform.BuildTarget != BuildTarget: continue if Platform.ToolChain != ToolChain: continue if Platform.Arch != Arch: continue if hasattr (Platform, 'BuildOption'): for Tool in Platform.BuildOption: if 'GUID' in Platform.BuildOption[Tool]: if 'PATH' in Platform.BuildOption[Tool]: value = Platform.BuildOption[Tool]['GUID'] if value in guidList: EdkLogger.error("build", FORMAT_INVALID, "Duplicate GUID value %s used with Tool %s in DSC [BuildOptions]." % (value, Tool)) path = Platform.BuildOption[Tool]['PATH'] guidList.append(value) guidAttribs.append((value, Tool, path)) for Tool in Platform.ToolDefinition: if 'GUID' in Platform.ToolDefinition[Tool]: if 'PATH' in Platform.ToolDefinition[Tool]: value = Platform.ToolDefinition[Tool]['GUID'] if value in tooldefguidList: EdkLogger.error("build", FORMAT_INVALID, "Duplicate GUID value %s used with Tool %s in tools_def.txt." % (value, Tool)) tooldefguidList.append(value) if value in guidList: # Already added by platform continue path = Platform.ToolDefinition[Tool]['PATH'] guidList.append(value) guidAttribs.append((value, Tool, path)) # Sort by GuidTool name guidAttribs = sorted (guidAttribs, key=lambda x: x[1]) # Write out GuidedSecTools.txt toolsFile = os.path.join(FvDir, 'GuidedSectionTools.txt') toolsFile = open(toolsFile, 'wt') for guidedSectionTool in guidAttribs: print(' '.join(guidedSectionTool), file=toolsFile) toolsFile.close() ## Returns the real path of the tool. # def GetRealPathOfTool (self, tool): if os.path.exists(tool): return os.path.realpath(tool) return tool ## Launch the module or platform build # def Launch(self): self.AllDrivers = set() self.AllModules = set() self.PreMakeCacheMiss = set() self.PreMakeCacheHit = set() self.MakeCacheMiss = set() self.MakeCacheHit = set() if not self.ModuleFile: if not self.SpawnMode or self.Target not in ["", "all"]: self.SpawnMode = False self._BuildPlatform() else: self._MultiThreadBuildPlatform() else: self.SpawnMode = False self._BuildModule() if self.Target == 'cleanall': RemoveDirectory(os.path.dirname(GlobalData.gDatabasePath), True) def CreateAsBuiltInf(self): for Module in self.BuildModules: Module.CreateAsBuiltInf() def GenDestCache(self): for Module in self.AllModules: Module.GenPreMakefileHashList() Module.GenMakefileHashList() Module.CopyModuleToCache() def GenLocalPreMakeCache(self): for Module in self.PreMakeCacheMiss: Module.GenPreMakefileHashList() ## Do some clean-up works when error occurred def Relinquish(self): OldLogLevel = EdkLogger.GetLevel() EdkLogger.SetLevel(EdkLogger.ERROR) Utils.Progressor.Abort() if self.SpawnMode == True: BuildTask.Abort() EdkLogger.SetLevel(OldLogLevel) def ParseDefines(DefineList=[]): DefineDict = {} if DefineList is not None: for Define in DefineList: DefineTokenList = Define.split("=", 1) if not GlobalData.gMacroNamePattern.match(DefineTokenList[0]): EdkLogger.error('build', FORMAT_INVALID, "The macro name must be in the pattern [A-Z][A-Z0-9_]*", ExtraData=DefineTokenList[0]) if len(DefineTokenList) == 1: DefineDict[DefineTokenList[0]] = "TRUE" else: DefineDict[DefineTokenList[0]] = DefineTokenList[1].strip() return DefineDict def LogBuildTime(Time): if Time: TimeDurStr = '' TimeDur = time.gmtime(Time) if TimeDur.tm_yday > 1: TimeDurStr = time.strftime("%H:%M:%S", TimeDur) + ", %d day(s)" % (TimeDur.tm_yday - 1) else: TimeDurStr = time.strftime("%H:%M:%S", TimeDur) return TimeDurStr else: return None def ThreadNum(): OptionParser = MyOptionParser() if not OptionParser.BuildOption and not OptionParser.BuildTarget: OptionParser.GetOption() BuildOption, BuildTarget = OptionParser.BuildOption, OptionParser.BuildTarget ThreadNumber = BuildOption.ThreadNumber GlobalData.gCmdConfDir = BuildOption.ConfDirectory if ThreadNumber is None: TargetObj = TargetTxtDict() ThreadNumber = TargetObj.Target.TargetTxtDictionary[TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD_NUMBER] if ThreadNumber == '': ThreadNumber = 0 else: ThreadNumber = int(ThreadNumber, 0) if ThreadNumber == 0: try: ThreadNumber = multiprocessing.cpu_count() except (ImportError, NotImplementedError): ThreadNumber = 1 return ThreadNumber ## Tool entrance method # # This method mainly dispatch specific methods per the command line options. # If no error found, return zero value so the caller of this tool can know # if it's executed successfully or not. # # @retval 0 Tool was successful # @retval 1 Tool failed # LogQMaxSize = ThreadNum() * 10 def Main(): StartTime = time.time() # # Create a log Queue # LogQ = mp.Queue(LogQMaxSize) # Initialize log system EdkLogger.LogClientInitialize(LogQ) GlobalData.gCommand = sys.argv[1:] # # Parse the options and args # OptionParser = MyOptionParser() if not OptionParser.BuildOption and not OptionParser.BuildTarget: OptionParser.GetOption() Option, Target = OptionParser.BuildOption, OptionParser.BuildTarget GlobalData.gOptions = Option GlobalData.gCaseInsensitive = Option.CaseInsensitive # Set log level LogLevel = EdkLogger.INFO if Option.verbose is not None: EdkLogger.SetLevel(EdkLogger.VERBOSE) LogLevel = EdkLogger.VERBOSE elif Option.quiet is not None: EdkLogger.SetLevel(EdkLogger.QUIET) LogLevel = EdkLogger.QUIET elif Option.debug is not None: EdkLogger.SetLevel(Option.debug + 1) LogLevel = Option.debug + 1 else: EdkLogger.SetLevel(EdkLogger.INFO) if Option.WarningAsError == True: EdkLogger.SetWarningAsError() Log_Agent = LogAgent(LogQ,LogLevel,Option.LogFile) Log_Agent.start() if platform.platform().find("Windows") >= 0: GlobalData.gIsWindows = True else: GlobalData.gIsWindows = False EdkLogger.quiet("Build environment: %s" % platform.platform()) EdkLogger.quiet(time.strftime("Build start time: %H:%M:%S, %b.%d %Y\n", time.localtime())); ReturnCode = 0 MyBuild = None BuildError = True try: if len(Target) == 0: Target = "all" elif len(Target) >= 2: EdkLogger.error("build", OPTION_NOT_SUPPORTED, "More than one targets are not supported.", ExtraData="Please select one of: %s" % (' '.join(gSupportedTarget))) else: Target = Target[0].lower() if Target not in gSupportedTarget: EdkLogger.error("build", OPTION_NOT_SUPPORTED, "Not supported target [%s]." % Target, ExtraData="Please select one of: %s" % (' '.join(gSupportedTarget))) # # Check environment variable: EDK_TOOLS_PATH, WORKSPACE, PATH # CheckEnvVariable() GlobalData.gCommandLineDefines.update(ParseDefines(Option.Macros)) Workspace = os.getenv("WORKSPACE") # # Get files real name in workspace dir # GlobalData.gAllFiles = Utils.DirCache(Workspace) WorkingDirectory = os.getcwd() if not Option.ModuleFile: FileList = glob.glob(os.path.normpath(os.path.join(WorkingDirectory, '*.inf'))) FileNum = len(FileList) if FileNum >= 2: EdkLogger.error("build", OPTION_NOT_SUPPORTED, "There are %d INF files in %s." % (FileNum, WorkingDirectory), ExtraData="Please use '-m <INF_FILE_PATH>' switch to choose one.") elif FileNum == 1: Option.ModuleFile = NormFile(FileList[0], Workspace) if Option.ModuleFile: if os.path.isabs (Option.ModuleFile): if os.path.normcase (os.path.normpath(Option.ModuleFile)).find (Workspace) == 0: Option.ModuleFile = NormFile(os.path.normpath(Option.ModuleFile), Workspace) Option.ModuleFile = PathClass(Option.ModuleFile, Workspace) ErrorCode, ErrorInfo = Option.ModuleFile.Validate(".inf", False) if ErrorCode != 0: EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo) if Option.PlatformFile is not None: if os.path.isabs (Option.PlatformFile): if os.path.normcase (os.path.normpath(Option.PlatformFile)).find (Workspace) == 0: Option.PlatformFile = NormFile(os.path.normpath(Option.PlatformFile), Workspace) Option.PlatformFile = PathClass(Option.PlatformFile, Workspace) if Option.FdfFile is not None: if os.path.isabs (Option.FdfFile): if os.path.normcase (os.path.normpath(Option.FdfFile)).find (Workspace) == 0: Option.FdfFile = NormFile(os.path.normpath(Option.FdfFile), Workspace) Option.FdfFile = PathClass(Option.FdfFile, Workspace) ErrorCode, ErrorInfo = Option.FdfFile.Validate(".fdf", False) if ErrorCode != 0: EdkLogger.error("build", ErrorCode, ExtraData=ErrorInfo) if Option.Flag is not None and Option.Flag not in ['-c', '-s']: EdkLogger.error("build", OPTION_VALUE_INVALID, "UNI flag must be one of -c or -s") MyBuild = Build(Target, Workspace, Option,LogQ) GlobalData.gCommandLineDefines['ARCH'] = ' '.join(MyBuild.ArchList) if not (MyBuild.LaunchPrebuildFlag and os.path.exists(MyBuild.PlatformBuildPath)): MyBuild.Launch() # # All job done, no error found and no exception raised # BuildError = False except FatalError as X: if MyBuild is not None: # for multi-thread build exits safely MyBuild.Relinquish() if Option is not None and Option.debug is not None: EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc()) ReturnCode = X.args[0] except Warning as X: # error from Fdf parser if MyBuild is not None: # for multi-thread build exits safely MyBuild.Relinquish() if Option is not None and Option.debug is not None: EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc()) else: EdkLogger.error(X.ToolName, FORMAT_INVALID, File=X.FileName, Line=X.LineNumber, ExtraData=X.Message, RaiseError=False) ReturnCode = FORMAT_INVALID except KeyboardInterrupt: if MyBuild is not None: # for multi-thread build exits safely MyBuild.Relinquish() ReturnCode = ABORT_ERROR if Option is not None and Option.debug is not None: EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc()) except: if MyBuild is not None: # for multi-thread build exits safely MyBuild.Relinquish() # try to get the meta-file from the object causing exception Tb = sys.exc_info()[-1] MetaFile = GlobalData.gProcessingFile while Tb is not None: if 'self' in Tb.tb_frame.f_locals and hasattr(Tb.tb_frame.f_locals['self'], 'MetaFile'): MetaFile = Tb.tb_frame.f_locals['self'].MetaFile Tb = Tb.tb_next EdkLogger.error( "\nbuild", CODE_ERROR, "Unknown fatal error when processing [%s]" % MetaFile, ExtraData="\n(Please send email to %s for help, attaching following call stack trace!)\n" % MSG_EDKII_MAIL_ADDR, RaiseError=False ) EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc()) ReturnCode = CODE_ERROR finally: Utils.Progressor.Abort() Utils.ClearDuplicatedInf() if ReturnCode == 0: try: MyBuild.LaunchPostbuild() Conclusion = "Done" except: Conclusion = "Failed" elif ReturnCode == ABORT_ERROR: Conclusion = "Aborted" else: Conclusion = "Failed" FinishTime = time.time() BuildDuration = time.gmtime(int(round(FinishTime - StartTime))) BuildDurationStr = "" if BuildDuration.tm_yday > 1: BuildDurationStr = time.strftime("%H:%M:%S", BuildDuration) + ", %d day(s)" % (BuildDuration.tm_yday - 1) else: BuildDurationStr = time.strftime("%H:%M:%S", BuildDuration) if MyBuild is not None: if not BuildError: MyBuild.BuildReport.GenerateReport(BuildDurationStr, LogBuildTime(MyBuild.AutoGenTime), LogBuildTime(MyBuild.MakeTime), LogBuildTime(MyBuild.GenFdsTime)) EdkLogger.SetLevel(EdkLogger.QUIET) EdkLogger.quiet("\n- %s -" % Conclusion) EdkLogger.quiet(time.strftime("Build end time: %H:%M:%S, %b.%d %Y", time.localtime())) EdkLogger.quiet("Build total time: %s\n" % BuildDurationStr) Log_Agent.kill() Log_Agent.join() return ReturnCode if __name__ == '__main__': try: mp.set_start_method('spawn') except: pass r = Main() ## 0-127 is a safe return range, and 1 is a standard default error if r < 0 or r > 127: r = 1 sys.exit(r)
[]
[]
[ "PACKAGES_PATH", "PATHEXT", "PYTHON3_ENABLE", "PYTHON_COMMAND", "WORKSPACE", "PATH", "EDK_TOOLS_BIN", "EDK_TOOLS_PATH" ]
[]
["PACKAGES_PATH", "PATHEXT", "PYTHON3_ENABLE", "PYTHON_COMMAND", "WORKSPACE", "PATH", "EDK_TOOLS_BIN", "EDK_TOOLS_PATH"]
python
8
0
test/e2e/util.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 e2e import ( "bytes" "fmt" "io" "io/ioutil" "math" "math/rand" "net/http" "os" "os/exec" "path/filepath" "sort" "strconv" "strings" "time" "k8s.io/kubernetes/pkg/api" apierrs "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/client/unversioned/cache" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/watch" "github.com/davecgh/go-spew/spew" "github.com/prometheus/client_golang/extraction" "github.com/prometheus/client_golang/model" "golang.org/x/crypto/ssh" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const ( // Initial pod start can be delayed O(minutes) by slow docker pulls // TODO: Make this 30 seconds once #4566 is resolved. podStartTimeout = 5 * time.Minute // How long to wait for a service endpoint to be resolvable. serviceStartTimeout = 1 * time.Minute // String used to mark pod deletion nonExist = "NonExist" // How often to poll pods and nodes. poll = 5 * time.Second // service accounts are provisioned after namespace creation // a service account is required to support pod creation in a namespace as part of admission control serviceAccountProvisionTimeout = 2 * time.Minute // How long to try single API calls (like 'get' or 'list'). Used to prevent // transient failures from failing tests. singleCallTimeout = 30 * time.Second // How long nodes have to be "ready" when a test begins. They should already // be "ready" before the test starts, so this is small. nodeReadyInitialTimeout = 20 * time.Second // How long pods have to be "ready" when a test begins. They should already // be "ready" before the test starts, so this is small. podReadyBeforeTimeout = 20 * time.Second podRespondingTimeout = 2 * time.Minute serviceRespondingTimeout = 2 * time.Minute // How wide to print pod names, by default. Useful for aligning printing to // quickly scan through output. podPrintWidth = 55 ) type CloudConfig struct { ProjectID string Zone string Cluster string MasterName string NodeInstanceGroup string NumNodes int ClusterTag string Provider cloudprovider.Interface } type TestContextType struct { KubeConfig string KubeContext string CertDir string Host string RepoRoot string Provider string CloudConfig CloudConfig KubectlPath string OutputDir string prefix string MinStartupPods int UpgradeTarget string PrometheusPushGateway string } var testContext TestContextType func SetTestContext(t TestContextType) { testContext = t } type ContainerFailures struct { status *api.ContainerStateTerminated restarts int } // Convenient wrapper around cache.Store that returns list of api.Pod instead of interface{}. type podStore struct { cache.Store stopCh chan struct{} } func newPodStore(c *client.Client, namespace string, label labels.Selector, field fields.Selector) *podStore { lw := &cache.ListWatch{ ListFunc: func() (runtime.Object, error) { return c.Pods(namespace).List(label, field) }, WatchFunc: func(rv string) (watch.Interface, error) { return c.Pods(namespace).Watch(label, field, rv) }, } store := cache.NewStore(cache.MetaNamespaceKeyFunc) stopCh := make(chan struct{}) cache.NewReflector(lw, &api.Pod{}, store, 0).RunUntil(stopCh) return &podStore{store, stopCh} } func (s *podStore) List() []*api.Pod { objects := s.Store.List() pods := make([]*api.Pod, 0) for _, o := range objects { pods = append(pods, o.(*api.Pod)) } return pods } func (s *podStore) Stop() { close(s.stopCh) } type RCConfig struct { Client *client.Client Image string Command []string Name string Namespace string PollInterval time.Duration Timeout time.Duration PodStatusFile *os.File Replicas int CpuRequest int64 // millicores CpuLimit int64 // millicores MemRequest int64 // bytes MemLimit int64 // bytes // Env vars, set the same for every pod. Env map[string]string // Extra labels added to every pod. Labels map[string]string // Ports to declare in the container (map of name to containerPort). Ports map[string]int // Pointer to a list of pods; if non-nil, will be set to a list of pods // created by this RC by RunRC. CreatedPods *[]*api.Pod // Maximum allowable container failures. If exceeded, RunRC returns an error. // Defaults to replicas*0.1 if unspecified. MaxContainerFailures *int } func nowStamp() string { return time.Now().Format(time.StampMilli) } func Logf(format string, a ...interface{}) { fmt.Fprintf(GinkgoWriter, nowStamp()+": INFO: "+format+"\n", a...) } func Failf(format string, a ...interface{}) { Fail(nowStamp()+": "+fmt.Sprintf(format, a...), 1) } func Skipf(format string, args ...interface{}) { Skip(nowStamp() + ": " + fmt.Sprintf(format, args...)) } func SkipUnlessNodeCountIsAtLeast(minNodeCount int) { if testContext.CloudConfig.NumNodes < minNodeCount { Skipf("Requires at least %d nodes (not %d)", minNodeCount, testContext.CloudConfig.NumNodes) } } func SkipIfProviderIs(unsupportedProviders ...string) { if providerIs(unsupportedProviders...) { Skipf("Not supported for providers %v (found %s)", unsupportedProviders, testContext.Provider) } } func SkipUnlessProviderIs(supportedProviders ...string) { if !providerIs(supportedProviders...) { Skipf("Only supported for providers %v (not %s)", supportedProviders, testContext.Provider) } } func providerIs(providers ...string) bool { for _, provider := range providers { if strings.ToLower(provider) == strings.ToLower(testContext.Provider) { return true } } return false } type podCondition func(pod *api.Pod) (bool, error) // podReady returns whether pod has a condition of Ready with a status of true. func podReady(pod *api.Pod) bool { for _, cond := range pod.Status.Conditions { if cond.Type == api.PodReady && cond.Status == api.ConditionTrue { return true } } return false } // logPodStates logs basic info of provided pods for debugging. func logPodStates(pods []api.Pod) { // Find maximum widths for pod, node, and phase strings for column printing. maxPodW, maxNodeW, maxPhaseW := len("POD"), len("NODE"), len("PHASE") for _, pod := range pods { if len(pod.ObjectMeta.Name) > maxPodW { maxPodW = len(pod.ObjectMeta.Name) } if len(pod.Spec.NodeName) > maxNodeW { maxNodeW = len(pod.Spec.NodeName) } if len(pod.Status.Phase) > maxPhaseW { maxPhaseW = len(pod.Status.Phase) } } // Increase widths by one to separate by a single space. maxPodW++ maxNodeW++ maxPhaseW++ // Log pod info. * does space padding, - makes them left-aligned. Logf("%-[1]*[2]s %-[3]*[4]s %-[5]*[6]s %[7]s", maxPodW, "POD", maxNodeW, "NODE", maxPhaseW, "PHASE", "CONDITIONS") for _, pod := range pods { Logf("%-[1]*[2]s %-[3]*[4]s %-[5]*[6]s %[7]s", maxPodW, pod.ObjectMeta.Name, maxNodeW, pod.Spec.NodeName, maxPhaseW, pod.Status.Phase, pod.Status.Conditions) } Logf("") // Final empty line helps for readability. } // podRunningReady checks whether pod p's phase is running and it has a ready // condition of status true. func podRunningReady(p *api.Pod) (bool, error) { // Check the phase is running. if p.Status.Phase != api.PodRunning { return false, fmt.Errorf("want pod '%s' on '%s' to be '%v' but was '%v'", p.ObjectMeta.Name, p.Spec.NodeName, api.PodRunning, p.Status.Phase) } // Check the ready condition is true. if !podReady(p) { return false, fmt.Errorf("pod '%s' on '%s' didn't have condition {%v %v}; conditions: %v", p.ObjectMeta.Name, p.Spec.NodeName, api.PodReady, api.ConditionTrue, p.Status.Conditions) } return true, nil } // check if a Pod is controlled by a Replication Controller in the List func hasReplicationControllersForPod(rcs *api.ReplicationControllerList, pod api.Pod) bool { for _, rc := range rcs.Items { selector := labels.SelectorFromSet(rc.Spec.Selector) if selector.Matches(labels.Set(pod.ObjectMeta.Labels)) { return true } } return false } // waitForPodsRunningReady waits up to timeout to ensure that all pods in // namespace ns are either running and ready, or failed but controlled by a // replication controller. Also, it ensures that at least minPods are running // and ready. It has separate behavior from other 'wait for' pods functions in // that it requires the list of pods on every iteration. This is useful, for // example, in cluster startup, because the number of pods increases while // waiting. func waitForPodsRunningReady(ns string, minPods int, timeout time.Duration) error { c, err := loadClient() if err != nil { return err } start := time.Now() Logf("Waiting up to %v for all pods (need at least %d) in namespace '%s' to be running and ready", timeout, minPods, ns) if wait.Poll(poll, timeout, func() (bool, error) { // We get the new list of pods and replication controllers in every // iteration because more pods come online during startup and we want to // ensure they are also checked. rcList, err := c.ReplicationControllers(ns).List(labels.Everything()) if err != nil { Logf("Error getting replication controllers in namespace '%s': %v", ns, err) return false, nil } replicas := 0 for _, rc := range rcList.Items { replicas += rc.Spec.Replicas } podList, err := c.Pods(ns).List(labels.Everything(), fields.Everything()) if err != nil { Logf("Error getting pods in namespace '%s': %v", ns, err) return false, nil } nOk, replicaOk, badPods := 0, 0, []api.Pod{} for _, pod := range podList.Items { if res, err := podRunningReady(&pod); res && err == nil { nOk++ if hasReplicationControllersForPod(rcList, pod) { replicaOk++ } } else { if pod.Status.Phase != api.PodFailed { Logf("The status of Pod %s is %s, waiting for it to be either Running or Failed", pod.ObjectMeta.Name, pod.Status.Phase) badPods = append(badPods, pod) } else if !hasReplicationControllersForPod(rcList, pod) { Logf("Pod %s is Failed, but it's not controlled by a ReplicationController", pod.ObjectMeta.Name) badPods = append(badPods, pod) } //ignore failed pods that are controlled by a replication controller } } Logf("%d / %d pods in namespace '%s' are running and ready (%d seconds elapsed)", nOk, len(podList.Items), ns, int(time.Since(start).Seconds())) Logf("expected %d pod replicas in namespace '%s', %d are Running and Ready.", replicas, ns, replicaOk) if replicaOk == replicas && nOk >= minPods && len(badPods) == 0 { return true, nil } logPodStates(badPods) return false, nil }) != nil { return fmt.Errorf("Not all pods in namespace '%s' running and ready within %v", ns, timeout) } return nil } func waitForServiceAccountInNamespace(c *client.Client, ns, serviceAccountName string, timeout time.Duration) error { Logf("Waiting up to %v for service account %s to be provisioned in ns %s", timeout, serviceAccountName, ns) for start := time.Now(); time.Since(start) < timeout; time.Sleep(poll) { sa, err := c.ServiceAccounts(ns).Get(serviceAccountName) if apierrs.IsNotFound(err) { Logf("Get service account %s in ns %s failed, ignoring for %v: %v", serviceAccountName, ns, poll, err) continue } if err != nil { Logf("Get service account %s in ns %s failed: %v", serviceAccountName, ns, err) return err } if len(sa.Secrets) == 0 { Logf("Service account %s in ns %s had 0 secrets, ignoring for %v: %v", serviceAccountName, ns, poll, err) continue } Logf("Service account %s in ns %s with secrets found. (%v)", serviceAccountName, ns, time.Since(start)) return nil } return fmt.Errorf("Service account %s in namespace %s not ready within %v", serviceAccountName, ns, timeout) } func waitForPodCondition(c *client.Client, ns, podName, desc string, timeout time.Duration, condition podCondition) error { Logf("Waiting up to %[1]v for pod %-[2]*[3]s status to be %[4]s", timeout, podPrintWidth, podName, desc) for start := time.Now(); time.Since(start) < timeout; time.Sleep(poll) { pod, err := c.Pods(ns).Get(podName) if err != nil { // Aligning this text makes it much more readable Logf("Get pod %-[1]*[2]s in namespace '%[3]s' failed, ignoring for %[4]v. Error: %[5]v", podPrintWidth, podName, ns, poll, err) continue } done, err := condition(pod) if done { return err } Logf("Waiting for pod %-[1]*[2]s in namespace '%[3]s' status to be '%[4]s'"+ "(found phase: %[5]q, readiness: %[6]t) (%[7]v elapsed)", podPrintWidth, podName, ns, desc, pod.Status.Phase, podReady(pod), time.Since(start)) } return fmt.Errorf("gave up waiting for pod '%s' to be '%s' after %v", podName, desc, timeout) } // waitForDefaultServiceAccountInNamespace waits for the default service account to be provisioned // the default service account is what is associated with pods when they do not specify a service account // as a result, pods are not able to be provisioned in a namespace until the service account is provisioned func waitForDefaultServiceAccountInNamespace(c *client.Client, namespace string) error { return waitForServiceAccountInNamespace(c, namespace, "default", serviceAccountProvisionTimeout) } // waitForPersistentVolumePhase waits for a PersistentVolume to be in a specific phase or until timeout occurs, whichever comes first. func waitForPersistentVolumePhase(phase api.PersistentVolumePhase, c *client.Client, pvName string, poll, timeout time.Duration) error { Logf("Waiting up to %v for PersistentVolume %s to have phase %s", timeout, pvName, phase) for start := time.Now(); time.Since(start) < timeout; time.Sleep(poll) { pv, err := c.PersistentVolumes().Get(pvName) if err != nil { Logf("Get persistent volume %s in failed, ignoring for %v: %v", pvName, poll, err) continue } else { if pv.Status.Phase == phase { Logf("PersistentVolume %s found and phase=%s (%v)", pvName, phase, time.Since(start)) return nil } else { Logf("PersistentVolume %s found but phase is %s instead of %s.", pvName, pv.Status.Phase, phase) } } } return fmt.Errorf("PersistentVolume %s not in phase %s within %v", pvName, phase, timeout) } // createTestingNS should be used by every test, note that we append a common prefix to the provided test name. // Please see NewFramework instead of using this directly. func createTestingNS(baseName string, c *client.Client) (*api.Namespace, error) { namespaceObj := &api.Namespace{ ObjectMeta: api.ObjectMeta{ GenerateName: fmt.Sprintf("e2e-tests-%v-", baseName), Namespace: "", }, Status: api.NamespaceStatus{}, } // Be robust about making the namespace creation call. var got *api.Namespace if err := wait.Poll(poll, singleCallTimeout, func() (bool, error) { var err error got, err = c.Namespaces().Create(namespaceObj) if err != nil { return false, nil } return true, nil }); err != nil { return nil, err } if err := waitForDefaultServiceAccountInNamespace(c, got.Name); err != nil { return nil, err } return got, nil } // deleteTestingNS checks whether all e2e based existing namespaces are in the Terminating state // and waits until they are finally deleted. func deleteTestingNS(c *client.Client) error { // TODO: Since we don't have support for bulk resource deletion in the API, // while deleting a namespace we are deleting all objects from that namespace // one by one (one deletion == one API call). This basically exposes us to // throttling - currently controller-manager has a limit of max 20 QPS. // Once #10217 is implemented and used in namespace-controller, deleting all // object from a given namespace should be much faster and we will be able // to lower this timeout. // However, now Density test is producing ~26000 events and Load capacity test // is producing ~35000 events, thus assuming there are no other requests it will // take ~30 minutes to fully delete the namespace. Thus I'm setting it to 60 // minutes to avoid any timeouts here. timeout := 60 * time.Minute Logf("Waiting for terminating namespaces to be deleted...") for start := time.Now(); time.Since(start) < timeout; time.Sleep(15 * time.Second) { namespaces, err := c.Namespaces().List(labels.Everything(), fields.Everything()) if err != nil { Logf("Listing namespaces failed: %v", err) continue } terminating := 0 for _, ns := range namespaces.Items { if strings.HasPrefix(ns.ObjectMeta.Name, "e2e-tests-") { if ns.Status.Phase == api.NamespaceActive { return fmt.Errorf("Namespace %s is active", ns.ObjectMeta.Name) } terminating++ } } if terminating == 0 { return nil } } return fmt.Errorf("Waiting for terminating namespaces to be deleted timed out") } // deleteNS deletes the provided namespace, waits for it to be completely deleted, and then checks // whether there are any pods remaining in a non-terminating state. func deleteNS(c *client.Client, namespace string) error { if err := c.Namespaces().Delete(namespace); err != nil { return err } err := wait.Poll(5*time.Second, 5*time.Minute, func() (bool, error) { if _, err := c.Namespaces().Get(namespace); err != nil { if apierrs.IsNotFound(err) { return true, nil } Logf("Error while waiting for namespace to be terminated: %v", err) return false, nil } return false, nil }) // check for pods that were not deleted remaining := []string{} missingTimestamp := false if pods, perr := c.Pods(namespace).List(labels.Everything(), fields.Everything()); perr == nil { for _, pod := range pods.Items { Logf("Pod %s %s on node %s remains, has deletion timestamp %s", namespace, pod.Name, pod.Spec.NodeName, pod.DeletionTimestamp) remaining = append(remaining, pod.Name) if pod.DeletionTimestamp == nil { missingTimestamp = true } } } // a timeout occured if err != nil { if missingTimestamp { return fmt.Errorf("namespace %s was not deleted within limit: %v, some pods were not marked with a deletion timestamp, pods remaining: %v", namespace, err, remaining) } return fmt.Errorf("namespace %s was not deleted within limit: %v, pods remaining: %v", namespace, err, remaining) } // pods were not deleted but the namespace was deleted if len(remaining) > 0 { return fmt.Errorf("pods remained within namespace %s after deletion: %v", namespace, remaining) } return nil } func waitForPodRunningInNamespace(c *client.Client, podName string, namespace string) error { return waitForPodCondition(c, namespace, podName, "running", podStartTimeout, func(pod *api.Pod) (bool, error) { if pod.Status.Phase == api.PodRunning { Logf("Found pod '%s' on node '%s'", podName, pod.Spec.NodeName) return true, nil } if pod.Status.Phase == api.PodFailed { return true, fmt.Errorf("Giving up; pod went into failed status: \n%s", spew.Sprintf("%#v", pod)) } return false, nil }) } // waitForPodNotPending returns an error if it took too long for the pod to go out of pending state. func waitForPodNotPending(c *client.Client, ns, podName string) error { return waitForPodCondition(c, ns, podName, "!pending", podStartTimeout, func(pod *api.Pod) (bool, error) { if pod.Status.Phase != api.PodPending { Logf("Saw pod '%s' in namespace '%s' out of pending state (found '%q')", podName, ns, pod.Status.Phase) return true, nil } return false, nil }) } // waitForPodSuccessInNamespace returns nil if the pod reached state success, or an error if it reached failure or ran too long. func waitForPodSuccessInNamespace(c *client.Client, podName string, contName string, namespace string) error { return waitForPodCondition(c, namespace, podName, "success or failure", podStartTimeout, func(pod *api.Pod) (bool, error) { // Cannot use pod.Status.Phase == api.PodSucceeded/api.PodFailed due to #2632 ci, ok := api.GetContainerStatus(pod.Status.ContainerStatuses, contName) if !ok { Logf("No Status.Info for container '%s' in pod '%s' yet", contName, podName) } else { if ci.State.Terminated != nil { if ci.State.Terminated.ExitCode == 0 { By("Saw pod success") return true, nil } return true, fmt.Errorf("pod '%s' terminated with failure: %+v", podName, ci.State.Terminated) } Logf("Nil State.Terminated for container '%s' in pod '%s' in namespace '%s' so far", contName, podName, namespace) } return false, nil }) } // waitForRCPodOnNode returns the pod from the given replication controller (described by rcName) which is scheduled on the given node. // In case of failure or too long waiting time, an error is returned. func waitForRCPodOnNode(c *client.Client, ns, rcName, node string) (*api.Pod, error) { label := labels.SelectorFromSet(labels.Set(map[string]string{"name": rcName})) var p *api.Pod = nil err := wait.Poll(10*time.Second, 5*time.Minute, func() (bool, error) { Logf("Waiting for pod %s to appear on node %s", rcName, node) pods, err := c.Pods(ns).List(label, fields.Everything()) if err != nil { return false, err } for _, pod := range pods.Items { if pod.Spec.NodeName == node { Logf("Pod %s found on node %s", pod.Name, node) p = &pod return true, nil } } return false, nil }) return p, err } // waitForRCPodToDisappear returns nil if the pod from the given replication controller (described by rcName) no longer exists. // In case of failure or too long waiting time, an error is returned. func waitForRCPodToDisappear(c *client.Client, ns, rcName, podName string) error { label := labels.SelectorFromSet(labels.Set(map[string]string{"name": rcName})) return wait.Poll(20*time.Second, 5*time.Minute, func() (bool, error) { Logf("Waiting for pod %s to disappear", podName) pods, err := c.Pods(ns).List(label, fields.Everything()) if err != nil { return false, err } found := false for _, pod := range pods.Items { if pod.Name == podName { Logf("Pod %s still exists", podName) found = true } } if !found { Logf("Pod %s no longer exists", podName) return true, nil } return false, nil }) } // waitForService waits until the service appears (exist == true), or disappears (exist == false) func waitForService(c *client.Client, namespace, name string, exist bool, interval, timeout time.Duration) error { err := wait.Poll(interval, timeout, func() (bool, error) { _, err := c.Services(namespace).Get(name) if err != nil { Logf("Get service %s in namespace %s failed (%v).", name, namespace, err) return !exist, nil } else { Logf("Service %s in namespace %s found.", name, namespace) return exist, nil } }) if err != nil { stateMsg := map[bool]string{true: "to appear", false: "to disappear"} return fmt.Errorf("error waiting for service %s/%s %s: %v", namespace, name, stateMsg[exist], err) } return nil } // waitForReplicationController waits until the RC appears (exist == true), or disappears (exist == false) func waitForReplicationController(c *client.Client, namespace, name string, exist bool, interval, timeout time.Duration) error { err := wait.Poll(interval, timeout, func() (bool, error) { _, err := c.ReplicationControllers(namespace).Get(name) if err != nil { Logf("Get ReplicationController %s in namespace %s failed (%v).", name, namespace, err) return !exist, nil } else { Logf("ReplicationController %s in namespace %s found.", name, namespace) return exist, nil } }) if err != nil { stateMsg := map[bool]string{true: "to appear", false: "to disappear"} return fmt.Errorf("error waiting for ReplicationController %s/%s %s: %v", namespace, name, stateMsg[exist], err) } return nil } // Context for checking pods responses by issuing GETs to them and verifying if the answer with pod name. type podResponseChecker struct { c *client.Client ns string label labels.Selector controllerName string respondName bool // Whether the pod should respond with its own name. pods *api.PodList } // checkAllResponses issues GETs to all pods in the context and verify they reply with pod name. func (r podResponseChecker) checkAllResponses() (done bool, err error) { successes := 0 currentPods, err := r.c.Pods(r.ns).List(r.label, fields.Everything()) Expect(err).NotTo(HaveOccurred()) for i, pod := range r.pods.Items { // Check that the replica list remains unchanged, otherwise we have problems. if !isElementOf(pod.UID, currentPods) { return false, fmt.Errorf("pod with UID %s is no longer a member of the replica set. Must have been restarted for some reason. Current replica set: %v", pod.UID, currentPods) } body, err := r.c.Get(). Prefix("proxy"). Namespace(r.ns). Resource("pods"). Name(string(pod.Name)). Do(). Raw() if err != nil { Logf("Controller %s: Failed to GET from replica %d [%s]: %v:", r.controllerName, i+1, pod.Name, err) continue } // The response checker expects the pod's name unless !respondName, in // which case it just checks for a non-empty response. got := string(body) what := "" if r.respondName { what = "expected" want := pod.Name if got != want { Logf("Controller %s: Replica %d [%s] expected response %q but got %q", r.controllerName, i+1, pod.Name, want, got) continue } } else { what = "non-empty" if len(got) == 0 { Logf("Controller %s: Replica %d [%s] expected non-empty response", r.controllerName, i+1, pod.Name) continue } } successes++ Logf("Controller %s: Got %s result from replica %d [%s]: %q, %d of %d required successes so far", r.controllerName, what, i+1, pod.Name, got, successes, len(r.pods.Items)) } if successes < len(r.pods.Items) { return false, nil } return true, nil } func podsResponding(c *client.Client, ns, name string, wantName bool, pods *api.PodList) error { By("trying to dial each unique pod") label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name})) return wait.Poll(poll, podRespondingTimeout, podResponseChecker{c, ns, label, name, wantName, pods}.checkAllResponses) } func serviceResponding(c *client.Client, ns, name string) error { By(fmt.Sprintf("trying to dial the service %s.%s via the proxy", ns, name)) return wait.Poll(poll, serviceRespondingTimeout, func() (done bool, err error) { body, err := c.Get(). Prefix("proxy"). Namespace(ns). Resource("services"). Name(name). Do(). Raw() if err != nil { Logf("Failed to GET from service %s: %v:", name, err) return false, nil } got := string(body) if len(got) == 0 { Logf("Service %s: expected non-empty response", name) return false, err // stop polling } Logf("Service %s: found nonempty answer: %s", name, got) return true, nil }) } func loadConfig() (*client.Config, error) { switch { case testContext.KubeConfig != "": fmt.Printf(">>> testContext.KubeConfig: %s\n", testContext.KubeConfig) c, err := clientcmd.LoadFromFile(testContext.KubeConfig) if err != nil { return nil, fmt.Errorf("error loading KubeConfig: %v", err.Error()) } if testContext.KubeContext != "" { fmt.Printf(">>> testContext.KubeContext: %s\n", testContext.KubeContext) c.CurrentContext = testContext.KubeContext } return clientcmd.NewDefaultClientConfig(*c, &clientcmd.ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: testContext.Host}}).ClientConfig() default: return nil, fmt.Errorf("KubeConfig must be specified to load client config") } } func loadClient() (*client.Client, error) { config, err := loadConfig() if err != nil { return nil, fmt.Errorf("error creating client: %v", err.Error()) } c, err := client.New(config) if err != nil { return nil, fmt.Errorf("error creating client: %v", err.Error()) } return c, nil } // randomSuffix provides a random string to append to pods,services,rcs. // TODO: Allow service names to have the same form as names // for pods and replication controllers so we don't // need to use such a function and can instead // use the UUID utilty function. func randomSuffix() string { r := rand.New(rand.NewSource(time.Now().UnixNano())) return strconv.Itoa(r.Int() % 10000) } func expectNoError(err error, explain ...interface{}) { ExpectWithOffset(1, err).NotTo(HaveOccurred(), explain...) } // Stops everything from filePath from namespace ns and checks if everything matching selectors from the given namespace is correctly stopped. func cleanup(filePath string, ns string, selectors ...string) { By("using delete to clean up resources") var nsArg string if ns != "" { nsArg = fmt.Sprintf("--namespace=%s", ns) } runKubectl("stop", "--grace-period=0", "-f", filePath, nsArg) for _, selector := range selectors { resources := runKubectl("get", "rc,svc", "-l", selector, "--no-headers", nsArg) if resources != "" { Failf("Resources left running after stop:\n%s", resources) } pods := runKubectl("get", "pods", "-l", selector, nsArg, "-t", "{{ range .items }}{{ if not .metadata.deletionTimestamp }}{{ .metadata.name }}{{ \"\\n\" }}{{ end }}{{ end }}") if pods != "" { Failf("Pods left unterminated after stop:\n%s", pods) } } } // validatorFn is the function which is individual tests will implement. // we may want it to return more than just an error, at some point. type validatorFn func(c *client.Client, podID string) error // validateController is a generic mechanism for testing RC's that are running. // It takes a container name, a test name, and a validator function which is plugged in by a specific test. // "containername": this is grepped for. // "containerImage" : this is the name of the image we expect to be launched. Not to confuse w/ images (kitten.jpg) which are validated. // "testname": which gets bubbled up to the logging/failure messages if errors happen. // "validator" function: This function is given a podID and a client, and it can do some specific validations that way. func validateController(c *client.Client, containerImage string, replicas int, containername string, testname string, validator validatorFn, ns string) { getPodsTemplate := "--template={{range.items}}{{.metadata.name}} {{end}}" // NB: kubectl adds the "exists" function to the standard template functions. // This lets us check to see if the "running" entry exists for each of the containers // we care about. Exists will never return an error and it's safe to check a chain of // things, any one of which may not exist. In the below template, all of info, // containername, and running might be nil, so the normal index function isn't very // helpful. // This template is unit-tested in kubectl, so if you change it, update the unit test. // You can read about the syntax here: http://golang.org/pkg/text/template/. getContainerStateTemplate := fmt.Sprintf(`--template={{if (exists . "status" "containerStatuses")}}{{range .status.containerStatuses}}{{if (and (eq .name "%s") (exists . "state" "running"))}}true{{end}}{{end}}{{end}}`, containername) getImageTemplate := fmt.Sprintf(`--template={{if (exists . "status" "containerStatuses")}}{{range .status.containerStatuses}}{{if eq .name "%s"}}{{.image}}{{end}}{{end}}{{end}}`, containername) By(fmt.Sprintf("waiting for all containers in %s pods to come up.", testname)) //testname should be selector waitLoop: for start := time.Now(); time.Since(start) < podStartTimeout; time.Sleep(5 * time.Second) { getPodsOutput := runKubectl("get", "pods", "-o", "template", getPodsTemplate, "--api-version=v1", "-l", testname, fmt.Sprintf("--namespace=%v", ns)) pods := strings.Fields(getPodsOutput) if numPods := len(pods); numPods != replicas { By(fmt.Sprintf("Replicas for %s: expected=%d actual=%d", testname, replicas, numPods)) continue } var runningPods []string for _, podID := range pods { running := runKubectl("get", "pods", podID, "-o", "template", getContainerStateTemplate, "--api-version=v1", fmt.Sprintf("--namespace=%v", ns)) if running != "true" { Logf("%s is created but not running", podID) continue waitLoop } currentImage := runKubectl("get", "pods", podID, "-o", "template", getImageTemplate, "--api-version=v1", fmt.Sprintf("--namespace=%v", ns)) if currentImage != containerImage { Logf("%s is created but running wrong image; expected: %s, actual: %s", podID, containerImage, currentImage) continue waitLoop } // Call the generic validator function here. // This might validate for example, that (1) getting a url works and (2) url is serving correct content. if err := validator(c, podID); err != nil { Logf("%s is running right image but validator function failed: %v", podID, err) continue waitLoop } Logf("%s is verified up and running", podID) runningPods = append(runningPods, podID) } // If we reach here, then all our checks passed. if len(runningPods) == replicas { return } } // Reaching here means that one of more checks failed multiple times. Assuming its not a race condition, something is broken. Failf("Timed out after %v seconds waiting for %s pods to reach valid state", podStartTimeout.Seconds(), testname) } // kubectlCmd runs the kubectl executable through the wrapper script. func kubectlCmd(args ...string) *exec.Cmd { defaultArgs := []string{} // Reference a --server option so tests can run anywhere. if testContext.Host != "" { defaultArgs = append(defaultArgs, "--"+clientcmd.FlagAPIServer+"="+testContext.Host) } if testContext.KubeConfig != "" { defaultArgs = append(defaultArgs, "--"+clientcmd.RecommendedConfigPathFlag+"="+testContext.KubeConfig) // Reference the KubeContext if testContext.KubeContext != "" { defaultArgs = append(defaultArgs, "--"+clientcmd.FlagContext+"="+testContext.KubeContext) } } else { if testContext.CertDir != "" { defaultArgs = append(defaultArgs, fmt.Sprintf("--certificate-authority=%s", filepath.Join(testContext.CertDir, "ca.crt")), fmt.Sprintf("--client-certificate=%s", filepath.Join(testContext.CertDir, "kubecfg.crt")), fmt.Sprintf("--client-key=%s", filepath.Join(testContext.CertDir, "kubecfg.key"))) } } kubectlArgs := append(defaultArgs, args...) //We allow users to specify path to kubectl, so you can test either "kubectl" or "cluster/kubectl.sh" //and so on. cmd := exec.Command(testContext.KubectlPath, kubectlArgs...) //caller will invoke this and wait on it. return cmd } // kubectlBuilder is used to build, custimize and execute a kubectl Command. // Add more functions to customize the builder as needed. type kubectlBuilder struct { cmd *exec.Cmd } func newKubectlCommand(args ...string) *kubectlBuilder { b := new(kubectlBuilder) b.cmd = kubectlCmd(args...) return b } func (b kubectlBuilder) withStdinData(data string) *kubectlBuilder { b.cmd.Stdin = strings.NewReader(data) return &b } func (b kubectlBuilder) exec() string { var stdout, stderr bytes.Buffer cmd := b.cmd cmd.Stdout, cmd.Stderr = &stdout, &stderr Logf("Running '%s %s'", cmd.Path, strings.Join(cmd.Args[1:], " ")) // skip arg[0] as it is printed separately if err := cmd.Run(); err != nil { Failf("Error running %v:\nCommand stdout:\n%v\nstderr:\n%v\n", cmd, cmd.Stdout, cmd.Stderr) return "" } Logf(stdout.String()) // TODO: trimspace should be unnecessary after switching to use kubectl binary directly return strings.TrimSpace(stdout.String()) } // runKubectl is a convenience wrapper over kubectlBuilder func runKubectl(args ...string) string { return newKubectlCommand(args...).exec() } func startCmdAndStreamOutput(cmd *exec.Cmd) (stdout, stderr io.ReadCloser, err error) { stdout, err = cmd.StdoutPipe() if err != nil { return } stderr, err = cmd.StderrPipe() if err != nil { return } Logf("Asynchronously running '%s %s'", cmd.Path, strings.Join(cmd.Args, " ")) err = cmd.Start() return } // Rough equivalent of ctrl+c for cleaning up processes. Intended to be run in defer. func tryKill(cmd *exec.Cmd) { if err := cmd.Process.Kill(); err != nil { Logf("ERROR failed to kill command %v! The process may leak", cmd) } } // testContainerOutputInNamespace runs the given pod in the given namespace and waits // for all of the containers in the podSpec to move into the 'Success' status. It retrieves // the exact container log and searches for lines of expected output. func testContainerOutputInNamespace(scenarioName string, c *client.Client, pod *api.Pod, containerIndex int, expectedOutput []string, ns string) { By(fmt.Sprintf("Creating a pod to test %v", scenarioName)) defer c.Pods(ns).Delete(pod.Name, api.NewDeleteOptions(0)) if _, err := c.Pods(ns).Create(pod); err != nil { Failf("Failed to create pod: %v", err) } // Wait for client pod to complete. var containerName string for id, container := range pod.Spec.Containers { expectNoError(waitForPodSuccessInNamespace(c, pod.Name, container.Name, ns)) if id == containerIndex { containerName = container.Name } } if containerName == "" { Failf("Invalid container index: %d", containerIndex) } // Grab its logs. Get host first. podStatus, err := c.Pods(ns).Get(pod.Name) if err != nil { Failf("Failed to get pod status: %v", err) } By(fmt.Sprintf("Trying to get logs from node %s pod %s container %s: %v", podStatus.Spec.NodeName, podStatus.Name, containerName, err)) var logs []byte start := time.Now() // Sometimes the actual containers take a second to get started, try to get logs for 60s for time.Now().Sub(start) < (60 * time.Second) { err = nil logs, err = c.Get(). Prefix("proxy"). Resource("nodes"). Name(podStatus.Spec.NodeName). Suffix("containerLogs", ns, podStatus.Name, containerName). Do(). Raw() if err == nil && strings.Contains(string(logs), "Internal Error") { err = fmt.Errorf("Fetched log contains \"Internal Error\": %q.", string(logs)) } if err != nil { By(fmt.Sprintf("Warning: Failed to get logs from node %q pod %q container %q. %v", podStatus.Spec.NodeName, podStatus.Name, containerName, err)) time.Sleep(5 * time.Second) continue } By(fmt.Sprintf("Successfully fetched pod logs:%v\n", string(logs))) break } for _, m := range expectedOutput { Expect(string(logs)).To(ContainSubstring(m), "%q in container output", m) } } // podInfo contains pod information useful for debugging e2e tests. type podInfo struct { oldHostname string oldPhase string hostname string phase string } // PodDiff is a map of pod name to podInfos type PodDiff map[string]*podInfo // Print formats and prints the give PodDiff. func (p PodDiff) Print(ignorePhases util.StringSet) { for name, info := range p { if ignorePhases.Has(info.phase) { continue } if info.phase == nonExist { Logf("Pod %v was deleted, had phase %v and host %v", name, info.oldPhase, info.oldHostname) continue } phaseChange, hostChange := false, false msg := fmt.Sprintf("Pod %v ", name) if info.oldPhase != info.phase { phaseChange = true if info.oldPhase == nonExist { msg += fmt.Sprintf("in phase %v ", info.phase) } else { msg += fmt.Sprintf("went from phase: %v -> %v ", info.oldPhase, info.phase) } } if info.oldHostname != info.hostname { hostChange = true if info.oldHostname == nonExist || info.oldHostname == "" { msg += fmt.Sprintf("assigned host %v ", info.hostname) } else { msg += fmt.Sprintf("went from host: %v -> %v ", info.oldHostname, info.hostname) } } if phaseChange || hostChange { Logf(msg) } } } // Diff computes a PodDiff given 2 lists of pods. func Diff(oldPods []*api.Pod, curPods []*api.Pod) PodDiff { podInfoMap := PodDiff{} // New pods will show up in the curPods list but not in oldPods. They have oldhostname/phase == nonexist. for _, pod := range curPods { podInfoMap[pod.Name] = &podInfo{hostname: pod.Spec.NodeName, phase: string(pod.Status.Phase), oldHostname: nonExist, oldPhase: nonExist} } // Deleted pods will show up in the oldPods list but not in curPods. They have a hostname/phase == nonexist. for _, pod := range oldPods { if info, ok := podInfoMap[pod.Name]; ok { info.oldHostname, info.oldPhase = pod.Spec.NodeName, string(pod.Status.Phase) } else { podInfoMap[pod.Name] = &podInfo{hostname: nonExist, phase: nonExist, oldHostname: pod.Spec.NodeName, oldPhase: string(pod.Status.Phase)} } } return podInfoMap } // RunRC Launches (and verifies correctness) of a Replication Controller // and will wait for all pods it spawns to become "Running". // It's the caller's responsibility to clean up externally (i.e. use the // namespace lifecycle for handling cleanup). func RunRC(config RCConfig) error { // Don't force tests to fail if they don't care about containers restarting. var maxContainerFailures int if config.MaxContainerFailures == nil { maxContainerFailures = int(math.Max(1.0, float64(config.Replicas)*.01)) } else { maxContainerFailures = *config.MaxContainerFailures } label := labels.SelectorFromSet(labels.Set(map[string]string{"name": config.Name})) By(fmt.Sprintf("%v Creating replication controller %s", time.Now(), config.Name)) rc := &api.ReplicationController{ ObjectMeta: api.ObjectMeta{ Name: config.Name, }, Spec: api.ReplicationControllerSpec{ Replicas: config.Replicas, Selector: map[string]string{ "name": config.Name, }, Template: &api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: map[string]string{"name": config.Name}, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: config.Name, Image: config.Image, Command: config.Command, Ports: []api.ContainerPort{{ContainerPort: 80}}, }, }, }, }, }, } if config.Env != nil { for k, v := range config.Env { c := &rc.Spec.Template.Spec.Containers[0] c.Env = append(c.Env, api.EnvVar{Name: k, Value: v}) } } if config.Labels != nil { for k, v := range config.Labels { rc.Spec.Template.ObjectMeta.Labels[k] = v } } if config.Ports != nil { for k, v := range config.Ports { c := &rc.Spec.Template.Spec.Containers[0] c.Ports = append(c.Ports, api.ContainerPort{Name: k, ContainerPort: v}) } } if config.CpuLimit > 0 || config.MemLimit > 0 { rc.Spec.Template.Spec.Containers[0].Resources.Limits = api.ResourceList{} } if config.CpuLimit > 0 { rc.Spec.Template.Spec.Containers[0].Resources.Limits[api.ResourceCPU] = *resource.NewMilliQuantity(config.CpuLimit, resource.DecimalSI) } if config.MemLimit > 0 { rc.Spec.Template.Spec.Containers[0].Resources.Limits[api.ResourceMemory] = *resource.NewQuantity(config.MemLimit, resource.DecimalSI) } if config.CpuRequest > 0 || config.MemRequest > 0 { rc.Spec.Template.Spec.Containers[0].Resources.Requests = api.ResourceList{} } if config.CpuRequest > 0 { rc.Spec.Template.Spec.Containers[0].Resources.Requests[api.ResourceCPU] = *resource.NewMilliQuantity(config.CpuRequest, resource.DecimalSI) } if config.MemRequest > 0 { rc.Spec.Template.Spec.Containers[0].Resources.Requests[api.ResourceMemory] = *resource.NewQuantity(config.MemRequest, resource.DecimalSI) } _, err := config.Client.ReplicationControllers(config.Namespace).Create(rc) if err != nil { return fmt.Errorf("Error creating replication controller: %v", err) } Logf("%v Created replication controller with name: %v, namespace: %v, replica count: %v", time.Now(), rc.Name, config.Namespace, rc.Spec.Replicas) podStore := newPodStore(config.Client, config.Namespace, label, fields.Everything()) defer podStore.Stop() interval := config.PollInterval if interval <= 0 { interval = 10 * time.Second } timeout := config.Timeout if timeout <= 0 { timeout = 5 * time.Minute } oldPods := make([]*api.Pod, 0) oldRunning := 0 lastChange := time.Now() for oldRunning != config.Replicas { time.Sleep(interval) terminating := 0 running := 0 waiting := 0 pending := 0 unknown := 0 inactive := 0 failedContainers := 0 containerRestartNodes := util.NewStringSet() pods := podStore.List() created := []*api.Pod{} for _, p := range pods { if p.DeletionTimestamp != nil { terminating++ continue } created = append(created, p) if p.Status.Phase == api.PodRunning { running++ for _, v := range FailedContainers(p) { failedContainers = failedContainers + v.restarts containerRestartNodes.Insert(p.Spec.NodeName) } } else if p.Status.Phase == api.PodPending { if p.Spec.NodeName == "" { waiting++ } else { pending++ } } else if p.Status.Phase == api.PodSucceeded || p.Status.Phase == api.PodFailed { inactive++ } else if p.Status.Phase == api.PodUnknown { unknown++ } } pods = created if config.CreatedPods != nil { *config.CreatedPods = pods } Logf("%v %v Pods: %d out of %d created, %d running, %d pending, %d waiting, %d inactive, %d terminating, %d unknown ", time.Now(), rc.Name, len(pods), config.Replicas, running, pending, waiting, inactive, terminating, unknown) promPushRunningPending(running, pending) if config.PodStatusFile != nil { fmt.Fprintf(config.PodStatusFile, "%s, %d, running, %d, pending, %d, waiting, %d, inactive, %d, unknown\n", time.Now(), running, pending, waiting, inactive, unknown) } if failedContainers > maxContainerFailures { dumpNodeDebugInfo(config.Client, containerRestartNodes.List()) return fmt.Errorf("%d containers failed which is more than allowed %d", failedContainers, maxContainerFailures) } if len(pods) < len(oldPods) || len(pods) > config.Replicas { // This failure mode includes: // kubelet is dead, so node controller deleted pods and rc creates more // - diagnose by noting the pod diff below. // pod is unhealthy, so replication controller creates another to take its place // - diagnose by comparing the previous "2 Pod states" lines for inactive pods errorStr := fmt.Sprintf("Number of reported pods changed: %d vs %d", len(pods), len(oldPods)) Logf("%v, pods that changed since the last iteration:", errorStr) Diff(oldPods, pods).Print(util.NewStringSet()) return fmt.Errorf(errorStr) } if len(pods) > len(oldPods) || running > oldRunning { lastChange = time.Now() } oldPods = pods oldRunning = running if time.Since(lastChange) > timeout { dumpPodDebugInfo(config.Client, pods) break } } if oldRunning != config.Replicas { if pods, err := config.Client.Pods(api.NamespaceAll).List(labels.Everything(), fields.Everything()); err == nil { for _, pod := range pods.Items { Logf("Pod %s\t%s\t%s\t%s", pod.Namespace, pod.Name, pod.Spec.NodeName, pod.DeletionTimestamp) } } else { Logf("Can't list pod debug info: %v", err) } return fmt.Errorf("Only %d pods started out of %d", oldRunning, config.Replicas) } return nil } func dumpPodDebugInfo(c *client.Client, pods []*api.Pod) { badNodes := util.NewStringSet() for _, p := range pods { if p.Status.Phase != api.PodRunning { if p.Spec.NodeName != "" { Logf("Pod %v assigned to host %v (IP: %v) in %v", p.Name, p.Spec.NodeName, p.Status.HostIP, p.Status.Phase) badNodes.Insert(p.Spec.NodeName) } else { Logf("Pod %v still unassigned", p.Name) } } } dumpNodeDebugInfo(c, badNodes.List()) } func dumpAllPodInfo(c *client.Client) { pods, err := c.Pods("").List(labels.Everything(), fields.Everything()) if err != nil { Logf("unable to fetch pod debug info: %v", err) } for _, pod := range pods.Items { Logf("Pod %s %s node=%s, deletionTimestamp=%s", pod.Namespace, pod.Name, pod.Spec.NodeName, pod.DeletionTimestamp) } } func dumpNodeDebugInfo(c *client.Client, nodeNames []string) { for _, n := range nodeNames { Logf("\nLogging kubelet events for node %v", n) for _, e := range getNodeEvents(c, n) { Logf("source %v message %v reason %v first ts %v last ts %v, involved obj %+v", e.Source, e.Message, e.Reason, e.FirstTimestamp, e.LastTimestamp, e.InvolvedObject) } Logf("\nLogging pods the kubelet thinks is on node %v", n) podList, err := GetKubeletPods(c, n) if err != nil { Logf("Unable to retrieve kubelet pods for node %v", n) continue } for _, p := range podList.Items { Logf("%v started at %v (%d container statuses recorded)", p.Name, p.Status.StartTime, len(p.Status.ContainerStatuses)) for _, c := range p.Status.ContainerStatuses { Logf("\tContainer %v ready: %v, restart count %v", c.Name, c.Ready, c.RestartCount) } } HighLatencyKubeletOperations(c, 10*time.Second, n) // TODO: Log node resource info } } // logNodeEvents logs kubelet events from the given node. This includes kubelet // restart and node unhealthy events. Note that listing events like this will mess // with latency metrics, beware of calling it during a test. func getNodeEvents(c *client.Client, nodeName string) []api.Event { events, err := c.Events(api.NamespaceSystem).List( labels.Everything(), fields.Set{ "involvedObject.kind": "Node", "involvedObject.name": nodeName, "involvedObject.namespace": api.NamespaceAll, "source": "kubelet", }.AsSelector()) if err != nil { Logf("Unexpected error retrieving node events %v", err) return []api.Event{} } return events.Items } func ScaleRC(c *client.Client, ns, name string, size uint, wait bool) error { By(fmt.Sprintf("%v Scaling replication controller %s in namespace %s to %d", time.Now(), name, ns, size)) scaler, err := kubectl.ScalerFor("ReplicationController", kubectl.NewScalerClient(c)) if err != nil { return err } waitForScale := kubectl.NewRetryParams(5*time.Second, 1*time.Minute) waitForReplicas := kubectl.NewRetryParams(5*time.Second, 5*time.Minute) if err = scaler.Scale(ns, name, size, nil, waitForScale, waitForReplicas); err != nil { return err } if !wait { return nil } return waitForRCPodsRunning(c, ns, name) } // Wait up to 10 minutes for pods to become Running. func waitForRCPodsRunning(c *client.Client, ns, rcName string) error { running := false label := labels.SelectorFromSet(labels.Set(map[string]string{"name": rcName})) podStore := newPodStore(c, ns, label, fields.Everything()) defer podStore.Stop() waitLoop: for start := time.Now(); time.Since(start) < 10*time.Minute; time.Sleep(5 * time.Second) { pods := podStore.List() for _, p := range pods { if p.Status.Phase != api.PodRunning { continue waitLoop } } running = true break } if !running { return fmt.Errorf("Timeout while waiting for replication controller %s pods to be running", rcName) } return nil } // Wait up to 10 minutes for getting pods with certain label func waitForPodsWithLabel(c *client.Client, ns string, label labels.Selector) (pods *api.PodList, err error) { for t := time.Now(); time.Since(t) < podListTimeout; time.Sleep(poll) { pods, err = c.Pods(ns).List(label, fields.Everything()) Expect(err).NotTo(HaveOccurred()) if len(pods.Items) > 0 { break } } if pods == nil || len(pods.Items) == 0 { err = fmt.Errorf("Timeout while waiting for pods with label %v", label) } return } // Delete a Replication Controller and all pods it spawned func DeleteRC(c *client.Client, ns, name string) error { By(fmt.Sprintf("%v Deleting replication controller %s in namespace %s", time.Now(), name, ns)) rc, err := c.ReplicationControllers(ns).Get(name) if err != nil { if apierrs.IsNotFound(err) { Logf("RC %s was already deleted: %v", name, err) return nil } return err } reaper, err := kubectl.ReaperForReplicationController(c, 10*time.Minute) if err != nil { if apierrs.IsNotFound(err) { Logf("RC %s was already deleted: %v", name, err) return nil } return err } startTime := time.Now() _, err = reaper.Stop(ns, name, 0, api.NewDeleteOptions(0)) if apierrs.IsNotFound(err) { Logf("RC %s was already deleted: %v", name, err) return nil } deleteRCTime := time.Now().Sub(startTime) Logf("Deleting RC took: %v", deleteRCTime) if err == nil { err = waitForRCPodsGone(c, rc) } terminatePodTime := time.Now().Sub(startTime) - deleteRCTime Logf("Terminating RC pods took: %v", terminatePodTime) return err } // waitForRCPodsGone waits until there are no pods reported under an RC's selector (because the pods // have completed termination). func waitForRCPodsGone(c *client.Client, rc *api.ReplicationController) error { return wait.Poll(poll, singleCallTimeout, func() (bool, error) { if pods, err := c.Pods(rc.Namespace).List(labels.SelectorFromSet(rc.Spec.Selector), fields.Everything()); err == nil && len(pods.Items) == 0 { return true, nil } return false, nil }) } // Convenient wrapper around listing nodes supporting retries. func listNodes(c *client.Client, label labels.Selector, field fields.Selector) (*api.NodeList, error) { var nodes *api.NodeList var errLast error if wait.Poll(poll, singleCallTimeout, func() (bool, error) { nodes, errLast = c.Nodes().List(label, field) return errLast == nil, nil }) != nil { return nil, fmt.Errorf("listNodes() failed with last error: %v", errLast) } return nodes, nil } // FailedContainers inspects all containers in a pod and returns failure // information for containers that have failed or been restarted. // A map is returned where the key is the containerID and the value is a // struct containing the restart and failure information func FailedContainers(pod *api.Pod) map[string]ContainerFailures { var state ContainerFailures states := make(map[string]ContainerFailures) statuses := pod.Status.ContainerStatuses if len(statuses) == 0 { return nil } else { for _, status := range statuses { if status.State.Terminated != nil { states[status.ContainerID] = ContainerFailures{status: status.State.Terminated} } else if status.LastTerminationState.Terminated != nil { states[status.ContainerID] = ContainerFailures{status: status.LastTerminationState.Terminated} } if status.RestartCount > 0 { var ok bool if state, ok = states[status.ContainerID]; !ok { state = ContainerFailures{} } state.restarts = status.RestartCount states[status.ContainerID] = state } } } return states } // Prints the histogram of the events and returns the number of bad events. func BadEvents(events []*api.Event) int { type histogramKey struct { reason string source string } histogram := make(map[histogramKey]int) for _, e := range events { histogram[histogramKey{reason: e.Reason, source: e.Source.Component}]++ } for key, number := range histogram { Logf("- reason: %s, source: %s -> %d", key.reason, key.source, number) } badPatterns := []string{"kill", "fail"} badEvents := 0 for key, number := range histogram { for _, s := range badPatterns { if strings.Contains(key.reason, s) { Logf("WARNING %d events from %s with reason: %s", number, key.source, key.reason) badEvents += number break } } } return badEvents } // NodeSSHHosts returns SSH-able host names for all nodes. It returns an error // if it can't find an external IP for every node, though it still returns all // hosts that it found in that case. func NodeSSHHosts(c *client.Client) ([]string, error) { var hosts []string nodelist, err := c.Nodes().List(labels.Everything(), fields.Everything()) if err != nil { return hosts, fmt.Errorf("error getting nodes: %v", err) } for _, n := range nodelist.Items { for _, addr := range n.Status.Addresses { // Use the first external IP address we find on the node, and // use at most one per node. // TODO(mbforbes): Use the "preferred" address for the node, once // such a thing is defined (#2462). if addr.Type == api.NodeExternalIP { hosts = append(hosts, addr.Address+":22") break } } } // Error if any node didn't have an external IP. if len(hosts) != len(nodelist.Items) { return hosts, fmt.Errorf( "only found %d external IPs on nodes, but found %d nodes. Nodelist: %v", len(hosts), len(nodelist.Items), nodelist) } return hosts, nil } // SSH synchronously SSHs to a node running on provider and runs cmd. If there // is no error performing the SSH, the stdout, stderr, and exit code are // returned. func SSH(cmd, host, provider string) (string, string, int, error) { return sshCore(cmd, host, provider, false) } // SSHVerbose is just like SSH, but it logs the command, user, host, stdout, // stderr, exit code, and error. func SSHVerbose(cmd, host, provider string) (string, string, int, error) { return sshCore(cmd, host, provider, true) } func sshCore(cmd, host, provider string, verbose bool) (string, string, int, error) { // Get a signer for the provider. signer, err := getSigner(provider) if err != nil { return "", "", 0, fmt.Errorf("error getting signer for provider %s: '%v'", provider, err) } // RunSSHCommand will default to Getenv("USER") if user == "", but we're // defaulting here as well for logging clarity. user := os.Getenv("KUBE_SSH_USER") if user == "" { user = os.Getenv("USER") } stdout, stderr, code, err := util.RunSSHCommand(cmd, user, host, signer) if verbose { remote := fmt.Sprintf("%s@%s", user, host) Logf("[%s] Running `%s`", remote, cmd) Logf("[%s] stdout: %q", remote, stdout) Logf("[%s] stderr: %q", remote, stderr) Logf("[%s] exit code: %d", remote, code) Logf("[%s] error: %v", remote, err) } return stdout, stderr, code, err } // getSigner returns an ssh.Signer for the provider ("gce", etc.) that can be // used to SSH to their nodes. func getSigner(provider string) (ssh.Signer, error) { // Get the directory in which SSH keys are located. keydir := filepath.Join(os.Getenv("HOME"), ".ssh") // Select the key itself to use. When implementing more providers here, // please also add them to any SSH tests that are disabled because of signer // support. keyfile := "" switch provider { case "gce", "gke": keyfile = "google_compute_engine" case "aws": keyfile = "kube_aws_rsa" default: return nil, fmt.Errorf("getSigner(...) not implemented for %s", provider) } key := filepath.Join(keydir, keyfile) return util.MakePrivateKeySignerFromFile(key) } // checkPodsRunning returns whether all pods whose names are listed in podNames // in namespace ns are running and ready, using c and waiting at most timeout. func checkPodsRunningReady(c *client.Client, ns string, podNames []string, timeout time.Duration) bool { np, desc := len(podNames), "running and ready" Logf("Waiting up to %v for the following %d pods to be %s: %s", timeout, np, desc, podNames) result := make(chan bool, len(podNames)) for ix := range podNames { // Launch off pod readiness checkers. go func(name string) { err := waitForPodCondition(c, ns, name, desc, timeout, podRunningReady) result <- err == nil }(podNames[ix]) } // Wait for them all to finish. success := true // TODO(mbforbes): Change to `for range` syntax and remove logging once we // support only Go >= 1.4. for _, podName := range podNames { if !<-result { Logf("Pod %-[1]*[2]s failed to be %[3]s.", podPrintWidth, podName, desc) success = false } } Logf("Wanted all %d pods to be %s. Result: %t. Pods: %v", np, desc, success, podNames) return success } // waitForNodeToBeReady returns whether node name is ready within timeout. func waitForNodeToBeReady(c *client.Client, name string, timeout time.Duration) bool { return waitForNodeToBe(c, name, true, timeout) } // waitForNodeToBeNotReady returns whether node name is not ready (i.e. the // readiness condition is anything but ready, e.g false or unknown) within // timeout. func waitForNodeToBeNotReady(c *client.Client, name string, timeout time.Duration) bool { return waitForNodeToBe(c, name, false, timeout) } func isNodeReadySetAsExpected(node *api.Node, wantReady bool) bool { // Check the node readiness condition (logging all). for i, cond := range node.Status.Conditions { Logf("Node %s condition %d/%d: type: %v, status: %v, reason: %q, message: %q, last transition time: %v", node.Name, i+1, len(node.Status.Conditions), cond.Type, cond.Status, cond.Reason, cond.Message, cond.LastTransitionTime) // Ensure that the condition type is readiness and the status // matches as desired. if cond.Type == api.NodeReady && (cond.Status == api.ConditionTrue) == wantReady { Logf("Successfully found node %s readiness to be %t", node.Name, wantReady) return true } } return false } // waitForNodeToBe returns whether node name's readiness state matches wantReady // within timeout. If wantReady is true, it will ensure the node is ready; if // it's false, it ensures the node is in any state other than ready (e.g. not // ready or unknown). func waitForNodeToBe(c *client.Client, name string, wantReady bool, timeout time.Duration) bool { Logf("Waiting up to %v for node %s readiness to be %t", timeout, name, wantReady) for start := time.Now(); time.Since(start) < timeout; time.Sleep(poll) { node, err := c.Nodes().Get(name) if err != nil { Logf("Couldn't get node %s", name) continue } if isNodeReadySetAsExpected(node, wantReady) { return true } } Logf("Node %s didn't reach desired readiness (%t) within %v", name, wantReady, timeout) return false } // checks whether all registered nodes are ready func allNodesReady(c *client.Client, timeout time.Duration) error { Logf("Waiting up to %v for all nodes to be ready", timeout) var notReady []api.Node err := wait.Poll(poll, timeout, func() (bool, error) { notReady = nil nodes, err := c.Nodes().List(labels.Everything(), fields.Everything()) if err != nil { return false, err } for _, node := range nodes.Items { if !isNodeReadySetAsExpected(&node, true) { notReady = append(notReady, node) } } return len(notReady) == 0, nil }) if err != nil && err != wait.ErrWaitTimeout { return err } if len(notReady) > 0 { return fmt.Errorf("Not ready nodes: %v", notReady) } return nil } // Filters nodes in NodeList in place, removing nodes that do not // satisfy the given condition // TODO: consider merging with pkg/client/cache.NodeLister func filterNodes(nodeList *api.NodeList, fn func(node api.Node) bool) { var l []api.Node for _, node := range nodeList.Items { if fn(node) { l = append(l, node) } } nodeList.Items = l } // LatencyMetrics stores data about request latency at a given quantile // broken down by verb (e.g. GET, PUT, LIST) and resource (e.g. pods, services). type LatencyMetric struct { Verb string Resource string // 0 <= quantile <=1, e.g. 0.95 is 95%tile, 0.5 is median. Quantile float64 Latency time.Duration } // latencyMetricIngestor implements extraction.Ingester type latencyMetricIngester []LatencyMetric func (l *latencyMetricIngester) Ingest(samples model.Samples) error { for _, sample := range samples { // Example line: // apiserver_request_latencies_summary{resource="namespaces",verb="LIST",quantile="0.99"} 908 if sample.Metric[model.MetricNameLabel] != "apiserver_request_latencies_summary" { continue } resource := string(sample.Metric["resource"]) verb := string(sample.Metric["verb"]) latency := sample.Value quantile, err := strconv.ParseFloat(string(sample.Metric[model.QuantileLabel]), 64) if err != nil { return err } *l = append(*l, LatencyMetric{ verb, resource, quantile, time.Duration(int64(latency)) * time.Microsecond, }) } return nil } // LatencyMetricByLatency implements sort.Interface for []LatencyMetric based on // the latency field. type LatencyMetricByLatency []LatencyMetric func (a LatencyMetricByLatency) Len() int { return len(a) } func (a LatencyMetricByLatency) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a LatencyMetricByLatency) Less(i, j int) bool { return a[i].Latency < a[j].Latency } func ReadLatencyMetrics(c *client.Client) ([]LatencyMetric, error) { body, err := getMetrics(c) if err != nil { return nil, err } var ingester latencyMetricIngester err = extraction.Processor004.ProcessSingle(strings.NewReader(body), &ingester, &extraction.ProcessOptions{}) return ingester, err } // Prints summary metrics for request types with latency above threshold // and returns number of such request types. func HighLatencyRequests(c *client.Client, threshold time.Duration, ignoredResources util.StringSet) (int, error) { ignoredVerbs := util.NewStringSet("WATCHLIST", "PROXY") metrics, err := ReadLatencyMetrics(c) if err != nil { return 0, err } sort.Sort(sort.Reverse(LatencyMetricByLatency(metrics))) var badMetrics []LatencyMetric top := 5 for _, metric := range metrics { if ignoredResources.Has(metric.Resource) || ignoredVerbs.Has(metric.Verb) { continue } isBad := false if metric.Latency > threshold && // We are only interested in 99%tile, but for logging purposes // it's useful to have all the offending percentiles. metric.Quantile <= 0.99 { badMetrics = append(badMetrics, metric) isBad = true } if top > 0 || isBad { top-- prefix := "" if isBad { prefix = "WARNING " } Logf("%vTop latency metric: %+v", prefix, metric) } } return len(badMetrics), nil } // Reset latency metrics in apiserver. func resetMetrics(c *client.Client) error { Logf("Resetting latency metrics in apiserver...") body, err := c.Get().AbsPath("/resetMetrics").DoRaw() if err != nil { return err } if string(body) != "metrics reset\n" { return fmt.Errorf("Unexpected response: %q", string(body)) } return nil } // Retrieve metrics information func getMetrics(c *client.Client) (string, error) { body, err := c.Get().AbsPath("/metrics").DoRaw() if err != nil { return "", err } return string(body), nil } // Retrieve debug information func getDebugInfo(c *client.Client) (map[string]string, error) { data := make(map[string]string) for _, key := range []string{"block", "goroutine", "heap", "threadcreate"} { resp, err := http.Get(c.Get().AbsPath(fmt.Sprintf("debug/pprof/%s", key)).URL().String() + "?debug=2") if err != nil { Logf("Warning: Error trying to fetch %s debug data: %v", key, err) continue } body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { Logf("Warning: Error trying to read %s debug data: %v", key, err) } data[key] = string(body) } return data, nil } func writePerfData(c *client.Client, dirName string, postfix string) error { fname := fmt.Sprintf("%s/metrics_%s.txt", dirName, postfix) handler, err := os.Create(fname) if err != nil { return fmt.Errorf("Error creating file '%s': %v", fname, err) } metrics, err := getMetrics(c) if err != nil { return fmt.Errorf("Error retrieving metrics: %v", err) } _, err = handler.WriteString(metrics) if err != nil { return fmt.Errorf("Error writing metrics: %v", err) } err = handler.Close() if err != nil { return fmt.Errorf("Error closing '%s': %v", fname, err) } debug, err := getDebugInfo(c) if err != nil { return fmt.Errorf("Error retrieving debug information: %v", err) } for key, value := range debug { fname := fmt.Sprintf("%s/%s_%s.txt", dirName, key, postfix) handler, err = os.Create(fname) if err != nil { return fmt.Errorf("Error creating file '%s': %v", fname, err) } _, err = handler.WriteString(value) if err != nil { return fmt.Errorf("Error writing %s: %v", key, err) } err = handler.Close() if err != nil { return fmt.Errorf("Error closing '%s': %v", fname, err) } } return nil } // parseKVLines parses output that looks like lines containing "<key>: <val>" // and returns <val> if <key> is found. Otherwise, it returns the empty string. func parseKVLines(output, key string) string { delim := ":" key = key + delim for _, line := range strings.Split(output, "\n") { pieces := strings.SplitAfterN(line, delim, 2) if len(pieces) != 2 { continue } k, v := pieces[0], pieces[1] if k == key { return strings.TrimSpace(v) } } return "" } func restartKubeProxy(host string) error { // TODO: Make it work for all providers. if !providerIs("gce", "gke", "aws") { return fmt.Errorf("unsupported provider: %s", testContext.Provider) } _, _, code, err := SSH("sudo /etc/init.d/kube-proxy restart", host, testContext.Provider) if err != nil || code != 0 { return fmt.Errorf("couldn't restart kube-proxy: %v (code %v)", err, code) } return nil } func restartApiserver() error { // TODO: Make it work for all providers. if !providerIs("gce", "gke", "aws") { return fmt.Errorf("unsupported provider: %s", testContext.Provider) } var command string if providerIs("gce", "gke") { command = "sudo docker ps | grep /kube-apiserver | cut -d ' ' -f 1 | xargs sudo docker kill" } else { command = "sudo /etc/init.d/kube-apiserver restart" } _, _, code, err := SSH(command, getMasterHost()+":22", testContext.Provider) if err != nil || code != 0 { return fmt.Errorf("couldn't restart apiserver: %v (code %v)", err, code) } return nil } func waitForApiserverUp(c *client.Client) error { for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) { body, err := c.Get().AbsPath("/healthz").Do().Raw() if err == nil && string(body) == "ok" { return nil } } return fmt.Errorf("waiting for apiserver timed out") }
[ "\"KUBE_SSH_USER\"", "\"USER\"", "\"HOME\"" ]
[]
[ "USER", "HOME", "KUBE_SSH_USER" ]
[]
["USER", "HOME", "KUBE_SSH_USER"]
go
3
0
experiments/generic/pod-memory-hog-exec/experiment/pod-memory-hog-exec.go
package experiment import ( "os" "github.com/litmuschaos/chaos-operator/pkg/apis/litmuschaos/v1alpha1" litmusLIB "github.com/Vr00mm/litmus-chaos-toolkit/chaoslib/litmus/pod-memory-hog-exec/lib" clients "github.com/Vr00mm/litmus-chaos-toolkit/pkg/clients" "github.com/Vr00mm/litmus-chaos-toolkit/pkg/events" experimentEnv "github.com/Vr00mm/litmus-chaos-toolkit/pkg/generic/pod-memory-hog-exec/environment" experimentTypes "github.com/Vr00mm/litmus-chaos-toolkit/pkg/generic/pod-memory-hog-exec/types" "github.com/Vr00mm/litmus-chaos-toolkit/pkg/log" "github.com/Vr00mm/litmus-chaos-toolkit/pkg/probe" "github.com/Vr00mm/litmus-chaos-toolkit/pkg/result" "github.com/Vr00mm/litmus-chaos-toolkit/pkg/status" "github.com/Vr00mm/litmus-chaos-toolkit/pkg/types" "github.com/Vr00mm/litmus-chaos-toolkit/pkg/utils/common" "github.com/sirupsen/logrus" ) // PodMemoryHogExec inject the pod-memory-hog-exec chaos func PodMemoryHogExec(clients clients.ClientSets) { experimentsDetails := experimentTypes.ExperimentDetails{} resultDetails := types.ResultDetails{} eventsDetails := types.EventDetails{} chaosDetails := types.ChaosDetails{} //Fetching all the ENV passed from the runner pod log.Infof("[PreReq]: Getting the ENV for the %v experiment", os.Getenv("EXPERIMENT_NAME")) experimentEnv.GetENV(&experimentsDetails) // Initialize the chaos attributes types.InitialiseChaosVariables(&chaosDetails) // Initialize Chaos Result Parameters types.SetResultAttributes(&resultDetails, chaosDetails) if experimentsDetails.EngineName != "" { // Initialize the probe details. Bail out upon error, as we haven't entered exp business logic yet if err := probe.InitializeProbesInChaosResultDetails(&chaosDetails, clients, &resultDetails); err != nil { log.Errorf("Unable to initialize the probes, err: %v", err) return } } //Updating the chaos result in the beginning of experiment log.Infof("[PreReq]: Updating the chaos result of %v experiment (SOT)", experimentsDetails.ExperimentName) if err := result.ChaosResult(&chaosDetails, clients, &resultDetails, "SOT"); err != nil { log.Errorf("Unable to Create the Chaos Result, err: %v", err) failStep := "[pre-chaos]: Failed to update the chaos result of pod-memory-hog-exec experiment (SOT), err: " + err.Error() result.RecordAfterFailure(&chaosDetails, &resultDetails, failStep, clients, &eventsDetails) return } // Set the chaos result uid result.SetResultUID(&resultDetails, clients, &chaosDetails) // generating the event in chaosresult to marked the verdict as awaited msg := "experiment: " + experimentsDetails.ExperimentName + ", Result: Awaited" types.SetResultEventAttributes(&eventsDetails, types.AwaitedVerdict, msg, "Normal", &resultDetails) events.GenerateEvents(&eventsDetails, clients, &chaosDetails, "ChaosResult") //DISPLAY THE APP INFORMATION log.InfoWithValues("The application information is as follows", logrus.Fields{ "Namespace": experimentsDetails.AppNS, "Label": experimentsDetails.AppLabel, "Chaos Duration": experimentsDetails.ChaosDuration, "Memory Consumption": experimentsDetails.MemoryConsumption, }) // Calling AbortWatcher go routine, it will continuously watch for the abort signal and generate the required events and result go common.AbortWatcherWithoutExit(experimentsDetails.ExperimentName, clients, &resultDetails, &chaosDetails, &eventsDetails) //PRE-CHAOS APPLICATION STATUS CHECK if chaosDetails.DefaultAppHealthCheck { log.Info("[Status]: Verify that the AUT (Application Under Test) is running (pre-chaos)") if err := status.AUTStatusCheck(experimentsDetails.AppNS, experimentsDetails.AppLabel, experimentsDetails.TargetContainer, experimentsDetails.Timeout, experimentsDetails.Delay, clients, &chaosDetails); err != nil { log.Errorf("Application status check failed, err: %v", err) failStep := "[pre-chaos]: Failed to verify that the AUT (Application Under Test) is in running state, err: " + err.Error() types.SetEngineEventAttributes(&eventsDetails, types.PreChaosCheck, "AUT: Not Running", "Warning", &chaosDetails) events.GenerateEvents(&eventsDetails, clients, &chaosDetails, "ChaosEngine") result.RecordAfterFailure(&chaosDetails, &resultDetails, failStep, clients, &eventsDetails) return } } if experimentsDetails.EngineName != "" { // marking AUT as running, as we already checked the status of application under test msg := common.GetStatusMessage(chaosDetails.DefaultAppHealthCheck, "AUT: Running", "") // run the probes in the pre-chaos check if len(resultDetails.ProbeDetails) != 0 { if err := probe.RunProbes(&chaosDetails, clients, &resultDetails, "PreChaos", &eventsDetails); err != nil { log.Errorf("Probe Failed, err: %v", err) failStep := "[pre-chaos]: Failed while running probes, err: " + err.Error() msg := common.GetStatusMessage(chaosDetails.DefaultAppHealthCheck, "AUT: Running", "Unsuccessful") types.SetEngineEventAttributes(&eventsDetails, types.PreChaosCheck, msg, "Warning", &chaosDetails) events.GenerateEvents(&eventsDetails, clients, &chaosDetails, "ChaosEngine") result.RecordAfterFailure(&chaosDetails, &resultDetails, failStep, clients, &eventsDetails) return } msg = common.GetStatusMessage(chaosDetails.DefaultAppHealthCheck, "AUT: Running", "Successful") } // generating the events for the pre-chaos check types.SetEngineEventAttributes(&eventsDetails, types.PreChaosCheck, msg, "Normal", &chaosDetails) events.GenerateEvents(&eventsDetails, clients, &chaosDetails, "ChaosEngine") } // Including the litmus lib for pod-memory-hog-exec switch experimentsDetails.ChaosLib { case "litmus": if err := litmusLIB.PrepareMemoryExecStress(&experimentsDetails, clients, &resultDetails, &eventsDetails, &chaosDetails); err != nil { log.Errorf("[Error]: pod memory hog failed, err: %v", err) failStep := "[chaos]: Failed inside the chaoslib, err: " + err.Error() result.RecordAfterFailure(&chaosDetails, &resultDetails, failStep, clients, &eventsDetails) return } default: log.Error("[Invalid]: Please Provide the correct LIB") failStep := "[chaos]: no match was found for the specified lib" result.RecordAfterFailure(&chaosDetails, &resultDetails, failStep, clients, &eventsDetails) return } log.Infof("[Confirmation]: %v chaos has been injected successfully", experimentsDetails.ExperimentName) resultDetails.Verdict = v1alpha1.ResultVerdictPassed //POST-CHAOS APPLICATION STATUS CHECK if chaosDetails.DefaultAppHealthCheck { log.Info("[Status]: Verify that the AUT (Application Under Test) is running (post-chaos)") if err := status.AUTStatusCheck(experimentsDetails.AppNS, experimentsDetails.AppLabel, experimentsDetails.TargetContainer, experimentsDetails.Timeout, experimentsDetails.Delay, clients, &chaosDetails); err != nil { log.Infof("Application status check failed, err: %v", err) failStep := "[post-chaos]: Failed to verify that the AUT (Application Under Test) is running, err: " + err.Error() types.SetEngineEventAttributes(&eventsDetails, types.PostChaosCheck, "AUT: Not Running", "Warning", &chaosDetails) events.GenerateEvents(&eventsDetails, clients, &chaosDetails, "ChaosEngine") result.RecordAfterFailure(&chaosDetails, &resultDetails, failStep, clients, &eventsDetails) return } } if experimentsDetails.EngineName != "" { // marking AUT as running, as we already checked the status of application under test msg := common.GetStatusMessage(chaosDetails.DefaultAppHealthCheck, "AUT: Running", "") // run the probes in the post-chaos check if len(resultDetails.ProbeDetails) != 0 { if err := probe.RunProbes(&chaosDetails, clients, &resultDetails, "PostChaos", &eventsDetails); err != nil { log.Errorf("Probes Failed, err: %v", err) failStep := "[post-chaos]: Failed while running probes, err: " + err.Error() msg := common.GetStatusMessage(chaosDetails.DefaultAppHealthCheck, "AUT: Running", "Unsuccessful") types.SetEngineEventAttributes(&eventsDetails, types.PostChaosCheck, msg, "Warning", &chaosDetails) events.GenerateEvents(&eventsDetails, clients, &chaosDetails, "ChaosEngine") result.RecordAfterFailure(&chaosDetails, &resultDetails, failStep, clients, &eventsDetails) return } msg = common.GetStatusMessage(chaosDetails.DefaultAppHealthCheck, "AUT: Running", "Successful") } // generating post chaos event types.SetEngineEventAttributes(&eventsDetails, types.PostChaosCheck, msg, "Normal", &chaosDetails) events.GenerateEvents(&eventsDetails, clients, &chaosDetails, "ChaosEngine") } //Updating the chaosResult in the end of experiment log.Infof("[The End]: Updating the chaos result of %v experiment (EOT)", experimentsDetails.ExperimentName) if err := result.ChaosResult(&chaosDetails, clients, &resultDetails, "EOT"); err != nil { log.Errorf("Unable to Update the Chaos Result, err: %v", err) return } // generating the event in chaosresult to marked the verdict as pass/fail msg = "experiment: " + experimentsDetails.ExperimentName + ", Result: " + string(resultDetails.Verdict) reason := types.PassVerdict eventType := "Normal" if resultDetails.Verdict != "Pass" { reason = types.FailVerdict eventType = "Warning" } types.SetResultEventAttributes(&eventsDetails, reason, msg, eventType, &resultDetails) events.GenerateEvents(&eventsDetails, clients, &chaosDetails, "ChaosResult") if experimentsDetails.EngineName != "" { msg := experimentsDetails.ExperimentName + " experiment has been " + string(resultDetails.Verdict) + "ed" types.SetEngineEventAttributes(&eventsDetails, types.Summary, msg, "Normal", &chaosDetails) events.GenerateEvents(&eventsDetails, clients, &chaosDetails, "ChaosEngine") } }
[ "\"EXPERIMENT_NAME\"" ]
[]
[ "EXPERIMENT_NAME" ]
[]
["EXPERIMENT_NAME"]
go
1
0
stograde/common/run.py
import copy import io import os import pty import subprocess from typing import List, Optional, Tuple from ..common.run_status import RunStatus def run(cmd: List[str], *, interact: bool = False, input_data: Optional[bytes] = None, timeout: Optional[float] = None) -> Tuple[RunStatus, str, bool]: if interact: return run_interactive(cmd) else: return run_static(cmd, input_data, timeout) def run_interactive(cmd: List[str]) -> Tuple[RunStatus, str, bool]: status = RunStatus.SUCCESS print('Recording {}. Send EOF (^D) to end.'.format(cmd), end='\n\n') # This is mostly taken from the stdlib's `pty` docs with io.BytesIO() as script: def read(fd): data = os.read(fd, 1024) script.write(data) return data pty.spawn(cmd, read) try: result = script.getvalue().decode(encoding='utf-8') except UnicodeDecodeError: result = script.getvalue().decode(encoding='cp437') print('\nSubmission recording completed.') runagain = input('Do you want to run the submission again? [y/N]: ') again = runagain.lower().startswith('y') return status, result, again def run_static(cmd: List[str], input_data: Optional[bytes] = None, timeout: Optional[int] = None) -> Tuple[RunStatus, str, bool]: status = RunStatus.SUCCESS result = '' try: proc_result = subprocess.run( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, input=input_data, env=copy_env(), check=True) if hasattr(proc_result, 'stdout'): result = proc_result.stdout except subprocess.CalledProcessError as err: status = RunStatus.CALLED_PROCESS_ERROR result = err.output if err.output else str(err) except subprocess.TimeoutExpired as err: status = RunStatus.TIMEOUT_EXPIRED result = err.output if err.output else str(err) except FileNotFoundError as err: status = RunStatus.FILE_NOT_FOUND result = str(err) except ProcessLookupError as err: status = RunStatus.PROCESS_LOOKUP_ERROR result = str(err) try: if not isinstance(result, str): result = str(result, 'utf-8') except UnicodeDecodeError: result = str(result, 'cp437') return status, result, False # This is to catch glibc errors, because it prints to /dev/tty # instead of stderr. See https://stackoverflow.com/a/27797579 def copy_env(): env = copy.copy(os.environ) env["LIBC_FATAL_STDERR_"] = "1" return env
[]
[]
[]
[]
[]
python
0
0
core/api.go
// Package core provides an API to include and use the GraphJin compiler with your own code. // For detailed documentation visit https://graphjin.com // // Example usage: /* package main import ( "database/sql" "fmt" "time" "github.com/dosco/graphjin/core" _ "github.com/jackc/pgx/v4/stdlib" ) func main() { db, err := sql.Open("pgx", "postgres://postgrs:@localhost:5432/example_db") if err != nil { log.Fatal(err) } gj, err := core.NewGraphJin(nil, db) if err != nil { log.Fatal(err) } query := ` query { posts { id title } }` ctx = context.WithValue(ctx, core.UserIDKey, 1) res, err := gj.GraphQL(ctx, query, nil) if err != nil { log.Fatal(err) } } */ package core import ( "context" "crypto/sha256" "database/sql" "encoding/json" "errors" _log "log" "os" "sync" "sync/atomic" "github.com/chirino/graphql" "github.com/dop251/goja" "github.com/dosco/graphjin/core/internal/allow" "github.com/dosco/graphjin/core/internal/crypto" "github.com/dosco/graphjin/core/internal/psql" "github.com/dosco/graphjin/core/internal/qcode" "github.com/dosco/graphjin/core/internal/sdata" "github.com/dosco/graphjin/core/internal/util" "github.com/spf13/afero" ) type contextkey int // Constants to set values on the context passed to the NewGraphJin function const ( // Name of the authentication provider. Eg. google, github, etc UserIDProviderKey contextkey = iota // The raw user id (jwt sub) value UserIDRawKey // User ID value for authenticated users UserIDKey // User role if pre-defined UserRoleKey ) // GraphJin struct is an instance of the GraphJin engine it holds all the required information like // datase schemas, relationships, etc that the GraphQL to SQL compiler would need to do it's job. type graphjin struct { conf *Config db *sql.DB log *_log.Logger fs afero.Fs dbtype string dbinfo *sdata.DBInfo schema *sdata.DBSchema allowList *allow.List encKey [32]byte apq apqCache queries map[string]*queryComp roles map[string]*Role roleStmt string roleStmtMD psql.Metadata rmap map[string]resItem abacEnabled bool qc *qcode.Compiler pc *psql.Compiler ge *graphql.Engine subs sync.Map scripts sync.Map prod bool } type GraphJin struct { atomic.Value } type script struct { ReqFunc reqFunc RespFunc respFunc vm *goja.Runtime util.Once } type Option func(*graphjin) error // NewGraphJin creates the GraphJin struct, this involves querying the database to learn its // schemas and relationships func NewGraphJin(conf *Config, db *sql.DB, options ...Option) (*GraphJin, error) { gj, err := newGraphJin(conf, db, nil, options...) if err != nil { return nil, err } g := &GraphJin{} g.Store(gj) if err := g.initDBWatcher(); err != nil { return nil, err } return g, nil } // newGraphJin helps with writing tests and benchmarks func newGraphJin(conf *Config, db *sql.DB, dbinfo *sdata.DBInfo, options ...Option) (*graphjin, error) { if conf == nil { conf = &Config{Debug: true, DisableAllowList: true} } gj := &graphjin{ conf: conf, db: db, dbinfo: dbinfo, log: _log.New(os.Stdout, "", 0), prod: conf.Production || os.Getenv("GO_ENV") == "production", } if err := gj.initAPQCache(); err != nil { return nil, err } //order matters, do not re-order the initializers if err := gj.initConfig(); err != nil { return nil, err } for _, op := range options { if err := op(gj); err != nil { return nil, err } } if err := gj.initFS(); err != nil { return nil, err } if err := gj.initDiscover(); err != nil { return nil, err } if err := gj.initResolvers(); err != nil { return nil, err } if err := gj.initSchema(); err != nil { return nil, err } if err := gj.initAllowList(); err != nil { return nil, err } if err := gj.initCompilers(); err != nil { return nil, err } if err := gj.initGraphQLEgine(); err != nil { return nil, err } if err := gj.prepareRoleStmt(); err != nil { return nil, err } if err := gj.initScripting(); err != nil { return nil, err } if conf.SecretKey != "" { sk := sha256.Sum256([]byte(conf.SecretKey)) conf.SecretKey = "" gj.encKey = sk } else { gj.encKey = crypto.NewEncryptionKey() } return gj, nil } func OptionSetFS(fs afero.Fs) Option { return func(s *graphjin) error { s.fs = fs return nil } } type Error struct { Message string `json:"message"` } // Result struct contains the output of the GraphQL function this includes resulting json from the // database query and any error information type Result struct { op qcode.QType name string sql string role string cacheControl string Errors []Error `json:"errors,omitempty"` Data json.RawMessage `json:"data,omitempty"` Extensions *extensions `json:"extensions,omitempty"` } // ReqConfig is used to pass request specific config values to the GraphQLEx and SubscribeEx functions. Dynamic variables can be set here. type ReqConfig struct { APQKey string Vars map[string]interface{} } // GraphQL function is called on the GraphJin struct to convert the provided GraphQL query into an // SQL query and execute it on the database. In production mode prepared statements are directly used // and no query compiling takes places. // // In developer mode all names queries are saved into a file `allow.list` and in production mode only // queries from this file can be run. func (g *GraphJin) GraphQL( c context.Context, query string, vars json.RawMessage, rc *ReqConfig) (*Result, error) { var err error gj := g.Load().(*graphjin) ct := gcontext{ Context: c, gj: gj, rc: rc, } if rc != nil && rc.APQKey != "" && query == "" { if v, ok := gj.apq.Get(rc.APQKey); ok { if v.query != "" { query = v.query } ct.op = v.op ct.name = v.name } else { err = errors.New("PersistedQueryNotFound") } } else { ct.op, ct.name = qcode.GetQType(query) } res := &Result{ op: ct.op, name: ct.name, } if err != nil { res.Errors = []Error{{Message: err.Error()}} return res, err } if ct.op == qcode.QTSubscription { return res, errors.New("use 'core.Subscribe' for subscriptions") } if ct.op == qcode.QTMutation && gj.schema.DBType() == "mysql" { return res, errors.New("mysql: mutations not supported") } // use the chirino/graphql library for introspection queries // disabled when allow list is enforced if !gj.prod && ct.name == "IntrospectionQuery" { r := gj.ge.ServeGraphQL(&graphql.Request{Query: query}) res.Data = r.Data if r.Error() != nil { res.Errors = []Error{{Message: r.Error().Error()}} } return res, r.Error() } var role string if v, ok := c.Value(UserRoleKey).(string); ok { role = v } else if c.Value(UserIDKey) != nil { role = "user" } else { role = "anon" } qreq := queryReq{ op: ct.op, name: ct.name, query: []byte(query), vars: vars, } qres, err := ct.execQuery(qreq, role) if err != nil { res.Errors = []Error{{Message: err.Error()}} } if qres.qc != nil { res.sql = qres.qc.st.sql if qres.qc.st.qc != nil { res.cacheControl = qres.qc.st.qc.Cache.Header } } res.Data = json.RawMessage(qres.data) res.role = qres.role return res, err } // Reload does database discover and reinitializes GraphJin. func (g *GraphJin) Reload() error { gj := g.Load().(*graphjin) gjNew, err := newGraphJin(gj.conf, gj.db, nil) if err == nil { g.Store(gjNew) } return err } // IsProd return true for production mode or false for development mode func (g *GraphJin) IsProd() bool { gj := g.Load().(*graphjin) return gj.prod } // Operation function return the operation type and name from the query. // It uses a very fast algorithm to extract the operation without having to parse the query. func Operation(query string) (OpType, string) { qt, name := qcode.GetQType(query) return OpType(qt), name }
[ "\"GO_ENV\"" ]
[]
[ "GO_ENV" ]
[]
["GO_ENV"]
go
1
0
cmd/bot/main.go
package main import ( "os" "fmt" "log" "time" "strconv" handlers "tasksbot/pkg/handlers" tb "gopkg.in/tucnak/telebot.v2" gokv "github.com/philippgille/gokv" gomap "github.com/philippgille/gokv/gomap" redis "github.com/philippgille/gokv/redis" ) func main() { // get envs token := os.Getenv("BOT_TOKEN") channelID, err := strconv.Atoi(os.Getenv("BOT_CHANNEL_ID")) if err != nil { log.Fatal(err) return } // init kv storage store, closable := getStore() if closable { defer store.Close() } // init telebot channel := tb.ChatID(channelID) bot, err := tb.NewBot(tb.Settings{ Token: token, Poller: &tb.LongPoller{Timeout: 10*time.Second}, }) if err != nil { log.Fatal(err) return } // message handlers bot.Handle("/start", func(msg *tb.Message) { handlers.Start(bot, msg) }) bot.Handle("/create", func(msg *tb.Message) { handlers.Create(bot, msg, store) }) bot.Handle(tb.OnText, func(msg *tb.Message) { handlers.OnText(bot, msg, store) }) // callback handlers bot.Handle(tb.OnCallback, func(cb *tb.Callback) { switch cb.Data { case "\fconfirm": handlers.Confirm(bot, cb, channel) case "\fcancel": handlers.Cancel(bot, cb) case "\faccept": handlers.Accept(bot, cb) } }) log.Println("bot started") bot.Start() } func getStore() (gokv.Store, bool) { if os.Getenv("REDIS_ADDRESS") != "" { db := 0 if os.Getenv("REDIS_DB") != "" { db, _ = strconv.Atoi(os.Getenv("REDIS_DB")) } options := redis.Options{ Address: os.Getenv("REDIS_ADDRESS"), Password: os.Getenv("REDIS_PASSWORD"), DB: db} store, _ := redis.NewClient(options) passwordInfo := "password is empty" if os.Getenv("REDIS_PASSWORD") != "" { passwordInfo = "password is not empty" } log.Println(fmt.Sprintf("chosed redis as storage. address: %s, db: %d, %s", options.Address, db, passwordInfo)) return store, true } else { options := gomap.DefaultOptions store := gomap.NewStore(options) log.Println("chosed gomap as storage") return store, false } }
[ "\"BOT_TOKEN\"", "\"BOT_CHANNEL_ID\"", "\"REDIS_ADDRESS\"", "\"REDIS_DB\"", "\"REDIS_DB\"", "\"REDIS_ADDRESS\"", "\"REDIS_PASSWORD\"", "\"REDIS_PASSWORD\"" ]
[]
[ "BOT_CHANNEL_ID", "REDIS_ADDRESS", "REDIS_PASSWORD", "BOT_TOKEN", "REDIS_DB" ]
[]
["BOT_CHANNEL_ID", "REDIS_ADDRESS", "REDIS_PASSWORD", "BOT_TOKEN", "REDIS_DB"]
go
5
0
cmd/rebase/main.go
package main import ( "bytes" "flag" "io/ioutil" "log" "os" "path/filepath" "github.com/BurntSushi/toml" "github.com/buildpacks/imgutil/remote" "github.com/buildpacks/lifecycle" "github.com/buildpacks/lifecycle/api" "github.com/buildpacks/lifecycle/cmd" "github.com/pkg/errors" "github.com/pivotal/kpack/pkg/buildchange" "github.com/pivotal/kpack/pkg/dockercreds" "github.com/pivotal/kpack/pkg/flaghelpers" ) const ( buildSecretsDir = "/var/build-secrets" ) var ( runImage = flag.String("run-image", os.Getenv("RUN_IMAGE"), "The new run image to rebase") lastBuiltImage = flag.String("last-built-image", os.Getenv("LAST_BUILT_IMAGE"), "The previous image to rebase") buildChanges = flag.String("build-changes", os.Getenv("BUILD_CHANGES"), "JSON string of build changes and their reason") reportFilePath = flag.String("report", os.Getenv("REPORT_FILE_PATH"), "The location at which to write the report.toml") dockerCredentials flaghelpers.CredentialsFlags dockerCfgCredentials flaghelpers.CredentialsFlags dockerConfigCredentials flaghelpers.CredentialsFlags imagePullSecrets flaghelpers.CredentialsFlags ) func init() { flag.Var(&dockerCredentials, "basic-docker", "Basic authentication for docker of the form 'secretname=git.domain.com'") flag.Var(&dockerCfgCredentials, "dockercfg", "Docker Cfg credentials in the form of the path to the credential") flag.Var(&dockerConfigCredentials, "dockerconfig", "Docker Config JSON credentials in the form of the path to the credential") flag.Var(&imagePullSecrets, "imagepull", "Builder Image pull credentials in the form of the path to the credential") } func main() { flag.Parse() tags := flag.Args() logger := log.New(os.Stdout, "", 0) if err := buildchange.Log(logger, *buildChanges); err != nil { logger.Println(err) } cmd.Exit(rebase(tags, logger)) } func rebase(tags []string, logger *log.Logger) error { if len(tags) < 1 { return cmd.FailCode(cmd.CodeInvalidArgs, "must provide one or more image tags") } keychain, err := dockercreds.ParseMountedAnnotatedSecrets(buildSecretsDir, dockerCredentials) if err != nil { return cmd.FailErrCode(err, cmd.CodeInvalidArgs) } for _, c := range combine(dockerCfgCredentials, dockerConfigCredentials, imagePullSecrets) { credPath := filepath.Join(buildSecretsDir, c) dockerCfgCreds, err := dockercreds.ParseDockerPullSecrets(credPath) if err != nil { return err } for domain := range dockerCfgCreds { logger.Printf("Loading secret for %q from secret %q at location %q", domain, c, credPath) } keychain, err = keychain.Append(dockerCfgCreds) if err != nil { return err } } appImage, err := remote.NewImage(tags[0], keychain, remote.FromBaseImage(*lastBuiltImage)) if err != nil { return err } if !appImage.Found() { return errors.Errorf("could not access previous image: %s", *lastBuiltImage) } newBaseImage, err := remote.NewImage(*runImage, keychain, remote.FromBaseImage(*runImage)) if err != nil { return err } if !newBaseImage.Found() { return errors.Errorf("could not access run image: %s", *runImage) } rebaser := lifecycle.Rebaser{ Logger: cmd.DefaultLogger, PlatformAPI: api.MustParse("0.8"), } report, err := rebaser.Rebase(appImage, newBaseImage, tags[1:]) if err != nil { return err } if *reportFilePath == "" { return nil } buf := &bytes.Buffer{} err = toml.NewEncoder(buf).Encode(report) if err != nil { return err } return ioutil.WriteFile(*reportFilePath, buf.Bytes(), 0777) } func combine(credentials ...[]string) []string { var combinded []string for _, creds := range credentials { combinded = append(combinded, creds...) } return combinded }
[ "\"RUN_IMAGE\"", "\"LAST_BUILT_IMAGE\"", "\"BUILD_CHANGES\"", "\"REPORT_FILE_PATH\"" ]
[]
[ "RUN_IMAGE", "BUILD_CHANGES", "REPORT_FILE_PATH", "LAST_BUILT_IMAGE" ]
[]
["RUN_IMAGE", "BUILD_CHANGES", "REPORT_FILE_PATH", "LAST_BUILT_IMAGE"]
go
4
0
test/timings/test_performances.py
#!/usr/bin/env python # BEGIN_COPYRIGHT # # Copyright 2009-2018 CRS4. # # 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. # # END_COPYRIGHT from __future__ import print_function import sys import os import argparse import logging logging.basicConfig(level=logging.INFO) import pydoop import pydoop.hadut as hadut import pydoop.hdfs as hdfs import pydoop.test_support as pts from timer import Timer DEFAULT_SCRIPT = "../../examples/wordcount/bin/wordcount-full.py" CONF = { "mapreduce.job.maps": "2", "mapreduce.job.reduces": "2", "mapreduce.job.name": "wordcount", "mapreduce.pipes.isjavarecordreader": "false", "mapreduce.pipes.isjavarecordwriter": "false" } DATASET_DIR = "dataset" HADOOP_CONF_DIR = pydoop.hadoop_conf() PREFIX = os.getenv("PREFIX", pts.get_wd_prefix()) LOCAL_FILE_PREFIX = "file:/" HDFS_FILE_PREFIX = "hdfs:///" def update_conf(args): if args.D: for kv_pair in args.D: k, v = [_.strip() for _ in kv_pair.split("=")] CONF[k] = v if args.mappers: CONF["mapreduce.job.maps"] = args.mappers if args.reducers: CONF["mapreduce.job.reduces"] = args.reducers def make_parser(): parser = argparse.ArgumentParser() parser.add_argument("--script", metavar="script", help="the script to launch") parser.add_argument("--mappers", metavar="# mappers", type=int, help="the number of mappers for your mapred job") parser.add_argument("--reducers", metavar="# reducers", type=int, help="number of reducers of your mapred job") parser.add_argument("--dataset", metavar="max file size for the dataset", help="set to generate the dataset", type=int) parser.add_argument("-D", metavar="NAME=VALUE", action="append", help="additional Hadoop configuration parameters") return parser def create_dataset(logger, max_file_size_in_mb=200): logger.info("Creating the dataset") INPUT_FILE = "../../examples/input/alice.txt" if not os.path.exists(INPUT_FILE): raise IOError("input file not found") with open(INPUT_FILE) as f: text = f.read() base_text_file_length = len(text) if not os.path.exists("dataset"): os.mkdir("dataset") step_factor = 2 step_file_length = 0 step_file_length_mb = 0 while step_file_length_mb < max_file_size_in_mb: step_file_length = (step_file_length if step_file_length > 0 else base_text_file_length) * step_factor step_file_length_mb = int(step_file_length / 1048576) if step_file_length_mb == 0: continue filename = "dataset/{0}MB".format(step_file_length_mb) logger.info(" ->generating: %s", filename) with open(filename, "w") as f: file_length = 0 while file_length < step_file_length: f.write(text) file_length += base_text_file_length def main(argv): logger = logging.getLogger("main") logger.setLevel(logging.DEBUG) with Timer() as total_time: parser = make_parser() args = parser.parse_args(argv) if args.dataset: print(args.dataset) create_dataset(logger, args.dataset) if args.script: piped_code_file = args.script else: piped_code_file = DEFAULT_SCRIPT if not os.path.exists(piped_code_file): raise IOError("script {0} not found !!!".format(piped_code_file)) with open(piped_code_file) as f: pipes_code = pts.adapt_script(f.read()) dataset = [d for d in os.listdir("dataset") if d.endswith("MB")] dataset.sort(key=lambda x: int(x.replace("MB", ""))) logger.info(" Uploading dataset: { %s }", ', '.join(dataset)) if not hadut.path_exists(os.path.join(DATASET_DIR)): logger.info(" dataset folder created") hdfs.mkdir(DATASET_DIR) for data_filename in dataset: source_path = os.path.join(DATASET_DIR, data_filename) dest_path = os.path.join(DATASET_DIR, data_filename) if not hadut.path_exists(os.path.join(DATASET_DIR, data_filename)): logger.info(" -> uploading %s...", source_path) hdfs.put(source_path, dest_path) update_conf(args) results = dict() for data_input in dataset: with Timer() as t: runner = hadut.PipesRunner(prefix=PREFIX, logger=logger) logger.info("Running the script %s with data input %s..", piped_code_file, data_input) data_input_path = os.path.join(DATASET_DIR, data_input) runner.set_input(data_input_path, put=False) runner.set_exe(pipes_code) runner.run(properties=CONF, hadoop_conf_dir=HADOOP_CONF_DIR, logger=logger) res = runner.collect_output() print(data_input_path) local_wc = pts.LocalWordCount(data_input_path) logging.info(local_wc.check(res)) # print(res) # runner.clean() results[data_input] = (t.secs, t.msecs) print("\n\n RESULTs") print("=" * (len(piped_code_file) + 15)) print(" * script: {0}".format(piped_code_file)) print(" * mappers: {0}".format(CONF["mapreduce.job.maps"])) print(" * reducers: {0}".format(CONF["mapreduce.job.reduces"])) print(" * dataset: [{0}]".format(",".join(dataset))) print(" * times (input -> secs):") for data_input in dataset: print(" - {0} -> {1} secs.".format( data_input, results[data_input][0] )) print("\n => Total execution time: {0}".format(total_time.secs)) print("=" * (len(piped_code_file) + 15)) print("\n") if __name__ == "__main__": main(sys.argv[1:])
[]
[]
[ "PREFIX" ]
[]
["PREFIX"]
python
1
0
nbdev/export.py
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/00_export.ipynb (unless otherwise specified). __all__ = ['first', 'read_nb', 'check_re', 'is_export', 'find_default_export', 'export_names', 'extra_add', 'relative_import', 'reset_nbdev_module', 'get_nbdev_module', 'save_nbdev_module', 'create_mod_file', 'add_init', 'update_version', 'update_baseurl', 'notebook2script', 'DocsTestClass'] # Cell from .imports import * from fastscript import * # Cell def first(x): "First element of `x`, or None if missing" try: return next(iter(x)) except StopIteration: return None # Cell def read_nb(fname): "Read the notebook in `fname`." with open(Path(fname),'r', encoding='utf8') as f: return nbformat.reads(f.read(), as_version=4) # Cell def check_re(cell, pat, code_only=True): "Check if `cell` contains a line with regex `pat`" if code_only and cell['cell_type'] != 'code': return if isinstance(pat, str): pat = re.compile(pat, re.IGNORECASE | re.MULTILINE) return pat.search(cell['source']) # Cell _re_blank_export = re.compile(r""" # Matches any line with #export or #exports or #exporti without any module name: ^ # beginning of line (since re.MULTILINE is passed) \s* # any number of whitespace \#\s* # "#", then any number of whitespace export[si]? # export or exports or exporti \s* # any number of whitespace $ # end of line (since re.MULTILINE is passed) """, re.IGNORECASE | re.MULTILINE | re.VERBOSE) # Cell _re_mod_export = re.compile(r""" # Matches any line with #export or #exports or #exporti with a module name and catches it in group 1: ^ # beginning of line (since re.MULTILINE is passed) \s* # any number of whitespace \#\s* # "#", then any number of whitespace export[si]? # export or exports or exporti \s+ # one or more whitespace chars (\S+) # catch a group with any non-whitespace chars \s* # any number of whitespace $ # end of line (since re.MULTILINE is passed) """, re.IGNORECASE | re.MULTILINE | re.VERBOSE) # Cell _re_internal_export = re.compile(r""" # Matches any line with #export or #exports without any module name: ^ # beginning of line (since re.MULTILINE is passed) \s* # any number of whitespace \#\s* # "#", then any number of whitespace exporti # export or exports or exporti \s* # any number of whitespace \S* # any number of non-whitespace chars \s* # any number of whitespace $ # end of line (since re.MULTILINE is passed) """, re.IGNORECASE | re.MULTILINE | re.VERBOSE) # Cell def is_export(cell, default): "Check if `cell` is to be exported and returns the name of the module to export it if provided" tst = check_re(cell, _re_blank_export) if tst: if default is None: print(f"This cell doesn't have an export destination and was ignored:\n{cell['source'][1]}") return default, (_re_internal_export.search(tst.string) is None) tst = check_re(cell, _re_mod_export) if tst: return os.path.sep.join(tst.groups()[0].split('.')), (_re_internal_export.search(tst.string) is None) else: return None # Cell _re_default_exp = re.compile(r""" # Matches any line with #default_exp with a module name and catches it in group 1: ^ # beginning of line (since re.MULTILINE is passed) \s* # any number of whitespace \#\s* # "#", then any number of whitespace default_exp # default_exp \s+ # one or more whitespace chars (\S+) # catch a group with any non-whitespace chars \s* # any number of whitespace $ # end of line (since re.MULTILINE is passed) """, re.IGNORECASE | re.MULTILINE | re.VERBOSE) # Cell def find_default_export(cells): "Find in `cells` the default export module." for cell in cells: tst = check_re(cell, _re_default_exp) if tst: return tst.groups()[0] # Cell _re_patch_func = re.compile(r""" # Catches any function decorated with @patch, its name in group 1 and the patched class in group 2 @patch # At any place in the cell, something that begins with @patch \s*def # Any number of whitespace (including a new line probably) followed by def \s+ # One whitespace or more ([^\(\s]+) # Catch a group composed of anything but whitespace or an opening parenthesis (name of the function) \s*\( # Any number of whitespace followed by an opening parenthesis [^:]* # Any number of character different of : (the name of the first arg that is type-annotated) :\s* # A column followed by any number of whitespace (?: # Non-catching group with either ([^,\s\(\)]*) # a group composed of anything but a comma, a parenthesis or whitespace (name of the class) | # or (\([^\)]*\))) # a group composed of something between parenthesis (tuple of classes) \s* # Any number of whitespace (?:,|\)) # Non-catching group with either a comma or a closing parenthesis """, re.VERBOSE) # Cell _re_typedispatch_func = re.compile(r""" # Catches any function decorated with @typedispatch (@typedispatch # At any place in the cell, catch a group with something that begins with @typedispatch \s*def # Any number of whitespace (including a new line probably) followed by def \s+ # One whitespace or more [^\(]+ # Anything but whitespace or an opening parenthesis (name of the function) \s*\( # Any number of whitespace followed by an opening parenthesis [^\)]* # Any number of character different of ) \)[\s\S]*:) # A closing parenthesis followed by any number of characters and whitespace (type annotation) and : """, re.VERBOSE) # Cell _re_class_func_def = re.compile(r""" # Catches any 0-indented function or class definition with its name in group 1 ^ # Beginning of a line (since re.MULTILINE is passed) (?:async\sdef|def|class) # Non-catching group for def or class \s+ # One whitespace or more ([^\(\s]+) # Catching group with any character except an opening parenthesis or a whitespace (name) \s* # Any number of whitespace (?:\(|:) # Non-catching group with either an opening parenthesis or a : (classes don't need ()) """, re.MULTILINE | re.VERBOSE) # Cell _re_obj_def = re.compile(r""" # Catches any 0-indented object definition (bla = thing) with its name in group 1 ^ # Beginning of a line (since re.MULTILINE is passed) ([_a-zA-Z]+[a-zA-Z0-9_\.]*) # Catch a group which is a valid python variable name \s* # Any number of whitespace (?::\s*\S.*|)= # Non-catching group of either a colon followed by a type annotation, or nothing; followed by an = """, re.MULTILINE | re.VERBOSE) # Cell def _not_private(n): for t in n.split('.'): if (t.startswith('_') and not t.startswith('__')) or t.startswith('@'): return False return '\\' not in t and '^' not in t and '[' not in t and t != 'else' def export_names(code, func_only=False): "Find the names of the objects, functions or classes defined in `code` that are exported." #Format monkey-patches with @patch def _f(gps): nm, cls, t = gps.groups() if cls is not None: return f"def {cls}.{nm}():" return '\n'.join([f"def {c}.{nm}():" for c in re.split(', *', t[1:-1])]) code = _re_typedispatch_func.sub('', code) code = _re_patch_func.sub(_f, code) names = _re_class_func_def.findall(code) if not func_only: names += _re_obj_def.findall(code) return [n for n in names if _not_private(n)] # Cell _re_all_def = re.compile(r""" # Catches a cell with defines \_all\_ = [\*\*] and get that \*\* in group 1 ^_all_ # Beginning of line (since re.MULTILINE is passed) \s*=\s* # Any number of whitespace, =, any number of whitespace \[ # Opening [ ([^\n\]]*) # Catching group with anything except a ] or newline \] # Closing ] """, re.MULTILINE | re.VERBOSE) #Same with __all__ _re__all__def = re.compile(r'^__all__\s*=\s*\[([^\]]*)\]', re.MULTILINE) # Cell def extra_add(code): "Catch adds to `__all__` required by a cell with `_all_=`" if _re_all_def.search(code): names = _re_all_def.search(code).groups()[0] names = re.sub('\s*,\s*', ',', names) names = names.replace('"', "'") code = _re_all_def.sub('', code) code = re.sub(r'([^\n]|^)\n*$', r'\1', code) return names.split(','),code return [],code # Cell def _add2add(fname, names, line_width=120): if len(names) == 0: return with open(fname, 'r', encoding='utf8') as f: text = f.read() tw = TextWrapper(width=120, initial_indent='', subsequent_indent=' '*11, break_long_words=False) re_all = _re__all__def.search(text) start,end = re_all.start(),re_all.end() text_all = tw.wrap(f"{text[start:end-1]}{'' if text[end-2]=='[' else ', '}{', '.join(names)}]") with open(fname, 'w', encoding='utf8') as f: f.write(text[:start] + '\n'.join(text_all) + text[end:]) # Cell def relative_import(name, fname): "Convert a module `name` to a name relative to `fname`" mods = name.split('.') splits = str(fname).split(os.path.sep) if mods[0] not in splits: return name i=len(splits)-1 while i>0 and splits[i] != mods[0]: i-=1 splits = splits[i:] while len(mods)>0 and splits[0] == mods[0]: splits,mods = splits[1:],mods[1:] return '.' * (len(splits)) + '.'.join(mods) # Cell _re_import = ReLibName(r'^(\s*)from (LIB_NAME\.\S*) import (.*)$') # Cell def _deal_import(code_lines, fname): def _replace(m): sp,mod,obj = m.groups() return f"{sp}from {relative_import(mod, fname)} import {obj}" return [_re_import.re.sub(_replace,line) for line in code_lines] # Cell _re_index_custom = re.compile(r'def custom_doc_links\(name\):(.*)$', re.DOTALL) # Cell def reset_nbdev_module(): "Create a skeletton for <code>_nbdev</code>" fname = Config().lib_path/'_nbdev.py' fname.parent.mkdir(parents=True, exist_ok=True) sep = '\n'* (int(Config().get('cell_spacing', '1'))+1) if fname.is_file(): with open(fname, 'r') as f: search = _re_index_custom.search(f.read()) else: search = None prev_code = search.groups()[0] if search is not None else ' return None\n' with open(fname, 'w') as f: f.write(f"# AUTOGENERATED BY NBDEV! DO NOT EDIT!") f.write('\n\n__all__ = ["index", "modules", "custom_doc_links", "git_url"]') f.write('\n\nindex = {}') f.write('\n\nmodules = []') f.write(f'\n\ndoc_url = "{Config().doc_host}{Config().doc_baseurl}"') f.write(f'\n\ngit_url = "{Config().git_url}"') f.write(f'{sep}def custom_doc_links(name):{prev_code}') # Cell class _EmptyModule(): def __init__(self): self.index,self.modules = {},[] self.doc_url,self.git_url = f"{Config().doc_host}{Config().doc_baseurl}",Config().git_url def custom_doc_links(self, name): return None # Cell def get_nbdev_module(): "Reads <code>_nbdev</code>" try: spec = importlib.util.spec_from_file_location(f"{Config().lib_name}._nbdev", Config().lib_path/'_nbdev.py') mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod except: return _EmptyModule() # Cell _re_index_idx = re.compile(r'index\s*=\s*{[^}]*}') _re_index_mod = re.compile(r'modules\s*=\s*\[[^\]]*\]') # Cell def save_nbdev_module(mod): "Save `mod` inside <code>_nbdev</code>" fname = Config().lib_path/'_nbdev.py' with open(fname, 'r') as f: code = f.read() t = r',\n '.join([f'"{k}": "{v}"' for k,v in mod.index.items()]) code = _re_index_idx.sub("index = {"+ t +"}", code) t = r',\n '.join(['"' + f.replace('\\','/') + '"' for f in mod.modules]) code = _re_index_mod.sub(f"modules = [{t}]", code) with open(fname, 'w') as f: f.write(code) # Cell def create_mod_file(fname, nb_path): "Create a module file for `fname`." fname.parent.mkdir(parents=True, exist_ok=True) file_path = os.path.relpath(nb_path, Config().config_file.parent).replace('\\', '/') with open(fname, 'w') as f: f.write(f"# AUTOGENERATED! DO NOT EDIT! File to edit: {file_path} (unless otherwise specified).") f.write('\n\n__all__ = []') # Cell def _notebook2script(fname, silent=False, to_dict=None): "Finds cells starting with `#export` and puts them into a new module" if os.environ.get('IN_TEST',0): return # don't export if running tests sep = '\n'* (int(Config().get('cell_spacing', '1'))+1) fname = Path(fname) nb = read_nb(fname) default = find_default_export(nb['cells']) if default is not None: default = os.path.sep.join(default.split('.')) if to_dict is None: create_mod_file(Config().lib_path/f'{default}.py', Config().nbs_path/f'{fname}') mod = get_nbdev_module() exports = [is_export(c, default) for c in nb['cells']] cells = [(i,c,e) for i,(c,e) in enumerate(zip(nb['cells'],exports)) if e is not None] for i,c,(e,a) in cells: fname_out = Config().lib_path/f'{e}.py' orig = (f'# {"" if a else "Internal "}C' if e==default else f'# Comes from {fname.name}, c') + 'ell\n' code = sep + orig + '\n'.join(_deal_import(c['source'].split('\n')[1:], fname_out)) names = export_names(code) extra,code = extra_add(code) if a: if to_dict is None: _add2add(fname_out, [f"'{f}'" for f in names if '.' not in f and len(f) > 0] + extra) mod.index.update({f: fname.name for f in names}) code = re.sub(r' +$', '', code, flags=re.MULTILINE) if code != sep + orig[:-1]: if to_dict is not None: to_dict[e].append((i, fname, code)) else: with open(fname_out, 'a', encoding='utf8') as f: f.write(code) if f'{e}.py' not in mod.modules: mod.modules.append(f'{e}.py') save_nbdev_module(mod) if not silent: print(f"Converted {fname.name}.") return to_dict # Cell def add_init(path): "Add `__init__.py` in all subdirs of `path` containing python files if it's not there already" for p,d,f in os.walk(path): for f_ in f: if f_.endswith('.py'): if not (Path(p)/'__init__.py').exists(): (Path(p)/'__init__.py').touch() break # Cell _re_version = re.compile('^__version__\s*=.*$', re.MULTILINE) # Cell def update_version(): "Add or update `__version__` in the main `__init__.py` of the library" fname = Config().lib_path/'__init__.py' if not fname.exists(): fname.touch() version = f'__version__ = "{Config().version}"' with open(fname, 'r') as f: code = f.read() if _re_version.search(code) is None: code = version + "\n" + code else: code = _re_version.sub(version, code) with open(fname, 'w') as f: f.write(code) # Cell _re_baseurl = re.compile('^baseurl\s*:.*$', re.MULTILINE) # Cell def update_baseurl(): "Add or update `baseurl` in `_config.yml` for the docs" fname = Config().doc_path/'_config.yml' if not fname.exists(): return with open(fname, 'r') as f: code = f.read() if _re_baseurl.search(code) is None: code = code + f"\nbaseurl: {Config().doc_baseurl}" else: code = _re_baseurl.sub(f"baseurl: {Config().doc_baseurl}", code) with open(fname, 'w') as f: f.write(code) # Cell def notebook2script(fname=None, silent=False, to_dict=False): "Convert notebooks matching `fname` to modules" # initial checks if os.environ.get('IN_TEST',0): return # don't export if running tests if fname is None: reset_nbdev_module() update_version() update_baseurl() files = [f for f in Config().nbs_path.glob('*.ipynb') if not f.name.startswith('_')] else: files = glob.glob(fname) d = collections.defaultdict(list) if to_dict else None for f in sorted(files): d = _notebook2script(f, silent=silent, to_dict=d) if to_dict: return d else: add_init(Config().lib_path) # Cell #export #for tests only class DocsTestClass: def test(): pass
[]
[]
[ "IN_TEST" ]
[]
["IN_TEST"]
python
1
0
4/figs/figX3/scripts_plots_data/calculate_well_dft_single_frame.py
import os import sys import gaptrain as gt import autode as ade import numpy as np ade.Config.n_cores = 4 def get_truncated_portion(frame, max_dist): """ Given a frame discard all but the central water molecule and the water molecules that are within max_dist of it :param frame: :param max_dist: :return: """ box_length = np.average(frame.box.size) coords = frame.coordinates() # Distances from the middle of the box to all the oxygen atoms mid_box_dists = np.linalg.norm(coords - box_length / 2.0, axis=1) central_oxygen = next(idx for idx in np.argsort(mid_box_dists) if frame.atoms[idx].label == 'O') central_o_dists = np.linalg.norm(coords - coords[central_oxygen], axis=1) close_o_idxs = [i for i in np.argsort(central_o_dists) if frame.atoms[i].label == 'O' and central_o_dists[i] < max_dist] atoms = [] for o_idx in close_o_idxs: # Skip any waters that are on the edge of the box if np.max(np.linalg.norm(coords[[o_idx + 1, o_idx + 2]] - coords[o_idx], axis=1)) > 1.5: continue # Add the O, and the two hydrogens, which are the next two atoms for i in range(3): atoms.append(frame.atoms[o_idx + i]) return ade.Molecule(name='tmp', atoms=atoms) def save_potential(traj_filename, stride=1, max_dist=5, frame_n=0): """ :param traj_filename: :param stride: :param max_dist: :return: """ frames = gt.Data(traj_filename) for i, frame in enumerate(frames[::stride]): if i != frame_n: continue mol = get_truncated_portion(frame, max_dist=max_dist) potentials = [] for r in rs: shift_mol = mol.copy() shift_mol.name = f'{i}_{r:.3f}' # Move the central oxygen atom for idx in range(3): shift_mol.atoms[idx].translate(vec=np.array([r, 0.0, 0.0])) shift_mol.single_point(method=method) potentials.append(shift_mol.energy) # Clean up all the generated files for filename in os.listdir(os.getcwd()): if filename.startswith(shift_mol.name): os.remove(filename) # Save the potential array to a .txt potentials = np.array(potentials) - min(potentials) np.savetxt(f'{traj_filename}_{frame_n}_pbe0_potential.txt', potentials) return if __name__ == '__main__': method = ade.methods.ORCA() method.keywords.sp.basis_set = 'def2-SVP' n_points = 7 rs = np.linspace(-1.5, 1.5, num=n_points) save_potential(traj_filename='GAP_rPBE0-D3_nvt_300K.xyz', stride=8, frame_n=int(sys.argv[1]))
[]
[]
[]
[]
[]
python
null
null
null
middleware/auth_middleware.go
package middleware import ( "context" "net/http" "os" "strings" "github.com/dgrijalva/jwt-go" "github.com/dgrijalva/jwt-go/request" "github.com/pkg/errors" "github.com/scorpionknifes/gqlmanage/models" "github.com/scorpionknifes/gqlmanage/mongodb" ) type key string // CurrentUserKey for middleware const CurrentUserKey key = "currentUser" // AuthMiddleware to authenticate graphql users func AuthMiddleware(repo mongodb.UserRepo) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token, err := parseToken(r) if err != nil { next.ServeHTTP(w, r) return } claims, ok := token.Claims.(jwt.MapClaims) if !ok || !token.Valid { next.ServeHTTP(w, r) return } user, err := repo.GetUser(claims["jti"].(string)) if err != nil { next.ServeHTTP(w, r) return } ctx := context.WithValue(r.Context(), CurrentUserKey, user) next.ServeHTTP(w, r.WithContext(ctx)) }) } } var authHeaderExtractor = &request.PostExtractionFilter{ Extractor: request.HeaderExtractor{"Authorization"}, Filter: stripBearerPrefixFromToken, } var graphqlHeaderExtractor = &request.PostExtractionFilter{ Extractor: request.HeaderExtractor{"Sec-Websocket-Protocol"}, Filter: stripWebSocketHeader, } func stripBearerPrefixFromToken(token string) (string, error) { bearer := "BEARER" if len(token) > len(bearer) && strings.ToUpper(token[0:len(bearer)]) == bearer { return token[len(bearer)+1:], nil } return token, nil } func stripWebSocketHeader(token string) (string, error) { head := "GRAPHQL-WS," if len(token) > len(head) && strings.ToUpper(token[0:len(head)]) == head { return token[len(head)+1:], nil } return token, nil } var authExtractor = &request.MultiExtractor{ authHeaderExtractor, graphqlHeaderExtractor, request.ArgumentExtractor{"access_token"}, } func parseToken(r *http.Request) (*jwt.Token, error) { jwtToken, err := request.ParseFromRequest(r, authExtractor, func(token *jwt.Token) (interface{}, error) { t := []byte(os.Getenv("JWT_SECRET")) return t, nil }) return jwtToken, errors.Wrap(err, "parseToken error: ") } // GetCurrentUserFromCTX from context func GetCurrentUserFromCTX(ctx context.Context) (*models.User, error) { errNoUserInContext := errors.New("no user in context") if ctx.Value(CurrentUserKey) == nil { return nil, errNoUserInContext } user, ok := ctx.Value(CurrentUserKey).(*models.User) if !ok || user.ID == "" { return nil, errNoUserInContext } return user, nil }
[ "\"JWT_SECRET\"" ]
[]
[ "JWT_SECRET" ]
[]
["JWT_SECRET"]
go
1
0
tests/ignite/handlers/test_checkpoint.py
import os import warnings from collections import OrderedDict from unittest.mock import MagicMock import pytest import torch import torch.nn as nn import ignite.distributed as idist from ignite.engine import Engine, Events, State from ignite.handlers import Checkpoint, DiskSaver, EarlyStopping, ModelCheckpoint, global_step_from_engine from ignite.handlers.checkpoint import BaseSaveHandler _PREFIX = "PREFIX" class DummyModel(nn.Module): def __init__(self): super(DummyModel, self).__init__() self.net = nn.Linear(1, 1) def forward(self, x): return self.net(x) class DummyPretrainedModel(nn.Module): def __init__(self): super(DummyPretrainedModel, self).__init__() self.features = nn.Linear(4, 2, bias=False) self.fc = nn.Linear(2, 1) def forward(self, x): x = self.features(x) x = self.fc(x) return x def test_checkpoint_wrong_input(): with pytest.raises(TypeError, match=r"Argument `to_save` should be a dictionary"): Checkpoint(12, lambda x: x, "prefix") with pytest.raises(TypeError, match=r"Argument `to_save` should be a dictionary"): Checkpoint([12], lambda x: x, "prefix") with pytest.raises(ValueError, match=r"No objects to checkpoint."): Checkpoint({}, lambda x: x, "prefix") model = DummyModel() to_save = {"model": model} with pytest.raises(TypeError, match=r"Argument `save_handler` should be callable"): Checkpoint(to_save, 12, "prefix") with pytest.raises( ValueError, match=r"If `score_name` is provided, then `score_function` should be also provided." ): Checkpoint(to_save, lambda x: x, score_name="acc") with pytest.raises(TypeError, match=r"global_step_transform should be a function."): Checkpoint(to_save, lambda x: x, score_function=lambda e: 123, score_name="acc", global_step_transform=123) with pytest.warns(UserWarning, match=r"Argument archived is deprecated"): Checkpoint(to_save, lambda x: x, score_function=lambda e: 123, score_name="acc", archived=True) with pytest.raises(ValueError, match=r"Cannot have key 'checkpointer' if `include_self` is True"): Checkpoint({"checkpointer": model}, lambda x: x, include_self=True) def test_checkpoint_score_function_wrong_output(): model = DummyModel() to_save = {"model": model} checkpointer = Checkpoint(to_save, lambda x: x, score_function=lambda e: {"1": 1}, score_name="acc") trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) with pytest.raises(ValueError, match=r"Output of score_function should be a number"): checkpointer(trainer) def test_checkpoint_default(): def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler) assert checkpointer.last_checkpoint is None trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) checkpointer(trainer) assert save_handler.call_count == 1 metadata = {"basename": name, "score_name": None, "priority": 0} save_handler.assert_called_with(obj, "{}_0.pt".format(name), metadata) trainer.state.epoch = 12 trainer.state.iteration = 1234 checkpointer(trainer) assert save_handler.call_count == 2 metadata["priority"] = 1234 save_handler.assert_called_with(obj, "{}_1234.pt".format(name), metadata) assert save_handler.remove.call_count == 1 save_handler.remove.assert_called_with("{}_0.pt".format(name)) assert checkpointer.last_checkpoint == "{}_1234.pt".format(name) model = DummyModel() to_save = {"model": model} _test(to_save, model.state_dict(), "model") model = DummyModel() optimizer = torch.optim.SGD(model.parameters(), lr=0.1) to_save = {"model": model, "optimizer": optimizer} _test(to_save, {"model": model.state_dict(), "optimizer": optimizer.state_dict()}, "checkpoint") def test_checkpoint_include_self_state_dict(): def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler, include_self=True) assert checkpointer.last_checkpoint is None trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) checkpointer(trainer) assert save_handler.call_count == 1 fname = "{}_0.pt".format(name) obj["checkpointer"] = OrderedDict([("saved", [(0, fname)])]) metadata = {"basename": name, "score_name": None, "priority": 0} save_handler.assert_called_with(obj, fname, metadata) # Swap object, state should be maintained checkpointer2 = Checkpoint(to_save, save_handler=save_handler, include_self=True) checkpointer2.load_state_dict(checkpointer.state_dict()) assert checkpointer2.last_checkpoint == fname trainer.state.epoch = 12 trainer.state.iteration = 1234 checkpointer2(trainer) assert save_handler.call_count == 2 metadata["priority"] = 1234 # This delete only happens if state was restored correctly. save_handler.remove.assert_called_with("{}_0.pt".format(name)) fname = "{}_1234.pt".format(name) obj["checkpointer"] = OrderedDict([("saved", [(1234, fname)])]) save_handler.assert_called_with(obj, fname, metadata) assert save_handler.remove.call_count == 1 assert checkpointer2.last_checkpoint == fname model = DummyModel() to_save = {"model": model} _test(to_save, model.state_dict(), "model") model = DummyModel() optimizer = torch.optim.SGD(model.parameters(), lr=0.1) to_save = {"model": model, "optimizer": optimizer} _test(to_save, {"model": model.state_dict(), "optimizer": optimizer.state_dict()}, "checkpoint") def test_checkpoint_with_dp(): model = DummyModel() dp_model = nn.DataParallel(model) to_save = {"model": dp_model} save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) checkpointer(trainer) assert save_handler.call_count == 1 metadata = {"basename": "model", "score_name": None, "priority": 0} save_handler.assert_called_with(model.state_dict(), "model_0.pt", metadata) def test_checkpoint_with_global_step_transform(): def _test(filename_prefix, to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint( to_save, save_handler=save_handler, filename_prefix=filename_prefix, global_step_transform=lambda e, _: e.state.epoch, ) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=2, iteration=1) checkpointer(trainer) assert save_handler.call_count == 1 if len(filename_prefix) > 0: filename_prefix += "_" metadata = {"basename": "{}{}".format(filename_prefix, name), "score_name": None, "priority": 2} save_handler.assert_called_with(obj, "{}{}_2.pt".format(filename_prefix, name), metadata) trainer.state.epoch = 12 trainer.state.iteration = 1234 checkpointer(trainer) assert save_handler.call_count == 2 metadata["priority"] = 12 save_handler.assert_called_with(obj, "{}{}_12.pt".format(filename_prefix, name), metadata) assert save_handler.remove.call_count == 1 save_handler.remove.assert_called_with("{}{}_2.pt".format(filename_prefix, name)) assert checkpointer.last_checkpoint == "{}{}_12.pt".format(filename_prefix, name) for prefix in ["", "dummytask"]: model = DummyModel() to_save = {"model": model} _test(prefix, to_save, model.state_dict(), "model") model = DummyModel() optimizer = torch.optim.SGD(model.parameters(), lr=0.1) to_save = {"model": model, "optimizer": optimizer} _test(prefix, to_save, {"model": model.state_dict(), "optimizer": optimizer.state_dict()}, "checkpoint") def test_checkpoint_with_score_function(): def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler, score_function=lambda e: e.state.score) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=1, iteration=1, score=0.77) checkpointer(trainer) assert save_handler.call_count == 1 metadata = {"basename": name, "score_name": None, "priority": 0.77} save_handler.assert_called_with(obj, "{}_0.7700.pt".format(name), metadata) trainer.state.epoch = 12 trainer.state.iteration = 1234 trainer.state.score = 0.78 checkpointer(trainer) assert save_handler.call_count == 2 metadata["priority"] = 0.78 save_handler.assert_called_with(obj, "{}_0.7800.pt".format(name), metadata) assert save_handler.remove.call_count == 1 save_handler.remove.assert_called_with("{}_0.7700.pt".format(name)) assert checkpointer.last_checkpoint == "{}_0.7800.pt".format(name) model = DummyModel() to_save = {"model": model} _test(to_save, model.state_dict(), "model") model = DummyModel() optimizer = torch.optim.SGD(model.parameters(), lr=0.1) to_save = {"model": model, "optimizer": optimizer} _test(to_save, {"model": model.state_dict(), "optimizer": optimizer.state_dict()}, "checkpoint") def test_checkpoint_with_score_name_and_function(): def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint( to_save, save_handler=save_handler, score_name="loss", score_function=lambda e: e.state.score ) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=1, iteration=1, score=-0.77) checkpointer(trainer) assert save_handler.call_count == 1 metadata = {"basename": name, "score_name": "loss", "priority": -0.77} save_handler.assert_called_with(obj, "{}_loss=-0.7700.pt".format(name), metadata) trainer.state.epoch = 12 trainer.state.iteration = 1234 trainer.state.score = -0.76 checkpointer(trainer) assert save_handler.call_count == 2 metadata["priority"] = -0.76 save_handler.assert_called_with(obj, "{}_loss=-0.7600.pt".format(name), metadata) assert save_handler.remove.call_count == 1 save_handler.remove.assert_called_with("{}_loss=-0.7700.pt".format(name)) assert checkpointer.last_checkpoint == "{}_loss=-0.7600.pt".format(name) model = DummyModel() to_save = {"model": model} _test(to_save, model.state_dict(), "model") model = DummyModel() optimizer = torch.optim.SGD(model.parameters(), lr=0.1) to_save = {"model": model, "optimizer": optimizer} _test(to_save, {"model": model.state_dict(), "optimizer": optimizer.state_dict()}, "checkpoint") def test_checkpoint_with_int_score(): def _test(to_save, obj, name, score_name=None): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint( to_save, save_handler=save_handler, score_name=score_name, score_function=lambda e: e.state.epoch ) if score_name is None: score_name = "" else: score_name += "=" trainer = Engine(lambda e, b: None) trainer.state = State(epoch=1, iteration=1) checkpointer(trainer) assert save_handler.call_count == 1 metadata = {"basename": name, "score_name": score_name[:-1] if len(score_name) > 0 else None, "priority": 1} save_handler.assert_called_with(obj, "{}_{}1.pt".format(name, score_name), metadata) trainer.state.epoch = 12 trainer.state.iteration = 1234 checkpointer(trainer) assert save_handler.call_count == 2 metadata["priority"] = 12 save_handler.assert_called_with(obj, "{}_{}12.pt".format(name, score_name), metadata) assert save_handler.remove.call_count == 1 save_handler.remove.assert_called_with("{}_{}1.pt".format(name, score_name)) assert checkpointer.last_checkpoint == "{}_{}12.pt".format(name, score_name) model = DummyModel() to_save = {"model": model} _test(to_save, model.state_dict(), "model") _test(to_save, model.state_dict(), "model", "epoch") model = DummyModel() optimizer = torch.optim.SGD(model.parameters(), lr=0.1) to_save = {"model": model, "optimizer": optimizer} _test(to_save, {"model": model.state_dict(), "optimizer": optimizer.state_dict()}, "checkpoint") _test(to_save, {"model": model.state_dict(), "optimizer": optimizer.state_dict()}, "checkpoint", "epoch") def test_checkpoint_with_score_function_and_trainer_epoch(): def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) trainer = Engine(lambda e, b: None) evaluator = Engine(lambda e, b: None) trainer.state = State(epoch=11, iteration=1) checkpointer = Checkpoint( to_save, save_handler=save_handler, global_step_transform=lambda _1, _2: trainer.state.epoch, score_function=lambda e: e.state.metrics["val_acc"], ) evaluator.state = State(epoch=1, iteration=1000, metrics={"val_acc": 0.77}) checkpointer(evaluator) assert save_handler.call_count == 1 metadata = {"basename": name, "score_name": None, "priority": 0.77} save_handler.assert_called_with(obj, "{}_11_0.7700.pt".format(name), metadata) trainer.state.epoch = 12 evaluator.state.metrics["val_acc"] = 0.78 checkpointer(evaluator) assert save_handler.call_count == 2 metadata["priority"] = 0.78 save_handler.assert_called_with(obj, "{}_12_0.7800.pt".format(name), metadata) assert save_handler.remove.call_count == 1 save_handler.remove.assert_called_with("{}_11_0.7700.pt".format(name)) assert checkpointer.last_checkpoint == "{}_12_0.7800.pt".format(name) model = DummyModel() to_save = {"model": model} _test(to_save, model.state_dict(), "model") def test_checkpoint_with_score_name_and_function_and_trainer_epoch(): def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) trainer = Engine(lambda e, b: None) evaluator = Engine(lambda e, b: None) trainer.state = State(epoch=11, iteration=1) checkpointer = Checkpoint( to_save, save_handler=save_handler, global_step_transform=lambda _1, _2: trainer.state.epoch, score_name="val_acc", score_function=lambda e: e.state.metrics["val_acc"], ) evaluator.state = State(epoch=1, iteration=1000, metrics={"val_acc": 0.77}) checkpointer(evaluator) assert save_handler.call_count == 1 metadata = {"basename": name, "score_name": "val_acc", "priority": 0.77} save_handler.assert_called_with(obj, "{}_11_val_acc=0.7700.pt".format(name), metadata) trainer.state.epoch = 12 evaluator.state.metrics["val_acc"] = 0.78 checkpointer(evaluator) assert save_handler.call_count == 2 metadata["priority"] = 0.78 save_handler.assert_called_with(obj, "{}_12_val_acc=0.7800.pt".format(name), metadata) assert save_handler.remove.call_count == 1 save_handler.remove.assert_called_with("{}_11_val_acc=0.7700.pt".format(name)) assert checkpointer.last_checkpoint == "{}_12_val_acc=0.7800.pt".format(name) model = DummyModel() to_save = {"model": model} _test(to_save, model.state_dict(), "model") def test_checkpoint_last_checkpoint(): save_handler = MagicMock(spec=BaseSaveHandler) to_save = {"model": DummyModel()} checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=None) trainer = Engine(lambda e, b: None) for i in range(10): trainer.state = State(epoch=1, iteration=i) checkpointer(trainer) assert save_handler.call_count == 10 assert checkpointer.last_checkpoint == "{}_9.pt".format("model") def test_checkpoint_last_checkpoint_on_score(): save_handler = MagicMock(spec=BaseSaveHandler) to_save = {"model": DummyModel()} checkpointer = Checkpoint( to_save, save_handler=save_handler, n_saved=None, score_name="val_acc", score_function=lambda e: e.state.metrics["val_acc"], ) trainer = Engine(lambda e, b: None) val_acc = 0.0 for i in range(10): val_acc = i * 0.1 trainer.state = State(epoch=1, iteration=i, metrics={"val_acc": val_acc}) checkpointer(trainer) assert save_handler.call_count == 10 assert checkpointer.last_checkpoint == "{}_val_acc=0.9000.pt".format("model") def test_checkpoint_save_handler_callable(): def save_handler(c, f): assert f == "model_12.pt" to_save = {"model": DummyModel()} checkpointer = Checkpoint(to_save, save_handler=save_handler,) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=1, iteration=12) checkpointer(trainer) def test_model_checkpoint_args_validation(dirname): existing = os.path.join(dirname, "existing_dir") nonempty = os.path.join(dirname, "nonempty") os.makedirs(existing) os.makedirs(nonempty) with open(os.path.join(nonempty, "{}_name_0.pt".format(_PREFIX)), "w"): pass with pytest.raises(ValueError, match=r"with extension '.pt' are already present "): ModelCheckpoint(nonempty, _PREFIX) with pytest.raises(ValueError, match=r"Argument save_interval is deprecated and should be None"): ModelCheckpoint(existing, _PREFIX, save_interval=42) with pytest.raises(ValueError, match=r"Directory path '\S+' is not found"): ModelCheckpoint(os.path.join(dirname, "non_existing_dir"), _PREFIX, create_dir=False) with pytest.raises(ValueError, match=r"Argument save_as_state_dict is deprecated and should be True"): ModelCheckpoint(existing, _PREFIX, create_dir=False, save_as_state_dict=False) with pytest.raises(ValueError, match=r"If `score_name` is provided, then `score_function` "): ModelCheckpoint(existing, _PREFIX, create_dir=False, score_name="test") with pytest.raises(TypeError, match=r"global_step_transform should be a function"): ModelCheckpoint(existing, _PREFIX, create_dir=False, global_step_transform=1234) with pytest.warns(UserWarning, match=r"Argument archived is deprecated"): ModelCheckpoint(existing, _PREFIX, create_dir=False, archived=True) h = ModelCheckpoint(dirname, _PREFIX, create_dir=False) assert h.last_checkpoint is None with pytest.raises(RuntimeError, match=r"No objects to checkpoint found."): h(None, []) def test_model_checkpoint_simple_recovery(dirname): h = ModelCheckpoint(dirname, _PREFIX, create_dir=False) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=1) model = DummyModel() to_save = {"model": model} h(engine, to_save) fname = h.last_checkpoint assert isinstance(fname, str) assert os.path.join(dirname, _PREFIX) in fname assert os.path.exists(fname) loaded_objects = torch.load(fname) assert loaded_objects == model.state_dict() def test_model_checkpoint_simple_recovery_from_existing_non_empty(dirname): def _test(ext, require_empty): previous_fname = os.path.join(dirname, "{}_{}_{}{}".format(_PREFIX, "obj", 1, ext)) with open(previous_fname, "w") as f: f.write("test") h = ModelCheckpoint(dirname, _PREFIX, create_dir=True, require_empty=require_empty) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=1) model = DummyModel() to_save = {"model": model} h(engine, to_save) fname = h.last_checkpoint ext = ".pt" assert isinstance(fname, str) assert os.path.join(dirname, "{}_{}_{}{}".format(_PREFIX, "model", 1, ext)) == fname assert os.path.exists(fname) assert os.path.exists(previous_fname) loaded_objects = torch.load(fname) assert loaded_objects == model.state_dict() os.remove(fname) _test(".txt", require_empty=True) _test(".pt", require_empty=False) def test_disk_saver_atomic(dirname): model = DummyModel() to_save_serializable = {"model": model} to_save_non_serializable = {"model": lambda x: x} def _test_existance(atomic, _to_save, expected): saver = DiskSaver(dirname, atomic=atomic, create_dir=False, require_empty=False) fname = "test.pt" try: with warnings.catch_warnings(): # Ignore torch/serialization.py:292: UserWarning: Couldn't retrieve source code for container of type # DummyModel. It won't be checked for correctness upon loading. warnings.simplefilter("ignore", category=UserWarning) saver(_to_save, fname) except Exception: pass fp = os.path.join(saver.dirname, fname) assert os.path.exists(fp) == expected if expected: saver.remove(fname) _test_existance(atomic=False, _to_save=to_save_serializable, expected=True) _test_existance(atomic=False, _to_save=to_save_non_serializable, expected=True) _test_existance(atomic=True, _to_save=to_save_serializable, expected=True) _test_existance(atomic=True, _to_save=to_save_non_serializable, expected=False) def test_last_k(dirname): h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) model = DummyModel() to_save = {"model": model} h(engine, to_save) for i in range(1, 9): engine.state.iteration = i h(engine, to_save) expected = ["{}_{}_{}.pt".format(_PREFIX, "model", i) for i in [7, 8]] assert sorted(os.listdir(dirname)) == expected, "{} vs {}".format(sorted(os.listdir(dirname)), expected) def test_disabled_n_saved(dirname): h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=None) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) model = DummyModel() to_save = {"model": model} num_iters = 100 for i in range(num_iters): engine.state.iteration = i h(engine, to_save) saved_files = sorted(os.listdir(dirname)) assert len(saved_files) == num_iters, "{}".format(saved_files) expected = sorted(["{}_{}_{}.pt".format(_PREFIX, "model", i) for i in range(num_iters)]) assert saved_files == expected, "{} vs {}".format(saved_files, expected) def test_best_k(dirname): scores = iter([1.2, -2.0, 3.1, -4.0]) def score_function(_): return next(scores) h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2, score_function=score_function) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) model = DummyModel() to_save = {"model": model} for _ in range(4): h(engine, to_save) expected = ["{}_{}_{:.4f}.pt".format(_PREFIX, "model", i) for i in [1.2, 3.1]] assert sorted(os.listdir(dirname)) == expected def test_best_k_with_suffix(dirname): scores = [0.3456789, 0.1234, 0.4567, 0.134567] scores_iter = iter(scores) def score_function(engine): return next(scores_iter) h = ModelCheckpoint( dirname, _PREFIX, create_dir=False, n_saved=2, score_function=score_function, score_name="val_loss" ) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) model = DummyModel() to_save = {"model": model} for _ in range(4): engine.state.epoch += 1 h(engine, to_save) expected = ["{}_{}_val_loss={:.4}.pt".format(_PREFIX, "model", scores[e - 1]) for e in [1, 3]] assert sorted(os.listdir(dirname)) == expected def test_removes_each_score_at_most_once(dirname): scores = [0, 1, 1, 2, 3] scores_iter = iter(scores) def score_function(_): return next(scores_iter) h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2, score_function=score_function) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) model = DummyModel() to_save = {"model": model} for _ in range(len(scores)): h(engine, to_save) # If a score was removed multiple times, the code above would have raise a # FileNotFoundError. So this just tests the absence of such a failure # without futher assertions. def test_with_engine(dirname): def update_fn(_1, _2): pass name = "model" engine = Engine(update_fn) handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2) model = DummyModel() to_save = {"model": model} engine.add_event_handler(Events.EPOCH_COMPLETED, handler, to_save) engine.run([0], max_epochs=4) expected = ["{}_{}_{}.pt".format(_PREFIX, name, i) for i in [3, 4]] assert sorted(os.listdir(dirname)) == expected def test_with_state_dict(dirname): def update_fn(_1, _2): pass engine = Engine(update_fn) handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1) model = DummyModel() to_save = {"model": model} engine.add_event_handler(Events.EPOCH_COMPLETED, handler, to_save) engine.run([0], max_epochs=4) saved_model = os.path.join(dirname, os.listdir(dirname)[0]) load_model = torch.load(saved_model) assert not isinstance(load_model, DummyModel) assert isinstance(load_model, dict) model_state_dict = model.state_dict() loaded_model_state_dict = load_model for key in model_state_dict.keys(): assert key in loaded_model_state_dict model_value = model_state_dict[key] loaded_model_value = loaded_model_state_dict[key] assert model_value.numpy() == loaded_model_value.numpy() def test_valid_state_dict_save(dirname): model = DummyModel() h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) to_save = {"name": 42} with pytest.raises(TypeError, match=r"should have `state_dict` method"): h(engine, to_save) to_save = {"name": model} try: h(engine, to_save) except ValueError: pytest.fail("Unexpected ValueError") def _test_save_model_optimizer_lr_scheduler_with_state_dict(device, dirname, on_zero_rank=False): torch.manual_seed(23) model = DummyModel().to(device) optim = torch.optim.SGD(model.parameters(), lr=0.1) lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optim, gamma=0.5) def update_fn(engine, batch): x = torch.rand((4, 1)).to(device) optim.zero_grad() y = model(x) loss = y.pow(2.0).sum() loss.backward() if idist.has_xla_support: import torch_xla.core.xla_model as xm xm.optimizer_step(optim, barrier=True) else: optim.step() lr_scheduler.step() engine = Engine(update_fn) if (not on_zero_rank) or (on_zero_rank and idist.get_rank() == 0): handler = ModelCheckpoint(dirname, _PREFIX, create_dir=True, n_saved=1) engine.add_event_handler( Events.EPOCH_COMPLETED, handler, {"model": model, "optimizer": optim, "lr_scheduler": lr_scheduler} ) engine.run([0], max_epochs=4) idist.barrier() saved_objects = sorted(os.listdir(dirname)) # saved object is ['PREFIX_checkpoint_3.pt', ] saved_checkpoint = os.path.join(dirname, saved_objects[0]) if idist.has_xla_support: device = "cpu" loaded_obj = torch.load(saved_checkpoint, map_location=device) for f in ["model", "optimizer", "lr_scheduler"]: assert f in loaded_obj loaded_model_state_dict = loaded_obj["model"] loaded_optimizer_state_dict = loaded_obj["optimizer"] loaded_lr_scheduler_state_dict = loaded_obj["lr_scheduler"] assert isinstance(loaded_model_state_dict, dict) assert isinstance(loaded_optimizer_state_dict, dict) assert isinstance(loaded_lr_scheduler_state_dict, dict) # Specifically move device to CPU first model_state_dict = model.cpu().state_dict() for key in model_state_dict.keys(): assert key in loaded_model_state_dict model_value = model_state_dict[key] loaded_model_value = loaded_model_state_dict[key] assert model_value.cpu().numpy() == loaded_model_value.cpu().numpy() optim_state_dict = optim.state_dict() for key in optim_state_dict.keys(): assert key in loaded_optimizer_state_dict optim_value = optim_state_dict[key] loaded_optim_value = loaded_optimizer_state_dict[key] if idist.get_rank() == 0: assert optim_value == loaded_optim_value lr_scheduler_state_dict = lr_scheduler.state_dict() for key in lr_scheduler_state_dict.keys(): assert key in loaded_lr_scheduler_state_dict lr_scheduler_value = lr_scheduler_state_dict[key] loaded_lr_scheduler_value = loaded_lr_scheduler_state_dict[key] assert lr_scheduler_value == loaded_lr_scheduler_value def test_save_model_optimizer_lr_scheduler_with_state_dict(dirname): _test_save_model_optimizer_lr_scheduler_with_state_dict("cpu", dirname) def _test_save_model_optimizer_lr_scheduler_with_validation(device, dirname, on_zero_rank=False): torch.manual_seed(23) def _build_objects(acc_list): model = DummyModel().to(device) optim = torch.optim.SGD(model.parameters(), lr=0.1) lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optim, gamma=0.5) def update_fn(engine, batch): x = torch.rand((4, 1)).to(device) optim.zero_grad() y = model(x) loss = y.pow(2.0).sum() loss.backward() if idist.has_xla_support: import torch_xla.core.xla_model as xm xm.optimizer_step(optim, barrier=True) else: optim.step() lr_scheduler.step() trainer = Engine(update_fn) evaluator = Engine(lambda e, b: None) acc_iter = iter(acc_list) @evaluator.on(Events.EPOCH_COMPLETED) def setup_result(): evaluator.state.metrics["accuracy"] = next(acc_iter) @trainer.on(Events.EPOCH_COMPLETED) def run_eval(): evaluator.run([0, 1, 2]) def score_function(engine): return engine.state.metrics["accuracy"] save_handler = DiskSaver(dirname, create_dir=True, require_empty=False) early_stop = EarlyStopping(score_function=score_function, patience=2, trainer=trainer) evaluator.add_event_handler(Events.COMPLETED, early_stop) checkpointer = Checkpoint( { "trainer": trainer, "model": model, "optim": optim, "lr_scheduler": lr_scheduler, "early_stop": early_stop, }, save_handler, include_self=True, global_step_transform=global_step_from_engine(trainer), ) evaluator.add_event_handler(Events.COMPLETED, checkpointer) return trainer, evaluator, model, optim, lr_scheduler, early_stop, checkpointer trainer, evaluator, model, optim, scheduler, early, checkpointer = _build_objects([0.2, 0.3, 0.2]) trainer.run([0], max_epochs=3) saved_objects = sorted(os.listdir(dirname)) saved_checkpoint = os.path.join(dirname, saved_objects[0]) loaded_obj = torch.load(saved_checkpoint, map_location=device) for f in ["trainer", "model", "optim", "lr_scheduler", "early_stop", "checkpointer"]: assert f in loaded_obj trainer2, evaluator2, model2, optim2, scheduler2, early2, checkpointer2 = _build_objects([0.1, 0.1, 0.1]) Checkpoint.load_objects( { "trainer": trainer2, "model": model2, "optim": optim2, "lr_scheduler": scheduler2, "early_stop": early2, "checkpointer": checkpointer2, }, loaded_obj, ) assert checkpointer2.last_checkpoint == checkpointer.last_checkpoint model_state_dict = model.cpu().state_dict() loaded_model_state_dict = model2.cpu().state_dict() for key in model_state_dict.keys(): assert key in loaded_model_state_dict model_value = model_state_dict[key] loaded_model_value = loaded_model_state_dict[key] assert model_value.cpu().numpy() == loaded_model_value.cpu().numpy() optim_state_dict = optim.state_dict() loaded_optimizer_state_dict = optim2.state_dict() # "params" contains tensor IDs, which are different del optim_state_dict["param_groups"][0]["params"] del loaded_optimizer_state_dict["param_groups"][0]["params"] for key in optim_state_dict.keys(): assert key in loaded_optimizer_state_dict optim_value = optim_state_dict[key] loaded_optim_value = loaded_optimizer_state_dict[key] if idist.get_rank() == 0: assert optim_value == loaded_optim_value def _check_state_dict(original, loaded): original_state_dict = original.state_dict() loaded_state_dict = loaded.state_dict() for key in original_state_dict.keys(): assert key in loaded_state_dict original_value = original_state_dict[key] loaded_value = loaded_state_dict[key] assert original_value == loaded_value _check_state_dict(trainer, trainer2) _check_state_dict(scheduler, scheduler2) _check_state_dict(early, early2) _check_state_dict(checkpointer, checkpointer2) trainer2.run([0], max_epochs=6) # early stopping should have triggered assert trainer2.state.epoch == 4 # If Checkpoint's state was restored correctly, it should continue to respect n_saved # and delete old checkpoints, and have the correct last_checkpoint. assert os.listdir(dirname) == ["checkpoint_4.pt"] assert checkpointer2.last_checkpoint == "checkpoint_4.pt" def test_save_model_optimizer_lr_scheduler_with_validation(dirname): _test_save_model_optimizer_lr_scheduler_with_validation("cpu", dirname) def test_checkpoint_load_objects(): with pytest.raises(TypeError, match=r"Argument checkpoint should be a dictionary"): Checkpoint.load_objects({}, []) with pytest.raises(TypeError, match=r"should have `load_state_dict` method"): Checkpoint.load_objects({"a": None}, {"a": None}) model = DummyModel() to_load = {"model": model, "another_model": model} with pytest.raises(ValueError, match=r"from `to_load` is not found in the checkpoint"): Checkpoint.load_objects(to_load, {}) model = DummyModel() to_load = {"model": model} model2 = DummyModel() chkpt = {"model": model2.state_dict()} Checkpoint.load_objects(to_load, chkpt) assert model.state_dict() == model2.state_dict() def test_checkpoint_load_objects_from_saved_file(dirname): def _get_single_obj_to_save(): model = DummyModel() to_save = {"model": model} return to_save def _get_multiple_objs_to_save(): model = DummyModel() optim = torch.optim.SGD(model.parameters(), lr=0.001) lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optim, gamma=0.5) to_save = {"model": model, "optimizer": optim, "lr_scheduler": lr_scheduler} return to_save trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) # case: multiple objects handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1) to_save = _get_multiple_objs_to_save() handler(trainer, to_save) fname = handler.last_checkpoint assert isinstance(fname, str) assert os.path.join(dirname, _PREFIX) in fname assert os.path.exists(fname) loaded_objects = torch.load(fname) Checkpoint.load_objects(to_save, loaded_objects) os.remove(fname) # case: saved multiple objects, loaded single object handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1) to_save = _get_multiple_objs_to_save() handler(trainer, to_save) fname = handler.last_checkpoint assert isinstance(fname, str) assert os.path.join(dirname, _PREFIX) in fname assert os.path.exists(fname) loaded_objects = torch.load(fname) to_load = {"model": to_save["model"]} Checkpoint.load_objects(to_load, loaded_objects) os.remove(fname) # case: single object handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1) to_save = _get_single_obj_to_save() handler(trainer, to_save) fname = handler.last_checkpoint assert isinstance(fname, str) assert os.path.join(dirname, _PREFIX) in fname assert os.path.exists(fname) loaded_objects = torch.load(fname) Checkpoint.load_objects(to_save, loaded_objects) def test_load_checkpoint_with_different_num_classes(dirname): model = DummyPretrainedModel() to_save_single_object = {"model": model} trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1) handler(trainer, to_save_single_object) fname = handler.last_checkpoint loaded_checkpoint = torch.load(fname) to_load_single_object = {"pretrained_features": model.features} with pytest.raises(RuntimeError): Checkpoint.load_objects(to_load_single_object, loaded_checkpoint) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=UserWarning) Checkpoint.load_objects(to_load_single_object, loaded_checkpoint, strict=False, blah="blah") loaded_weights = to_load_single_object["pretrained_features"].state_dict()["weight"] assert torch.all(model.state_dict()["features.weight"].eq(loaded_weights)) def test_disksaver_wrong_input(dirname): with pytest.raises(ValueError, match=r"Directory path '\S+' is not found"): DiskSaver("/tmp/non-existing-folder", create_dir=False) def _test(ext): previous_fname = os.path.join(dirname, "{}_{}_{}{}".format(_PREFIX, "obj", 1, ext)) with open(previous_fname, "w") as f: f.write("test") with pytest.raises(ValueError, match=r"with extension '.pt' are already present"): DiskSaver(dirname, require_empty=True) _test(".pt") def _test_checkpoint_with_ddp(device): torch.manual_seed(0) model = DummyModel().to(device) device_ids = ( None if "cpu" in device.type else [device,] ) ddp_model = nn.parallel.DistributedDataParallel(model, device_ids=device_ids) to_save = {"model": ddp_model} save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) checkpointer(trainer) assert save_handler.call_count == 1 metadata = {"basename": "model", "score_name": None, "priority": 0} save_handler.assert_called_with(model.state_dict(), "model_0.pt", metadata) def _test_checkpoint_load_objects_ddp(device): model = DummyModel().to(device) device_ids = ( None if "cpu" in device.type else [device,] ) ddp_model = nn.parallel.DistributedDataParallel(model, device_ids=device_ids) opt = torch.optim.SGD(ddp_model.parameters(), lr=0.01) # single object: to_load = {"model": ddp_model} checkpoint = ddp_model.module.state_dict() Checkpoint.load_objects(to_load, checkpoint) # multiple objects: to_load = {"model": ddp_model, "opt": opt} checkpoint = {"model": ddp_model.module.state_dict(), "opt": opt.state_dict()} Checkpoint.load_objects(to_load, checkpoint) @pytest.mark.distributed @pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support") def test_distrib_cpu(distributed_context_single_node_gloo, get_rank_zero_dirname): device = torch.device("cpu") dirname = get_rank_zero_dirname() _test_save_model_optimizer_lr_scheduler_with_state_dict(device, os.path.join(dirname, "1")) _test_save_model_optimizer_lr_scheduler_with_state_dict(device, os.path.join(dirname, "2"), on_zero_rank=True) _test_checkpoint_with_ddp(device) _test_checkpoint_load_objects_ddp(device) @pytest.mark.distributed @pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support") @pytest.mark.skipif(torch.cuda.device_count() < 1, reason="Skip if no GPU") def test_distrib_gpu(distributed_context_single_node_nccl, get_rank_zero_dirname): device = idist.device() dirname = get_rank_zero_dirname() _test_save_model_optimizer_lr_scheduler_with_state_dict(device, os.path.join(dirname, "1")) _test_save_model_optimizer_lr_scheduler_with_state_dict("cpu", os.path.join(dirname, "2"), on_zero_rank=True) _test_checkpoint_with_ddp(device=device) _test_checkpoint_load_objects_ddp(device=device) def _test_tpu_saves_to_cpu(device, dirname): torch.manual_seed(0) h = ModelCheckpoint(dirname, _PREFIX) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=1) model = DummyModel().to(device) to_save = {"model": model} h(engine, to_save) idist.barrier() fname = h.last_checkpoint assert isinstance(fname, str) assert os.path.join(dirname, _PREFIX) in fname assert os.path.exists(fname) loaded_objects = torch.load(fname) assert loaded_objects == model.cpu().state_dict() @pytest.mark.tpu @pytest.mark.skipif("NUM_TPU_WORKERS" in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars") @pytest.mark.skipif(not idist.has_xla_support, reason="Not on TPU device") def test_distrib_single_device_xla(dirname): assert "xla" in idist.device().type _test_tpu_saves_to_cpu(idist.device(), os.path.join(dirname, "1")) _test_save_model_optimizer_lr_scheduler_with_state_dict(idist.device(), os.path.join(dirname, "2")) def _test_tpu_saves_to_cpu_nprocs(index, dirname): device = idist.device() _test_tpu_saves_to_cpu(device, os.path.join(dirname, "1")) _test_save_model_optimizer_lr_scheduler_with_state_dict(device, os.path.join(dirname, "2")) import time # hack to have all proc properly sync: time.sleep(1) @pytest.mark.tpu @pytest.mark.skipif("NUM_TPU_WORKERS" not in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars") @pytest.mark.skipif(not idist.has_xla_support, reason="Not on TPU device") def test_distrib_single_device_xla_nprocs(xmp_executor, dirname): n = int(os.environ["NUM_TPU_WORKERS"]) xmp_executor(_test_tpu_saves_to_cpu_nprocs, args=(dirname,), nprocs=n) def test_checkpoint_filename_pattern(): def _test( to_save, filename_prefix="", score_function=None, score_name=None, global_step_transform=None, filename_pattern=None, ): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint( to_save, save_handler=save_handler, filename_prefix=filename_prefix, score_function=score_function, score_name=score_name, global_step_transform=global_step_transform, filename_pattern=filename_pattern, ) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=12, iteration=203, score=0.9999) checkpointer(trainer) return checkpointer.last_checkpoint model = DummyModel() to_save = {"model": model} assert _test(to_save) == "model_203.pt" assert _test(to_save, "best") == "best_model_203.pt" assert _test(to_save, score_function=lambda e: e.state.score) == "model_0.9999.pt" res = _test(to_save, score_function=lambda e: e.state.score, global_step_transform=lambda e, _: e.state.epoch) assert res == "model_12_0.9999.pt" assert _test(to_save, score_function=lambda e: e.state.score, score_name="acc") == "model_acc=0.9999.pt" res = _test( to_save, score_function=lambda e: e.state.score, score_name="acc", global_step_transform=lambda e, _: e.state.epoch, ) assert res == "model_12_acc=0.9999.pt" assert _test(to_save, "best", score_function=lambda e: e.state.score) == "best_model_0.9999.pt" res = _test( to_save, "best", score_function=lambda e: e.state.score, global_step_transform=lambda e, _: e.state.epoch ) assert res == "best_model_12_0.9999.pt" res = _test(to_save, "best", score_function=lambda e: e.state.score, score_name="acc") assert res == "best_model_acc=0.9999.pt" res = _test( to_save, "best", score_function=lambda e: e.state.score, score_name="acc", global_step_transform=lambda e, _: e.state.epoch, ) assert res == "best_model_12_acc=0.9999.pt" pattern = "chk-{name}--{global_step}.{ext}" assert _test(to_save, to_save, filename_pattern=pattern) == "chk-model--203.pt" pattern = "chk-{filename_prefix}--{name}--{global_step}.{ext}" assert _test(to_save, "best", filename_pattern=pattern) == "chk-best--model--203.pt" pattern = "chk-{name}--{score}.{ext}" assert _test(to_save, score_function=lambda e: e.state.score, filename_pattern=pattern) == "chk-model--0.9999.pt" pattern = "{global_step}-{name}-{score}.chk.{ext}" res = _test( to_save, score_function=lambda e: e.state.score, global_step_transform=lambda e, _: e.state.epoch, filename_pattern=pattern, ) assert res == "12-model-0.9999.chk.pt" pattern = "chk-{name}--{score_name}--{score}.{ext}" res = _test(to_save, score_function=lambda e: e.state.score, score_name="acc", filename_pattern=pattern) assert res == "chk-model--acc--0.9999.pt" pattern = "chk-{name}-{global_step}-{score_name}-{score}.{ext}" res = _test( to_save, score_function=lambda e: e.state.score, score_name="acc", global_step_transform=lambda e, _: e.state.epoch, filename_pattern=pattern, ) assert res == "chk-model-12-acc-0.9999.pt" pattern = "{filename_prefix}-{name}-{score}.chk" res = _test(to_save, "best", score_function=lambda e: e.state.score, filename_pattern=pattern) assert res == "best-model-0.9999.chk" pattern = "resnet-{filename_prefix}-{name}-{global_step}-{score}.chk" res = _test( to_save, "best", score_function=lambda e: e.state.score, global_step_transform=lambda e, _: e.state.epoch, filename_pattern=pattern, ) assert res == "resnet-best-model-12-0.9999.chk" pattern = "{filename_prefix}-{name}-{score_name}-{score}.chk" res = _test(to_save, "best", score_function=lambda e: e.state.score, score_name="acc", filename_pattern=pattern) assert res == "best-model-acc-0.9999.chk" pattern = "{global_step}-{filename_prefix}-{name}-{score_name}-{score}" res = _test( to_save, "best", score_function=lambda e: e.state.score, score_name="acc", global_step_transform=lambda e, _: e.state.epoch, filename_pattern=pattern, ) assert res == "12-best-model-acc-0.9999" pattern = "SAVE:{name}-{score_name}-{score}.pth" res = _test( to_save, "best", score_function=lambda e: e.state.score, score_name="acc", global_step_transform=lambda e, _: e.state.epoch, filename_pattern=pattern, ) assert res == "SAVE:model-acc-0.9999.pth" pattern = "{global_step}-chk-{filename_prefix}-{name}-{score_name}-{score}.{ext}" assert _test(to_save, filename_pattern=pattern) == "203-chk--model-None-None.pt" with pytest.raises(KeyError, match=r"random_key"): pattern = "SAVE:{random_key}.{ext}" _test(to_save, filename_pattern=pattern) def test_setup_filename_pattern(): # default filename pattern assert Checkpoint.setup_filename_pattern() == "{filename_prefix}_{name}_{global_step}_{score_name}={score}.{ext}" assert Checkpoint.setup_filename_pattern(False) == "{name}_{global_step}_{score_name}={score}.{ext}" assert Checkpoint.setup_filename_pattern(False, False, False) == "{name}_{global_step}.{ext}" assert Checkpoint.setup_filename_pattern(False, True, False) == "{name}_{global_step}_{score}.{ext}" assert Checkpoint.setup_filename_pattern(False, True, False, False) == "{name}_{score}.{ext}" assert Checkpoint.setup_filename_pattern(False, True, True, False) == "{name}_{score_name}={score}.{ext}" with pytest.raises(ValueError, match=r"At least one of with_score and with_global_step should be True."): Checkpoint.setup_filename_pattern(False, False, False, False) with pytest.raises(ValueError, match=r"If with_score_name is True, with_score should be also True"): Checkpoint.setup_filename_pattern(True, False, True, True) def _setup_checkpoint(): save_handler = MagicMock(spec=BaseSaveHandler) model = DummyModel() to_save = {"model": model} checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=None) assert checkpointer.last_checkpoint is None trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) checkpointer(trainer) trainer.state.iteration = 10 checkpointer(trainer) trainer.state.iteration = 20 checkpointer(trainer) assert save_handler.call_count == 3 return checkpointer def test_checkpoint_state_dict(): checkpointer = _setup_checkpoint() sd = checkpointer.state_dict() assert "saved" in sd assert isinstance(sd["saved"], list) and len(sd["saved"]) == len(checkpointer._saved) for saved_item, true_item in zip(sd["saved"], checkpointer._saved): assert saved_item[0] == true_item.priority assert saved_item[1] == true_item.filename def test_checkpoint_load_state_dict(): true_checkpointer = _setup_checkpoint() save_handler = MagicMock(spec=BaseSaveHandler) model = DummyModel() to_save = {"model": model} checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=None) sd = {"saved": [(0, "model_0.pt"), (10, "model_10.pt"), (20, "model_20.pt")]} checkpointer.load_state_dict(sd) assert checkpointer._saved == true_checkpointer._saved
[]
[]
[ "NUM_TPU_WORKERS" ]
[]
["NUM_TPU_WORKERS"]
python
1
0
nondefaced_detector/cli/main.py
"""Main command-line interface for nondefaced-detector.""" import click import csv import datetime import errno import logging import os import platform import sys os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import nobrainer import nibabel as nib import numpy as np import tensorflow as tf # Following works only for python>3.8 # from importlib.metadata import version, PackageNotFoundError from pkg_resources import get_distribution, DistributionNotFound from nobrainer.io import read_csv from nobrainer.io import verify_features_labels from nobrainer.tfrecord import write as _write_tfrecord from nondefaced_detector import prediction from nondefaced_detector.helpers import utils from nondefaced_detector.preprocess import preprocess, cleanup_files from nondefaced_detector.preprocess import preprocess_parallel from nondefaced_detector.utils import get_datalad _option_kwds = {"show_default": True} try: __version__ = get_distribution("nondefaced-detector").version except DistributionNotFound: # package is not installed pass @click.group() @click.version_option(__version__, message="%(prog)s version %(version)s") def cli(): """A framework to detect if a 3D MRI Volume has been defaced.""" return @cli.command() @click.option( "-c", "--csv", type=click.Path(exists=True), required=True, **_option_kwds ) @click.option( "-p", "--preprocess-path", type=click.Path(exists=True), default=None, required=False, **_option_kwds, ) @click.option( "-t", "--tfrecords-template", default="tfrecords/data_shard-{shard:03d}.tfrec", required=True, **_option_kwds, ) @click.option( "-s", "--volume-shape", default=(128, 128, 128), nargs=3, type=int, required=True, **_option_kwds, ) @click.option( "-n", "--examples-per-shard", type=int, default=100, help="Number of (feature, label) pairs per TFRecord file.", **_option_kwds, ) @click.option( "-j", "--num-parallel-calls", default=-1, type=int, help="Number of processes to use. If -1, uses all available processes.", **_option_kwds, ) @click.option( "-v", "--verbose", is_flag=True, help="Print progress bar.", **_option_kwds ) def convert( csv, preprocess_path, tfrecords_template, volume_shape, examples_per_shard, num_parallel_calls, verbose, ): """Preprocess MRI volumes and convert to Tfrecords. NOTE: Volumes will all be the same shape after preprocessing. """ volume_filepaths = read_csv(csv) num_parallel_calls = None if num_parallel_calls == -1 else num_parallel_calls if num_parallel_calls is None: # Get number of processes allocated to the current process. # Note the difference from `os.cpu_count()`. num_parallel_calls = len(os.sched_getaffinity(0)) invalid_pairs = verify_features_labels( volume_filepaths, check_labels_int=True, num_parallel_calls=num_parallel_calls, verbose=verbose, ) # UNCOMMENT the following when https://github.com/neuronets/nobrainer/pull/125 # is merged # if not invalid_pairs: # click.echo(click.style("Passed verification.", fg="green")) # else: # click.echo(click.style("Failed verification.", fg="red")) # for pair in invalid_pairs: # click.echo(pair[0]) # click.echo(pair[1]) # sys.exit(-1) ppaths = preprocess_parallel( volume_filepaths, conform_volume_to=volume_shape, num_parallel_calls=num_parallel_calls, save_path=preprocess_path, ) invalid_pairs = verify_features_labels( ppaths, volume_shape=volume_shape, check_labels_int=True, num_parallel_calls=num_parallel_calls, verbose=verbose, ) if not invalid_pairs: click.echo() else: click.echo(click.style("Failed post preprocessing re-verification.", fg="red")) click.echo( f"Oops! This is embarrasing. Looks like our preprocessing" " script shit the bed. Found {len(invalid_pairs)} invalid" " pairs of volumes. These files might not all have shape " " {volume_shape} or the labels might not be scalar values" " Please report this issue on " " https://github.com/poldracklab/nondefaced-detector " ) for pair in invalid_pairs: click.echo(pair[0]) click.echo(pair[1]) sys.exit(-1) # TODO: Convert to tfrecords os.makedirs(os.path.dirname(tfrecords_template), exist_ok=True) _write_tfrecord( features_labels=ppaths, filename_template=tfrecords_template, examples_per_shard=examples_per_shard, processes=num_parallel_calls, verbose=verbose, ) click.echo(click.style("Finished conversion to TFRecords.", fg="green")) @cli.command() @click.argument("infile") @click.option( "-m", "--model-path", type=click.Path(exists=True), help="Path to model weights. \ NOTE: A version of pretrained model weights can be found here: \ https://gin.g-node.org/shashankbansal56/nondefaced-detector-reproducibility/pretrained_weights", **_option_kwds, ) @click.option( "-o", "--outfile", required=False, default="outputs.csv", help="Path to save output csv file, set if infile is a csv", **_option_kwds, ) @click.option( "-t", "--classifier-threshold", default=0.5, type=float, help="Threshold for the classifier [Default is 0.5].", **_option_kwds, ) @click.option( "-r", "--conform-volume-to", default=(128, 128, 128), type=int, nargs=3, help="Conform volume to this size before predicting.", **_option_kwds, ) @click.option( "-p", "--preprocess-path", type=click.Path(exists=True), required=False, default="/tmp", help="Path to save preprocessed volumes.", **_option_kwds, ) @click.option( "-j", "--num-parallel-calls", default=-1, type=int, help="Number of processes to use. If -1, uses all available processes.", **_option_kwds, ) @click.option("--skip-header", is_flag=True, help="Skip csv header.", **_option_kwds) @click.option( "--keep-preprocessed", is_flag=True, help="Keep the preprocessed volumes.", **_option_kwds, ) @click.option( "-v", "--verbose", is_flag=True, help="Print progress bar.", **_option_kwds ) def predict( *, infile, outfile, classifier_threshold, model_path, conform_volume_to, preprocess_path, num_parallel_calls, skip_header, keep_preprocessed, verbose, ): """Predict labels from features using a trained model. The predictions are saved to OUTFILE. """ if verbose: os.environ["TF_CPP_MIN_LOG_LEVEL"] = "0" import tensorflow as tf tf.get_logger().setLevel(logging.INFO) tf.autograph.set_verbosity(1) if not os.path.exists(infile): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), infile) print("model_path:", model_path) if not model_path: print( "Model weights not found. \ Downloading to /tmp/nondefaced-detector-reproducibility" ) cache_dir = get_datalad() model_path = os.path.join(cache_dir, "pretrained_weights") required_dirs = ["axial", "coronal", "sagittal", "combined"] for plane in required_dirs: if not os.path.isdir(os.path.join(model_path, plane)): raise ValueError("Missing {} directory in model path".format(plane)) if infile.endswith(".nii") or infile.endswith(".nii.gz"): cpath = preprocess(infile, save_path=preprocess_path, with_label=False) volume, _, _ = utils.load_vol(cpath) model = prediction._get_model(model_path) predicted = prediction._predict(volume, model) print("Final layer output: ", predicted) print("Input classifier threshold: ", classifier_threshold) if predicted[0] >= classifier_threshold: print("Predicted Class: NONDEFACED") else: print("Predicted Class: DEFACED") if preprocess_path == "/tmp": cleanup_files(cpath) if infile.endswith("csv"): filepaths = [] with open(infile, newline="") as csvfile: reader = csv.reader(csvfile, delimiter=",") if skip_header: next(reader) for row in reader: filepaths.append(row[0]) num_parallel_calls = None if num_parallel_calls == -1 else num_parallel_calls if num_parallel_calls is None: # Get number of processes allocated to the current process. # Note the difference from `os.cpu_count()`. num_parallel_calls = len(os.sched_getaffinity(0)) outputs = preprocess_parallel( filepaths, num_parallel_calls=num_parallel_calls, conform_volume_to=conform_volume_to, with_label=False, ) preds = prediction.predict(outputs, model_path=model_path, n_slices=32) if os.path.exists(outfile): raise FileExistsError( "Output file already exists. Will not overwrite {}".format(outfile) ) if not outfile.endswith("csv"): raise ValueError("Need a csv file for writing output") with open(outfile, "w") as out: csv_out = csv.writer(out) csv_out.writerow(["volume", "score"]) for row in preds: csv_out.writerow(row) if not keep_preprocessed: cleanup_files(*outputs) @cli.command() def evaluate(): """Evaluate a model's predictions against known labels.""" click.echo( "Not implemented yet. In the future, this command will be used for evaluation." ) sys.exit(-2) @cli.command() def info(): """Return information about this system.""" uname = platform.uname() s = f"""\ Python: Version: {platform.python_version()} Implementation: {platform.python_implementation()} 64-bit: {sys.maxsize > 2**32} Packages: Nondefaced-Detector: {__version__} Nibabel: {nib.__version__} Numpy: {np.__version__} Nobrainer: {nobrainer.__version__} TensorFlow: {tf.__version__} GPU support: {tf.test.is_built_with_gpu_support()} GPU available: {bool(tf.config.list_physical_devices('GPU'))} System: OSType: {uname.system} Release: {uname.release} Version: {uname.version} Architecture: {uname.machine} Timestamp: {datetime.datetime.utcnow().strftime('%Y/%m/%d %T')}""" click.echo(s) if __name__ == "__main__": cli()
[]
[]
[ "TF_CPP_MIN_LOG_LEVEL" ]
[]
["TF_CPP_MIN_LOG_LEVEL"]
python
1
0
src/test/java/com/networknt/oas/SimpleSerializationTest.java
/******************************************************************************* * Copyright (c) 2017 ModelSolv, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * ModelSolv, Inc. - initial API and implementation and/or initial documentation *******************************************************************************/ package com.networknt.oas; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import com.google.common.collect.Lists; import com.google.common.collect.Queues; import com.networknt.jsonoverlay.JsonLoader; import com.networknt.jsonoverlay.Overlay; import com.networknt.jsonoverlay.SerializationOptions.Option; import com.networknt.oas.model.OpenApi3; import com.networknt.oas.model.Schema; import com.networknt.oas.model.impl.OpenApi3Impl; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.Deque; import java.util.Iterator; @RunWith(Enclosed.class) public class SimpleSerializationTest extends Assert { private static final String SPEC_REPO = "OAI/OpenAPI-Specification"; private static final String EXAMPLES_BRANCH = "master"; private static final String EXAMPLES_ROOT = "examples/v3.0"; private static ObjectMapper mapper = new ObjectMapper(); private static ObjectMapper yamlMapper = new YAMLMapper(); @RunWith(Parameterized.class) public static class ParameterizedTests extends Assert { @Parameters(name = "{index}: {1}") public static Collection<Object[]> findExamples() throws IOException { Collection<Object[]> examples = Lists.newArrayList(); Deque<URL> dirs = Queues.newArrayDeque(); String auth = System.getenv("GITHUB_AUTH") != null ? System.getenv("GITHUB_AUTH") + "@" : ""; String request = String.format("https://%sapi.github.com/repos/%s/contents/%s?ref=%s", auth, SPEC_REPO, EXAMPLES_ROOT, EXAMPLES_BRANCH); dirs.add(new URL(request)); while (!dirs.isEmpty()) { URL url = dirs.remove(); JsonNode tree = new JsonLoader().load(url); for (JsonNode result : iterable(tree.elements())) { String type = result.get("type").asText(); String path = result.get("path").asText(); String resultUrl = result.get("url").asText(); if (type.equals("dir")) { dirs.add(new URL(resultUrl)); } else if (type.equals("file") && (path.endsWith(".yaml") || path.endsWith(".json"))) { String downloadUrl = result.get("download_url").asText(); examples.add(new Object[] { new URL(downloadUrl), result.get("name").asText() }); } } } return examples; } @Parameter public URL exampleUrl; @Parameter(1) public String fileName; @Test public void serializeExample() throws Exception { if (!exampleUrl.toString().contains("callback-example")) { OpenApi3 model = (OpenApi3) new OpenApiParser().parse(exampleUrl); JsonNode serialized = Overlay.toJson((OpenApi3Impl) model); JsonNode expected = yamlMapper.readTree(exampleUrl); JSONAssert.assertEquals(mapper.writeValueAsString(expected), mapper.writeValueAsString(serialized), JSONCompareMode.STRICT); } } } public static class NonParameterizedTests { @Test public void toJsonNoticesChanges() throws Exception { OpenApi3 model = parseLocalModel("simpleTest"); assertEquals("simple model", model.getInfo().getTitle()); assertEquals("simple model", Overlay.of(model).toJson().at("/info/title").asText()); // this changes the overlay value but does not refresh cached JSON - // just marks // it as out-of-date model.getInfo().setTitle("changed title"); assertEquals("changed title", model.getInfo().getTitle()); assertEquals("changed title", Overlay.of(model).toJson().at("/info/title").asText()); } @Test public void toJsonFollowsRefs() throws Exception { OpenApi3 model = parseLocalModel("simpleTest"); Schema xSchema = model.getSchema("X"); assertEquals("#/components/schemas/Y", Overlay.of(xSchema).toJson().at("/properties/y/$ref").asText()); assertEquals("integer", Overlay.of(xSchema).toJson(Option.FOLLOW_REFS).at("/properties/y/type").asText()); } } private static OpenApi3 parseLocalModel(String name) throws Exception { URL url = SimpleSerializationTest.class.getResource("/models/" + name + ".yaml"); return (OpenApi3) new OpenApiParser().parse(url); } private static <T> Iterable<T> iterable(final Iterator<T> iterator) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return iterator; } }; } }
[ "\"GITHUB_AUTH\"", "\"GITHUB_AUTH\"" ]
[]
[ "GITHUB_AUTH" ]
[]
["GITHUB_AUTH"]
java
1
0
cluster_status.py
import json import logging import os import traceback from boto3.dynamodb.conditions import Attr, Key import storage from util import lambda_result logger = logging.getLogger('cluster_status') if os.environ.get('DEBUG'): logger.setLevel(logging.DEBUG) def set_cluster_status(event, context): """Set the status of a cluster, ie active, inactive, maintainance_mode, etc""" CLUSTER_TABLE = storage.get_cluster_table() query_string_params = event.get('queryStringParameters', {}) cluster_status = query_string_params.get('cluster_status') if cluster_status is None: return lambda_result( {"message": f'Must provide a status variable in uri query string'}, status_code=500) cluster_name = query_string_params.get('cluster_name') if cluster_name is None: return lambda_result( {"message": (f'Must provide a cluster_name ' f'variable in uri query string')}, status_code=500) try: CLUSTER_TABLE.update_item( Key={ 'id': cluster_name, }, UpdateExpression="SET cluster_status = :r", ExpressionAttributeValues={ ':r': cluster_status }, ReturnValues="UPDATED_NEW" ) return lambda_result( {"message": (f'Updated cluster status for {cluster_name} ' f'to {cluster_status}')}) except Exception: failed_txt = f'Failed to update cluster status for {cluster_name}' logger.exception(failed_txt) return lambda_result({"message": failed_txt}, status_code=500) def set_cluster_environment(event, context): """Set the environment of a cluster, ie dev, stage, prod""" CLUSTER_TABLE = storage.get_cluster_table() query_string_params = event.get('queryStringParameters', {}) environment = query_string_params.get('environment') if environment is None: return lambda_result( {"message": f'Must provide an environment param in uri query string'}, status_code=500) cluster_name = query_string_params.get('cluster_name') if cluster_name is None: return lambda_result( {"message": (f'Must provide a cluster_name ' f'variable in uri query string')}, status_code=500) try: CLUSTER_TABLE.update_item( Key={ 'id': cluster_name, }, UpdateExpression="ADD environment :e", ExpressionAttributeValues={ ':e': set([environment]) }, ReturnValues="UPDATED_NEW" ) msg = (f'Updated cluster environment for {cluster_name} ' f'to {environment}') return lambda_result(msg) except Exception as e: failed_txt = f'Failed to update cluster environment for {cluster_name}' failed_txt += "\n{} \n{}".format( str(e), repr(traceback.format_stack())) print(failed_txt) return lambda_result({"message": failed_txt}, status_code=500) def clusters_per_environment(event, context): """Query cluster status attribute for given environment, requires 'environment' query param, or defaults to all clusters""" clusters = [] environment = event.get('queryStringParameters', {}).get('environment') items = _query_dynamodb(environment) for cluster in items: clusters.append(cluster['id']) return lambda_result(clusters) def cluster_status(event, context): """Query cluster status attribute for given environment, requires 'environment' query param, or defaults to all clusters""" clusters = [] query_string_params = event.get('queryStringParameters', {}) environment = query_string_params.get('environment') cluster_status = query_string_params.get('cluster_status') items = _query_dynamodb(environment, cluster_status) for cluster in items: clusters.append(cluster['id']) return lambda_result(clusters) def set_cluster_metadata(event, context): """Set the metadata of a cluster. metadata is a json blob use for describing extra details about a cluster. """ CLUSTER_TABLE = storage.get_cluster_table() query_string_params = event.get('queryStringParameters', {}) metadata = event.get('body', {}) cluster_name = query_string_params.get('cluster_name') if cluster_name is None: return lambda_result( {"message": (f'Must provide a cluster_name ' f'variable in uri query string')}, status_code=500) try: if isinstance(metadata, str): metadata = json.loads(metadata) CLUSTER_TABLE.update_item( Key={ 'id': cluster_name, }, UpdateExpression="set metadata = :md", ExpressionAttributeValues={ ':md': metadata }, ReturnValues="UPDATED_NEW" ) return lambda_result( {"message": f'Updated cluster metadata for {cluster_name}'} ) except Exception: failed_txt = f'Failed to update cluster metadata for {cluster_name}' logger.exception(failed_txt) logger.error(json.dumps(event)) return lambda_result({"message": failed_txt}, status_code=500) def get_cluster_metadata(event, context): """Get the metadata of a cluster. metadata is a json blob use for describing extra details about a cluster. """ CLUSTER_TABLE = storage.get_cluster_table() query_string_params = event.get('queryStringParameters', {}) cluster_name = query_string_params.get('cluster_name') if cluster_name is None: return { "statusCode": 500, "body": json.dumps( {"message": (f'Must provide a cluster_name ' f'variable in uri query string')}) } status_code = 404 db_response = CLUSTER_TABLE.get_item( Key={ 'id': cluster_name, } ) metadata = {} if 'Item' in db_response: status_code = 200 metadata = db_response['Item'].get('metadata', {}) if isinstance(metadata, str): metadata = json.loads(metadata) metadata['environment'] = db_response['Item'].get('environment') metadata['status'] = db_response['Item'].get('status') metadata['id'] = cluster_name return lambda_result(metadata, status_code=status_code) def _query_dynamodb(environment, status=None, metadata=False): CLUSTER_TABLE = storage.get_cluster_table() fkey = Attr('environment').contains(environment) if status is not None: fkey = fkey & Key('cluster_status').eq(status) response = CLUSTER_TABLE.scan( ProjectionExpression="id", FilterExpression=fkey ) return response.get('Items', [])
[]
[]
[ "DEBUG" ]
[]
["DEBUG"]
python
1
0