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 |
---|---|---|---|---|---|---|---|---|---|---|
examples/pwr_run/checkpointing/throughput/final1_inverse/job38.py
|
"""
#Trains a ResNet on the CIFAR10 dataset.
"""
from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras.callbacks import ReduceLROnPlateau, TensorBoard
from keras.preprocessing.image import ImageDataGenerator
from keras.regularizers import l2
from keras import backend as K
from keras.models import Model
from keras.datasets import cifar10
from keras.applications.mobilenet_v2 import MobileNetV2
from keras import models, layers, optimizers
from datetime import datetime
import tensorflow as tf
import numpy as np
import os
import pdb
import sys
import argparse
import time
import signal
import glob
import json
import send_signal
parser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')
parser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')
parser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')
parser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')
parser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')
parser.set_defaults(resume=False)
args = parser.parse_args()
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=args.gpu_num
# Training parameters
batch_size = 64
args_lr = 0.0015
epoch_begin_time = 0
job_name = sys.argv[0].split('.')[0]
save_files = '/scratch/li.baol/checkpoint_final1_inverse/' + job_name + '*'
total_epochs = 83
starting_epoch = 0
# first step is to update the PID
pid = os.getpid()
message = job_name + ' pid ' + str(pid) # 'job50 pid 3333'
send_signal.send(args.node, 10002, message)
if args.resume:
save_file = glob.glob(save_files)[0]
# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])
starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])
data_augmentation = True
num_classes = 10
# Subtracting pixel mean improves accuracy
subtract_pixel_mean = True
n = 3
# Model name, depth and version
model_type = args.tc #'P100_resnet50_he_256_1'
# Load the CIFAR10 data.
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# Normalize data.
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# If subtract pixel mean is enabled
if subtract_pixel_mean:
x_train_mean = np.mean(x_train, axis=0)
x_train -= x_train_mean
x_test -= x_train_mean
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print('y_train shape:', y_train.shape)
# Convert class vectors to binary class matrices.
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
if args.resume:
print('resume from checkpoint')
message = job_name + ' b_end'
send_signal.send(args.node, 10002, message)
model = keras.models.load_model(save_file)
message = job_name + ' c_end'
send_signal.send(args.node, 10002, message)
else:
print('train from start')
model = models.Sequential()
base_model = MobileNetV2(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)
#base_model.summary()
#pdb.set_trace()
model.add(base_model)
model.add(layers.Flatten())
#model.add(layers.BatchNormalization())
#model.add(layers.Dense(128, activation='relu'))
#model.add(layers.Dropout(0.5))
#model.add(layers.BatchNormalization())
#model.add(layers.Dense(64, activation='relu'))
#model.add(layers.Dropout(0.5))
#model.add(layers.BatchNormalization())
model.add(layers.Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer=Adam(lr=args_lr),
metrics=['accuracy'])
#model.summary()
print(model_type)
#pdb.set_trace()
current_epoch = 0
################### connects interrupt signal to the process #####################
def terminateProcess(signalNumber, frame):
# first record the wasted epoch time
global epoch_begin_time
if epoch_begin_time == 0:
epoch_waste_time = 0
else:
epoch_waste_time = int(time.time() - epoch_begin_time)
message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'
if epoch_waste_time > 0:
send_signal.send(args.node, 10002, message)
print('checkpointing the model triggered by kill -15 signal')
# delete whatever checkpoint that already exists
for f in glob.glob(save_files):
os.remove(f)
model.save('/scratch/li.baol/checkpoint_final1_inverse/' + job_name + '_' + str(current_epoch) + '.h5')
print ('(SIGTERM) terminating the process')
message = job_name + ' checkpoint'
send_signal.send(args.node, 10002, message)
sys.exit()
signal.signal(signal.SIGTERM, terminateProcess)
#################################################################################
logdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name
tensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')
first_epoch_start = 0
class PrintEpoch(keras.callbacks.Callback):
def on_epoch_begin(self, epoch, logs=None):
global current_epoch, first_epoch_start
#remaining_epochs = epochs - epoch
current_epoch = epoch
print('current epoch ' + str(current_epoch))
global epoch_begin_time
epoch_begin_time = time.time()
if epoch == starting_epoch and args.resume:
first_epoch_start = time.time()
message = job_name + ' d_end'
send_signal.send(args.node, 10002, message)
elif epoch == starting_epoch:
first_epoch_start = time.time()
if epoch == starting_epoch:
# send signal to indicate checkpoint is qualified
message = job_name + ' ckpt_qual'
send_signal.send(args.node, 10002, message)
def on_epoch_end(self, epoch, logs=None):
if epoch == starting_epoch:
first_epoch_time = int(time.time() - first_epoch_start)
message = job_name + ' 1st_epoch ' + str(first_epoch_time)
send_signal.send(args.node, 10002, message)
progress = round((epoch+1) / round(total_epochs/2), 2)
message = job_name + ' completion ' + str(progress)
send_signal.send(args.node, 10002, message)
my_callback = PrintEpoch()
callbacks = [tensorboard_callback, my_callback]
#[checkpoint, lr_reducer, lr_scheduler, tensorboard_callback]
# Run training
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=round(total_epochs/2),
validation_data=(x_test, y_test),
shuffle=True,
callbacks=callbacks,
initial_epoch=starting_epoch,
verbose=1
)
# Score trained model.
scores = model.evaluate(x_test, y_test, verbose=1)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])
# send signal to indicate job has finished
message = job_name + ' finish'
send_signal.send(args.node, 10002, message)
|
[] |
[] |
[
"CUDA_DEVICE_ORDER",
"CUDA_VISIBLE_DEVICES"
] |
[]
|
["CUDA_DEVICE_ORDER", "CUDA_VISIBLE_DEVICES"]
|
python
| 2 | 0 | |
api/pkg/onboarding/db/repo_test.go
|
package db_test
import (
"context"
"os"
"testing"
"time"
"getsturdy.com/api/pkg/internal/dbtest"
"getsturdy.com/api/pkg/onboarding"
db_onboarding "getsturdy.com/api/pkg/onboarding/db"
"github.com/jmoiron/sqlx"
"github.com/stretchr/testify/assert"
)
func getDB(t *testing.T) *sqlx.DB {
if os.Getenv("E2E_TEST") == "" {
t.SkipNow()
}
return dbtest.DB(t)
}
func Test_InsertCompletedStep__double_insert_doesnt_fail(t *testing.T) {
repo := db_onboarding.New(getDB(t))
ctx := context.Background()
step := &onboarding.Step{
UserID: "user-id",
ID: "step-id",
CreatedAt: time.Now(),
}
assert.NoError(t, repo.InsertCompletedStep(ctx, step))
assert.NoError(t, repo.InsertCompletedStep(ctx, step))
}
func Test_GetCompletedSteps(t *testing.T) {
repo := db_onboarding.New(getDB(t))
ctx := context.Background()
step := &onboarding.Step{
UserID: "user-id",
ID: "step-id",
CreatedAt: time.Now(),
}
assert.NoError(t, repo.InsertCompletedStep(ctx, step))
steps, err := repo.GetCompletedSteps(ctx, step.UserID)
assert.NoError(t, err)
if assert.Len(t, steps, 1) {
assert.Equal(t, step.UserID, steps[0].UserID)
assert.Equal(t, step.ID, steps[0].ID)
}
}
|
[
"\"E2E_TEST\""
] |
[] |
[
"E2E_TEST"
] |
[]
|
["E2E_TEST"]
|
go
| 1 | 0 | |
main.go
|
package main
import (
"github.com/fabioxgn/go-bot"
_ "github.com/fabioxgn/go-bot/commands/catfacts"
_ "github.com/fabioxgn/go-bot/commands/catgif"
_ "github.com/fabioxgn/go-bot/commands/chucknorris"
_ "github.com/nloadholtes/uniform/ratt"
// Import all the commands you wish to use
"flag"
"os"
"strings"
)
var slack_flag bool
func main() {
flag.BoolVar(&slack_flag, "slack", false, "help message for flagname")
flag.Parse()
if slack_flag {
bot.RunSlack(os.Getenv("SLACK_TOKEN"))
} else {
bot.Run(&bot.Config{
Server: os.Getenv("IRC_SERVER"),
Channels: strings.Split(os.Getenv("IRC_CHANNELS"), ","),
User: os.Getenv("IRC_USER"),
Nick: os.Getenv("IRC_NICK"),
Password: os.Getenv("IRC_PASSWORD"),
UseTLS: true,
Debug: os.Getenv("DEBUG") != ""})
}
}
func init() {
}
|
[
"\"SLACK_TOKEN\"",
"\"IRC_SERVER\"",
"\"IRC_CHANNELS\"",
"\"IRC_USER\"",
"\"IRC_NICK\"",
"\"IRC_PASSWORD\"",
"\"DEBUG\""
] |
[] |
[
"IRC_NICK",
"IRC_CHANNELS",
"IRC_SERVER",
"SLACK_TOKEN",
"IRC_USER",
"DEBUG",
"IRC_PASSWORD"
] |
[]
|
["IRC_NICK", "IRC_CHANNELS", "IRC_SERVER", "SLACK_TOKEN", "IRC_USER", "DEBUG", "IRC_PASSWORD"]
|
go
| 7 | 0 | |
src/onecontainer_api/routers/tests/test_media.py
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2020 Intel Corporation
import os
import time
from fastapi.testclient import TestClient
from onecontainer_api import models, schemas, config, startup_svc
from onecontainer_api.frontend import app
web_server_port = 80
rtmp_server_port = 1935
for svc in config.INITIAL_SERVICES:
if svc["image"] == "web-rtmp":
web_server_port = svc["port"]["80/tcp"]
rtmp_server_port = svc["port"]["1935/tcp"]
break
video_0 = f"http://{config.BACKEND_NETWORK_GATEWAY}:{web_server_port}/sample-videos/fruit-and-vegetable-detection.mp4"
video_1 = f"http://{config.BACKEND_NETWORK_GATEWAY}:{web_server_port}/sample-videos/bottle-detection.mp4"
video_2 = f"http://{config.BACKEND_NETWORK_GATEWAY}:{web_server_port}/sample-videos/face-demographics-walking.mp4"
rtmp_ip = f"{config.BACKEND_NETWORK_GATEWAY}:{rtmp_server_port}"
input_data = {
"source": video_0
}
probe_input = {'streams': [{'index': 0, 'codec_name': 'h264', 'codec_long_name': 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10', 'profile': 'High', 'codec_type': 'video', 'codec_time_base': '1001/120000', 'codec_tag_string': 'avc1', 'codec_tag': '0x31637661', 'width': 960, 'height': 540, 'coded_width': 960, 'coded_height': 544, 'closed_captions': 0, 'has_b_frames': 0, 'sample_aspect_ratio': '1:1', 'display_aspect_ratio': '16:9', 'pix_fmt': 'yuv420p', 'level': 32, 'color_range': 'tv', 'color_space': 'bt709', 'color_transfer': 'bt709', 'color_primaries': 'bt709', 'chroma_location': 'left', 'field_order': 'progressive', 'refs': 1, 'is_avc': 'true', 'nal_length_size': '4', 'r_frame_rate': '60000/1001', 'avg_frame_rate': '60000/1001', 'time_base': '1/60000', 'start_pts': 0, 'start_time': '0.000000', 'duration_ts': 3636633, 'duration': '60.610550', 'bit_rate': '2335818', 'bits_per_raw_sample': '8', 'nb_frames': '3633', 'disposition': {'default': 1, 'dub': 0, 'original': 0, 'comment': 0, 'lyrics': 0, 'karaoke': 0, 'forced': 0, 'hearing_impaired': 0, 'visual_impaired': 0, 'clean_effects': 0, 'attached_pic': 0, 'timed_thumbnails': 0}, 'tags': {'creation_time': '2018-06-15T21:05:12.000000Z', 'language': 'und', 'handler_name': 'Core Media Video'}}], 'format': {'filename': 'http://172.17.0.1:5553/sample-videos/fruit-and-vegetable-detection.mp4', 'nb_streams': 1, 'nb_programs': 0, 'format_name': 'mov,mp4,m4a,3gp,3g2,mj2', 'format_long_name': 'QuickTime / MOV', 'start_time': '0.000000', 'duration': '60.610550', 'size': '17760065', 'bit_rate': '2344154', 'probe_score': 100, 'tags': {'major_brand': 'mp42', 'minor_version': '1', 'compatible_brands': 'mp41mp42isom', 'creation_time': '2018-06-15T21:05:12.000000Z'}}}
supported_containers = ["mkv", "mp4", "mov", "m4a", "avi", "webm", "wmv", "vob"]
supported_audio_codecs = {
"aac": "aac",
"ogg": "libvorbis",
"wav": "pcm_s16le",
"flac": "flac",
"ac3": "ac3",
"wma": "wmav2",
}
supported_gpu_codecs = {
"mp4": "h264_vaapi",
"mkv": "hevc_vaapi",
"mov": "mjpeg_vaapi",
"webm": "vp8_vaapi"
}
pipeline_codecs = {
"input_file": {
"source": video_1
},
"outputs": [
{
"container": "mp4",
"channels": [
{
"stream_type": "video",
"codec": "libx264"
}
]
}
]
}
pipeline_h264 = {
"input_file": {
"source": video_1
},
"outputs": [
{
"container": "mkv",
"channels": [
{
"stream_type": "video",
"codec": "libx264",
"codec_params": {
"preset": "ultrafast",
"tune": "film",
"crf": "30"
}
}
]
}
]
}
pipeline_mpegts = {
"input_file": {
"source": video_1,
"params": {
"re": None
}
},
"outputs": [
{
"container": "mpegts",
"channels": [
{
"stream_type": "video",
"codec": "libx264",
"codec_params": {
"preset": "fast",
"crf": "30"
}
}
]
}
]
}
pipeline_rtmp = {
"input_file": {
"source": video_1,
"params": {
"re": None
}
},
"outputs": [
{
"container": "flv",
"rtmp_ip": rtmp_ip,
"rtmp_path": "live",
"channels": [
{
"stream_type": "video",
"codec": "libx264",
"codec_params": {
"preset": "fast",
"crf": "30"
}
}
]
}
]
}
pipeline_filters = {
"input_file": {
"source": video_2
},
"outputs": [
{
"container": "mkv",
"channels": [
{
"stream_type": "video",
"filters": {
"scale": {
"w": "iw/2",
"h": -1
},
"deflicker": {
"mode": "pm",
"size": 10
},
"reverse": {},
"hue": {
"s": 0
}
}
},
{
"stream_type": "audio",
"filters": {
"atrim": {
"start": 1
},
"asetpts": "PTS-STARTPTS",
"volume": {
"volume": 0.8
},
"areverse": {},
"aphaser": {}
}
}
]
}
]
}
pipeline_copy = {
"input_file": {
"source": video_2
},
"outputs": [
{
"container": "mp4",
"channels": [
{
"stream_type": "video",
"codec": "copy"
},
{
"stream_type": "audio",
"codec": "copy"
}
]
}
]
}
pipeline_empty = {
"input_file": {
"source": video_2
},
"outputs": [
{
"container": "mp4"
}
]
}
pipeline_mkv = {
"input_file": {
"source": video_1
},
"outputs": [
{
"container": "mkv",
"params": {
"metadata": "stereo_mode=left_right",
"default_mode": "infer_no_subs"
}
}
]
}
pipeline_mp4 = {
"input_file": {
"source":video_1
},
"outputs": [
{
"container": "mp4",
"params": {
"movflags": "isml+frag_keyframe"
}
}
]
}
pipeline_aac = {
"input_file": {
"source": video_2
},
"outputs": [
{
"container": "aac",
"channels": [
{
"stream_type": "audio",
"codec": "aac",
"codec_params": {
"ab": 192000,
"profile": "aac_ltp",
"strict": "-2",
}
},
{
"stream_type": "video",
"params": {
"vn": None
}
}
]
}
]
}
class TestMedia():
def setup_method(self):
models.Base.metadata.create_all(bind=models.engine)
def teardown_method(self):
os.remove(config.DATABASE_URL.split("///")[1])
def test_probe(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/probe?sync=true", json=input_data)
assert response.status_code == 200
assert response.json() == probe_input
def test_probe_missing_fields(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/probe?sync=true", json={})
assert response.status_code == 400
assert response.json().get("status") == "InputFile field required: source"
def test_probe_wrong_data(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/probe?sync=true", json={"source": "wrong"})
assert response.status_code == 400
assert response.json().get("status", {}).get('detail', {}).get('description') == ["wrong: No such file or directory"]
response = client.post(f"/media/{svc_id}/probe?sync=true", json={"source": ""})
assert response.status_code == 400
assert response.json().get("status", {}).get('detail', {}).get("description") == [": No such file or directory"]
response = client.post(f"/media/{svc_id}/probe?sync=true", json={"source": None})
assert response.status_code == 400
assert response.json().get("status") == "InputFile none is not an allowed value: source"
response = client.post(f"/media/{svc_id}/probe?sync=true", json={"source": 1})
assert response.status_code == 400
assert response.json().get("status", {}).get('detail', {}).get("description") == ["1: No such file or directory"]
def test_pipeline_missing_fields(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
json_data = pipeline_codecs.copy()
json_data["outputs"] = [{}]
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 400
assert response.json().get("status") == "Pipeline field required: outputs,0,container"
json_data["outputs"][0] = {"container": "test", "channels": [{}]}
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 400
assert response.json().get("status") == "Pipeline field required: outputs,0,channels,0,stream_type"
json_data["outputs"] = []
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 400
assert response.json().get("status", {}).get('detail', {}).get('description') == "No outputs specified"
json_data.pop("input_file")
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 400
assert response.json().get("status") == "Pipeline field required: input_file"
def test_pipeline_unsupported_data(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
json_data = pipeline_codecs.copy()
json_data["outputs"][0]["container"] = "wrong"
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 200
pipeline_id = response.json()['id']
time.sleep(3)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
for output in response.json():
assert output['status'] == 'error'
assert output['command_output'][-1].strip() == f"{output.get('id')}.wrong: Invalid argument"
json_data["outputs"][0]["container"] = "mkv"
json_data["outputs"][0]["channels"][0]["codec"] = "wrong"
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 200
pipeline_id = response.json()['id']
time.sleep(2)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
for output in response.json():
assert output['status'] == 'error'
assert output['command_output'][-1].strip() == "Unknown encoder 'wrong'"
json_data["outputs"][0]["channels"][0]["codec"] = "libx264"
json_data["outputs"][0]["channels"][0]["stream_type"] = "wrong"
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] != 'error'
assert result[index]['command'] == f"ffmpeg -i {video_1} -map 0:v {outputs[index]}"
def test_pipeline_copy(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=pipeline_copy)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] != 'error'
assert result[index]['command'] == f"ffmpeg -i {video_2} -map 0:v -map 0:a -acodec copy -vcodec copy {outputs[index]}"
def test_pipeline_empty(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=pipeline_empty)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] != 'error'
assert result[index]['command'] == f"ffmpeg -i {video_2} -map 0:v -map 0:a {outputs[index]}"
def test_pipeline_mkv(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=pipeline_mkv)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] != 'error'
assert result[index]['command'] == f"ffmpeg -i {video_1} -map 0:v -default_mode infer_no_subs -metadata stereo_mode=left_right {outputs[index]}"
def test_pipeline_mp4(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=pipeline_mp4)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] != 'error'
assert result[index]['command'] == f"ffmpeg -i {video_1} -map 0:v -movflags isml+frag_keyframe {outputs[index]}"
def test_pipeline_aac(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=pipeline_aac)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] != 'error'
assert result[index]['command'] == f"ffmpeg -i {video_2} -map 0:v -map 0:a -ab 192000 -acodec aac -profile:a aac_ltp -strict -2 -vn {outputs[index]}"
def test_pipeline_h264(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=pipeline_h264)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
time.sleep(2)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] == 'finished'
assert result[index]['command'] == f"ffmpeg -i {video_1} -map 0:v -crf 30 -preset ultrafast -tune film -vcodec libx264 {outputs[index]}"
def test_pipeline_filters(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=pipeline_filters)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
time.sleep(5)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] == 'finished'
assert result[index]['command'] == f"ffmpeg -i {video_2} -filter_complex [0:v]scale=h=-1:w=iw/2[s0];[s0]deflicker=mode=pm:size=10[s1];[s1]reverse[s2];[s2]hue=s=0[s3];[0:a]atrim=start=1[s4];[s4]asetpts=PTS-STARTPTS[s5];[s5]volume=volume=0.8[s6];[s6]areverse[s7];[s7]aphaser[s8] -map [s3] -map [s8] {outputs[index]}"
def test_pipeline_supported_containers(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
json_data = pipeline_empty.copy()
for container in supported_containers:
json_data["outputs"][0]["container"] = container
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
timeout = 15
finished = False
while not finished and timeout:
time.sleep(3)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] != 'error'
if result[index]['status'] == 'finished':
assert result[index]['command_retcode'] == 0
assert result[index]['command'] == f"ffmpeg -i {video_2} -map 0:v -map 0:a {outputs[index]}"
finished = True
timeout -= 1
if not finished:
assert False
def test_pipeline_supported_audio_codecs(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
json_data = pipeline_empty.copy()
for extension, codec in supported_audio_codecs.items():
json_data["outputs"][0]["container"] = extension
json_data["outputs"][0]["channels"] = [{"stream_type": "audio", "codec": codec}, {"stream_type": "video", "params": {"vn": None}}]
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
timeout = 15
finished = False
while not finished and timeout:
time.sleep(3)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] != 'error'
if result[index]['status'] == 'finished':
assert result[index]['command_retcode'] == 0
assert result[index]['command'] == f"ffmpeg -i {video_2} -map 0:v -map 0:a -acodec {codec} -vn {outputs[index]}"
finished = True
timeout -= 1
if not finished:
assert False
def test_pipeline_supported_gpu_codecs(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
json_data = pipeline_empty.copy()
for extension, codec in supported_gpu_codecs.items():
json_data["outputs"][0]["container"] = extension
json_data["outputs"][0]["params"] = {"vaapi_device": "/dev/dri/renderD128"}
json_data["outputs"][0]["channels"] = [{"stream_type": "video", "codec": codec, "params": {"vf":"format=nv12,hwupload"}}]
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
timeout = 15
finished = False
while not finished or timeout == 0:
time.sleep(3)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] != 'error'
if result[index]['status'] == 'finished':
assert result[index]['command_retcode'] == 0
assert result[index]['command'] == f"ffmpeg -i {video_2} -map 0:v -map 0:a -vaapi_device /dev/dri/renderD128 -vcodec {codec} -vf format=nv12,hwupload {outputs[index]}"
finished = True
timeout -= 1
if not finished:
assert False
def test_pipeline_ttl(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
json_data = pipeline_copy.copy()
json_data["ttl"] = 5
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 200
result = response.json()
time.sleep(6)
response = client.get(f"/media/{svc_id}/pipeline/{result['id']}?sync=true")
assert response.status_code == 400
assert response.json().get("status", {}).get('detail', {}).get("description") == f"Pipeline {result['id']} doesn't exist"
def test_pipeline_azure_upload(self):
ks = os.getenv("AZURE_STORAGE_CONNECTION_STRING")
bucket = os.getenv("CLOUD_STORAGE_BUCKET")
if ks and bucket:
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
json_data = pipeline_copy.copy()
json_data["outputs"][0]["storage"] = [{
"name": "azure",
"bucket": bucket,
"env": {
"AZURE_STORAGE_CONNECTION_STRING": ks
}
}]
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=json_data)
assert response.status_code == 200
# response = client.get(f"/media/{svc_id}/pipeline/{result['id']}?sync=true")
def test_pipeline_mpegts(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=pipeline_mpegts)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
time.sleep(30)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] == 'running'
assert result[index]['command'] == f"ffmpeg -re -i {video_1} -map 0:v -f mpegts -crf 30 -preset fast -vcodec libx264 {outputs[index]}"
time.sleep(15)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] == 'finished'
def test_pipeline_stop(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=pipeline_mpegts)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
time.sleep(2)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] == 'running'
assert result[index]['command'] == f"ffmpeg -re -i {video_1} -map 0:v -f mpegts -crf 30 -preset fast -vcodec libx264 {outputs[index]}"
time.sleep(2)
response = client.delete(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] == 'finished'
def test_pipeline_rtmp(self):
with TestClient(app) as client:
response = client.get("/service")
data = list(filter(lambda x: x['app'] == 'mers-ffmpeg', response.json()))[0]
svc_id = data.pop("id")
response = client.post(f"/media/{svc_id}/pipeline?sync=true", json=pipeline_rtmp)
assert response.status_code == 200
pipeline_id = response.json()['id']
outputs = response.json().get("outputs", [])
time.sleep(30)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert outputs[index] == f"rtmp://{rtmp_ip}/live"
assert result[index]['status'] == 'running'
assert result[index]['command'] == f"ffmpeg -re -i {video_1} -map 0:v -f flv -crf 30 -preset fast -vcodec libx264 {outputs[index]}"
time.sleep(15)
response = client.get(f"/media/{svc_id}/pipeline/{pipeline_id}?sync=true")
assert response.status_code == 200
result = response.json()
for index in range(len(result)):
assert result[index]['status'] == 'finished'
|
[] |
[] |
[
"CLOUD_STORAGE_BUCKET",
"AZURE_STORAGE_CONNECTION_STRING"
] |
[]
|
["CLOUD_STORAGE_BUCKET", "AZURE_STORAGE_CONNECTION_STRING"]
|
python
| 2 | 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', 'backend_crm.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 | |
manage.py
|
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'visitkoreakz.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 | |
src/cmd/dist/test.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
func cmdtest() {
gogcflags = os.Getenv("GO_GCFLAGS")
var t tester
var noRebuild bool
flag.BoolVar(&t.listMode, "list", false, "list available tests")
flag.BoolVar(&t.rebuild, "rebuild", false, "rebuild everything first")
flag.BoolVar(&noRebuild, "no-rebuild", false, "overrides -rebuild (historical dreg)")
flag.BoolVar(&t.keepGoing, "k", false, "keep going even when error occurred")
flag.BoolVar(&t.race, "race", false, "run in race builder mode (different set of tests)")
flag.BoolVar(&t.compileOnly, "compile-only", false, "compile tests, but don't run them. This is for some builders. Not all dist tests respect this flag, but most do.")
flag.StringVar(&t.banner, "banner", "##### ", "banner prefix; blank means no section banners")
flag.StringVar(&t.runRxStr, "run", os.Getenv("GOTESTONLY"),
"run only those tests matching the regular expression; empty means to run all. "+
"Special exception: if the string begins with '!', the match is inverted.")
xflagparse(-1) // any number of args
if noRebuild {
t.rebuild = false
}
t.run()
}
// tester executes cmdtest.
type tester struct {
race bool
listMode bool
rebuild bool
failed bool
keepGoing bool
compileOnly bool // just try to compile all tests, but no need to run
runRxStr string
runRx *regexp.Regexp
runRxWant bool // want runRx to match (true) or not match (false)
runNames []string // tests to run, exclusive with runRx; empty means all
banner string // prefix, or "" for none
lastHeading string // last dir heading printed
cgoEnabled bool
partial bool
haveTime bool // the 'time' binary is available
tests []distTest
timeoutScale int
worklist []*work
}
type work struct {
dt *distTest
cmd *exec.Cmd
start chan bool
out []byte
err error
end chan bool
}
// A distTest is a test run by dist test.
// Each test has a unique name and belongs to a group (heading)
type distTest struct {
name string // unique test name; may be filtered with -run flag
heading string // group section; this header is printed before the test is run.
fn func(*distTest) error
}
func (t *tester) run() {
timelog("start", "dist test")
var exeSuffix string
if goos == "windows" {
exeSuffix = ".exe"
}
if _, err := os.Stat(filepath.Join(gobin, "go"+exeSuffix)); err == nil {
os.Setenv("PATH", fmt.Sprintf("%s%c%s", gobin, os.PathListSeparator, os.Getenv("PATH")))
}
slurp, err := exec.Command("go", "env", "CGO_ENABLED").Output()
if err != nil {
fatalf("Error running go env CGO_ENABLED: %v", err)
}
t.cgoEnabled, _ = strconv.ParseBool(strings.TrimSpace(string(slurp)))
if flag.NArg() > 0 && t.runRxStr != "" {
fatalf("the -run regular expression flag is mutually exclusive with test name arguments")
}
t.runNames = flag.Args()
if t.hasBash() {
if _, err := exec.LookPath("time"); err == nil {
t.haveTime = true
}
}
if t.rebuild {
t.out("Building packages and commands.")
// Force rebuild the whole toolchain.
goInstall("go", append([]string{"-a", "-i"}, toolchain...)...)
}
// Complete rebuild bootstrap, even with -no-rebuild.
// If everything is up-to-date, this is a no-op.
// If everything is not up-to-date, the first checkNotStale
// during the test process will kill the tests, so we might
// as well install the world.
// Now that for example "go install cmd/compile" does not
// also install runtime (you need "go install -i cmd/compile"
// for that), it's easy for previous workflows like
// "rebuild the compiler and then run run.bash"
// to break if we don't automatically refresh things here.
// Rebuilding is a shortened bootstrap.
// See cmdbootstrap for a description of the overall process.
//
// But don't do this if we're running in the Go build system,
// where cmd/dist is invoked many times. This just slows that
// down (Issue 24300).
if !t.listMode && os.Getenv("GO_BUILDER_NAME") == "" {
goInstall("go", append([]string{"-i"}, toolchain...)...)
goInstall("go", append([]string{"-i"}, toolchain...)...)
goInstall("go", "std", "cmd")
checkNotStale("go", "std", "cmd")
}
t.timeoutScale = 1
switch goarch {
case "arm":
t.timeoutScale = 2
case "mips", "mipsle", "mips64", "mips64le":
t.timeoutScale = 4
}
if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
t.timeoutScale, err = strconv.Atoi(s)
if err != nil {
fatalf("failed to parse $GO_TEST_TIMEOUT_SCALE = %q as integer: %v", s, err)
}
}
if t.runRxStr != "" {
if t.runRxStr[0] == '!' {
t.runRxWant = false
t.runRxStr = t.runRxStr[1:]
} else {
t.runRxWant = true
}
t.runRx = regexp.MustCompile(t.runRxStr)
}
t.registerTests()
if t.listMode {
for _, tt := range t.tests {
fmt.Println(tt.name)
}
return
}
// We must unset GOROOT_FINAL before tests, because runtime/debug requires
// correct access to source code, so if we have GOROOT_FINAL in effect,
// at least runtime/debug test will fail.
// If GOROOT_FINAL was set before, then now all the commands will appear stale.
// Nothing we can do about that other than not checking them below.
// (We call checkNotStale but only with "std" not "cmd".)
os.Setenv("GOROOT_FINAL_OLD", os.Getenv("GOROOT_FINAL")) // for cmd/link test
os.Unsetenv("GOROOT_FINAL")
for _, name := range t.runNames {
if !t.isRegisteredTestName(name) {
fatalf("unknown test %q", name)
}
}
// On a few builders, make GOROOT unwritable to catch tests writing to it.
if strings.HasPrefix(os.Getenv("GO_BUILDER_NAME"), "linux-") {
if os.Getuid() == 0 {
// Don't bother making GOROOT unwritable:
// we're running as root, so permissions would have no effect.
} else {
xatexit(t.makeGOROOTUnwritable())
}
}
for _, dt := range t.tests {
if !t.shouldRunTest(dt.name) {
t.partial = true
continue
}
dt := dt // dt used in background after this iteration
if err := dt.fn(&dt); err != nil {
t.runPending(&dt) // in case that hasn't been done yet
t.failed = true
if t.keepGoing {
log.Printf("Failed: %v", err)
} else {
fatalf("Failed: %v", err)
}
}
}
t.runPending(nil)
timelog("end", "dist test")
if t.failed {
fmt.Println("\nFAILED")
xexit(1)
} else if incomplete[goos+"/"+goarch] {
fmt.Println("\nFAILED (incomplete port)")
xexit(1)
} else if t.partial {
fmt.Println("\nALL TESTS PASSED (some were excluded)")
} else {
fmt.Println("\nALL TESTS PASSED")
}
}
func (t *tester) shouldRunTest(name string) bool {
if t.runRx != nil {
return t.runRx.MatchString(name) == t.runRxWant
}
if len(t.runNames) == 0 {
return true
}
for _, runName := range t.runNames {
if runName == name {
return true
}
}
return false
}
// short returns a -short flag to pass to 'go test'.
// It returns "-short", unless the environment variable
// GO_TEST_SHORT is set to a non-empty, false-ish string.
//
// This environment variable is meant to be an internal
// detail between the Go build system and cmd/dist
// and is not intended for use by users.
func short() string {
if v := os.Getenv("GO_TEST_SHORT"); v != "" {
short, err := strconv.ParseBool(v)
if err != nil {
fatalf("invalid GO_TEST_SHORT %q: %v", v, err)
}
if !short {
return "-short=false"
}
}
return "-short"
}
// goTest returns the beginning of the go test command line.
// Callers should use goTest and then pass flags overriding these
// defaults as later arguments in the command line.
func (t *tester) goTest() []string {
return []string{
"go", "test", short(), "-count=1", t.tags(), t.runFlag(""),
}
}
func (t *tester) tags() string {
if t.iOS() {
return "-tags=lldb"
}
return "-tags="
}
// timeoutDuration converts the provided number of seconds into a
// time.Duration, scaled by the t.timeoutScale factor.
func (t *tester) timeoutDuration(sec int) time.Duration {
return time.Duration(sec) * time.Second * time.Duration(t.timeoutScale)
}
// timeout returns the "-timeout=" string argument to "go test" given
// the number of seconds of timeout. It scales it by the
// t.timeoutScale factor.
func (t *tester) timeout(sec int) string {
return "-timeout=" + t.timeoutDuration(sec).String()
}
// ranGoTest and stdMatches are state closed over by the stdlib
// testing func in registerStdTest below. The tests are run
// sequentially, so there's no need for locks.
//
// ranGoBench and benchMatches are the same, but are only used
// in -race mode.
var (
ranGoTest bool
stdMatches []string
ranGoBench bool
benchMatches []string
)
func (t *tester) registerStdTest(pkg string) {
testName := "go_test:" + pkg
if t.runRx == nil || t.runRx.MatchString(testName) == t.runRxWant {
stdMatches = append(stdMatches, pkg)
}
t.tests = append(t.tests, distTest{
name: testName,
heading: "Testing packages.",
fn: func(dt *distTest) error {
if ranGoTest {
return nil
}
t.runPending(dt)
timelog("start", dt.name)
defer timelog("end", dt.name)
ranGoTest = true
timeoutSec := 180
for _, pkg := range stdMatches {
if pkg == "cmd/go" {
timeoutSec *= 3
break
}
}
// Special case for our slow cross-compiled
// qemu builders:
if t.shouldUsePrecompiledStdTest() {
return t.runPrecompiledStdTest(t.timeoutDuration(timeoutSec))
}
args := []string{
"test",
short(),
t.tags(),
t.timeout(timeoutSec),
"-gcflags=all=" + gogcflags,
}
if t.race {
args = append(args, "-race")
}
if t.compileOnly {
args = append(args, "-run=^$")
}
args = append(args, stdMatches...)
cmd := exec.Command("go", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
},
})
}
func (t *tester) registerRaceBenchTest(pkg string) {
testName := "go_test_bench:" + pkg
if t.runRx == nil || t.runRx.MatchString(testName) == t.runRxWant {
benchMatches = append(benchMatches, pkg)
}
t.tests = append(t.tests, distTest{
name: testName,
heading: "Running benchmarks briefly.",
fn: func(dt *distTest) error {
if ranGoBench {
return nil
}
t.runPending(dt)
timelog("start", dt.name)
defer timelog("end", dt.name)
ranGoBench = true
args := []string{
"test",
short(),
"-race",
t.timeout(1200), // longer timeout for race with benchmarks
"-run=^$", // nothing. only benchmarks.
"-benchtime=.1s",
"-cpu=4",
}
if !t.compileOnly {
args = append(args, "-bench=.*")
}
args = append(args, benchMatches...)
cmd := exec.Command("go", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
},
})
}
// stdOutErrAreTerminals is defined in test_linux.go, to report
// whether stdout & stderr are terminals.
var stdOutErrAreTerminals func() bool
func (t *tester) registerTests() {
// Fast path to avoid the ~1 second of `go list std cmd` when
// the caller lists specific tests to run. (as the continuous
// build coordinator does).
if len(t.runNames) > 0 {
for _, name := range t.runNames {
if strings.HasPrefix(name, "go_test:") {
t.registerStdTest(strings.TrimPrefix(name, "go_test:"))
}
if strings.HasPrefix(name, "go_test_bench:") {
t.registerRaceBenchTest(strings.TrimPrefix(name, "go_test_bench:"))
}
}
} else {
// Use a format string to only list packages and commands that have tests.
const format = "{{if (or .TestGoFiles .XTestGoFiles)}}{{.ImportPath}}{{end}}"
cmd := exec.Command("go", "list", "-f", format)
if t.race {
cmd.Args = append(cmd.Args, "-tags=race")
}
cmd.Args = append(cmd.Args, "std")
if t.shouldTestCmd() {
cmd.Args = append(cmd.Args, "cmd")
}
cmd.Stderr = new(bytes.Buffer)
all, err := cmd.Output()
if err != nil {
fatalf("Error running go list std cmd: %v:\n%s", err, cmd.Stderr)
}
pkgs := strings.Fields(string(all))
for _, pkg := range pkgs {
t.registerStdTest(pkg)
}
if t.race {
for _, pkg := range pkgs {
if t.packageHasBenchmarks(pkg) {
t.registerRaceBenchTest(pkg)
}
}
}
}
// Test the os/user package in the pure-Go mode too.
if !t.compileOnly {
t.tests = append(t.tests, distTest{
name: "osusergo",
heading: "os/user with tag osusergo",
fn: func(dt *distTest) error {
t.addCmd(dt, "src", t.goTest(), t.timeout(300), "-tags=osusergo", "os/user")
return nil
},
})
}
if t.race {
return
}
// Runtime CPU tests.
if !t.compileOnly && goos != "js" { // js can't handle -cpu != 1
testName := "runtime:cpu124"
t.tests = append(t.tests, distTest{
name: testName,
heading: "GOMAXPROCS=2 runtime -cpu=1,2,4 -quick",
fn: func(dt *distTest) error {
cmd := t.addCmd(dt, "src", t.goTest(), t.timeout(300), "runtime", "-cpu=1,2,4", "-quick")
// We set GOMAXPROCS=2 in addition to -cpu=1,2,4 in order to test runtime bootstrap code,
// creation of first goroutines and first garbage collections in the parallel setting.
cmd.Env = append(os.Environ(), "GOMAXPROCS=2")
return nil
},
})
}
// This test needs its stdout/stderr to be terminals, so we don't run it from cmd/go's tests.
// See issue 18153.
if goos == "linux" {
t.tests = append(t.tests, distTest{
name: "cmd_go_test_terminal",
heading: "cmd/go terminal test",
fn: func(dt *distTest) error {
t.runPending(dt)
timelog("start", dt.name)
defer timelog("end", dt.name)
if !stdOutErrAreTerminals() {
fmt.Println("skipping terminal test; stdout/stderr not terminals")
return nil
}
cmd := exec.Command("go", "test")
cmd.Dir = filepath.Join(os.Getenv("GOROOT"), "src/cmd/go/testdata/testterminal18153")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
},
})
}
// On the builders only, test that a moved GOROOT still works.
// Fails on iOS because CC_FOR_TARGET refers to clangwrap.sh
// in the unmoved GOROOT.
// Fails on Android and js/wasm with an exec format error.
// Fails on plan9 with "cannot find GOROOT" (issue #21016).
if os.Getenv("GO_BUILDER_NAME") != "" && goos != "android" && !t.iOS() && goos != "plan9" && goos != "js" {
t.tests = append(t.tests, distTest{
name: "moved_goroot",
heading: "moved GOROOT",
fn: func(dt *distTest) error {
t.runPending(dt)
timelog("start", dt.name)
defer timelog("end", dt.name)
moved := goroot + "-moved"
if err := os.Rename(goroot, moved); err != nil {
if goos == "windows" {
// Fails on Windows (with "Access is denied") if a process
// or binary is in this directory. For instance, using all.bat
// when run from c:\workdir\go\src fails here
// if GO_BUILDER_NAME is set. Our builders invoke tests
// a different way which happens to work when sharding
// tests, but we should be tolerant of the non-sharded
// all.bat case.
log.Printf("skipping test on Windows")
return nil
}
return err
}
// Run `go test fmt` in the moved GOROOT.
cmd := exec.Command(filepath.Join(moved, "bin", "go"), "test", "fmt")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// Don't set GOROOT in the environment.
for _, e := range os.Environ() {
if !strings.HasPrefix(e, "GOROOT=") && !strings.HasPrefix(e, "GOCACHE=") {
cmd.Env = append(cmd.Env, e)
}
}
err := cmd.Run()
if rerr := os.Rename(moved, goroot); rerr != nil {
fatalf("failed to restore GOROOT: %v", rerr)
}
return err
},
})
}
// Test that internal linking of standard packages does not
// require libgcc. This ensures that we can install a Go
// release on a system that does not have a C compiler
// installed and still build Go programs (that don't use cgo).
for _, pkg := range cgoPackages {
if !t.internalLink() {
break
}
// ARM libgcc may be Thumb, which internal linking does not support.
if goarch == "arm" {
break
}
pkg := pkg
var run string
if pkg == "net" {
run = "TestTCPStress"
}
t.tests = append(t.tests, distTest{
name: "nolibgcc:" + pkg,
heading: "Testing without libgcc.",
fn: func(dt *distTest) error {
// What matters is that the tests build and start up.
// Skip expensive tests, especially x509 TestSystemRoots.
t.addCmd(dt, "src", t.goTest(), "-ldflags=-linkmode=internal -libgcc=none", "-run=^Test[^CS]", pkg, t.runFlag(run))
return nil
},
})
}
// Test internal linking of PIE binaries where it is supported.
if goos == "linux" && (goarch == "amd64" || goarch == "arm64") {
t.tests = append(t.tests, distTest{
name: "pie_internal",
heading: "internal linking of -buildmode=pie",
fn: func(dt *distTest) error {
t.addCmd(dt, "src", t.goTest(), "reflect", "-buildmode=pie", "-ldflags=-linkmode=internal", t.timeout(60))
return nil
},
})
// Also test a cgo package.
if t.cgoEnabled && t.internalLink() {
t.tests = append(t.tests, distTest{
name: "pie_internal_cgo",
heading: "internal linking of -buildmode=pie",
fn: func(dt *distTest) error {
t.addCmd(dt, "src", t.goTest(), "os/user", "-buildmode=pie", "-ldflags=-linkmode=internal", t.timeout(60))
return nil
},
})
}
}
// sync tests
if goos != "js" { // js doesn't support -cpu=10
t.tests = append(t.tests, distTest{
name: "sync_cpu",
heading: "sync -cpu=10",
fn: func(dt *distTest) error {
t.addCmd(dt, "src", t.goTest(), "sync", t.timeout(120), "-cpu=10", t.runFlag(""))
return nil
},
})
}
if t.raceDetectorSupported() {
t.tests = append(t.tests, distTest{
name: "race",
heading: "Testing race detector",
fn: t.raceTest,
})
}
if t.cgoEnabled && !t.iOS() {
// Disabled on iOS. golang.org/issue/15919
t.registerHostTest("cgo_stdio", "../misc/cgo/stdio", "misc/cgo/stdio", ".")
t.registerHostTest("cgo_life", "../misc/cgo/life", "misc/cgo/life", ".")
fortran := os.Getenv("FC")
if fortran == "" {
fortran, _ = exec.LookPath("gfortran")
}
if t.hasBash() && goos != "android" && fortran != "" {
t.tests = append(t.tests, distTest{
name: "cgo_fortran",
heading: "../misc/cgo/fortran",
fn: func(dt *distTest) error {
t.addCmd(dt, "misc/cgo/fortran", "./test.bash", fortran)
return nil
},
})
}
if t.hasSwig() && goos != "android" {
t.tests = append(t.tests, distTest{
name: "swig_stdio",
heading: "../misc/swig/stdio",
fn: func(dt *distTest) error {
t.addCmd(dt, "misc/swig/stdio", t.goTest())
return nil
},
})
if t.hasCxx() {
t.tests = append(t.tests, distTest{
name: "swig_callback",
heading: "../misc/swig/callback",
fn: func(dt *distTest) error {
t.addCmd(dt, "misc/swig/callback", t.goTest())
return nil
},
})
}
}
}
if t.cgoEnabled {
t.tests = append(t.tests, distTest{
name: "cgo_test",
heading: "../misc/cgo/test",
fn: t.cgoTest,
})
}
// Don't run these tests with $GO_GCFLAGS because most of them
// assume that they can run "go install" with no -gcflags and not
// recompile the entire standard library. If make.bash ran with
// special -gcflags, that's not true.
if t.cgoEnabled && gogcflags == "" {
t.registerHostTest("testgodefs", "../misc/cgo/testgodefs", "misc/cgo/testgodefs", ".")
t.registerTest("testso", "../misc/cgo/testso", t.goTest(), t.timeout(600), ".")
t.registerTest("testsovar", "../misc/cgo/testsovar", t.goTest(), t.timeout(600), ".")
if t.supportedBuildmode("c-archive") {
t.registerHostTest("testcarchive", "../misc/cgo/testcarchive", "misc/cgo/testcarchive", ".")
}
if t.supportedBuildmode("c-shared") {
t.registerHostTest("testcshared", "../misc/cgo/testcshared", "misc/cgo/testcshared", ".")
}
if t.supportedBuildmode("shared") {
t.registerTest("testshared", "../misc/cgo/testshared", t.goTest(), t.timeout(600), ".")
}
if t.supportedBuildmode("plugin") {
t.registerTest("testplugin", "../misc/cgo/testplugin", t.goTest(), t.timeout(600), ".")
}
if gohostos == "linux" && goarch == "amd64" {
t.registerTest("testasan", "../misc/cgo/testasan", "go", "run", "main.go")
}
if mSanSupported(goos, goarch) {
t.registerHostTest("testsanitizers/msan", "../misc/cgo/testsanitizers", "misc/cgo/testsanitizers", ".")
}
if t.hasBash() && goos != "android" && !t.iOS() && gohostos != "windows" {
t.registerHostTest("cgo_errors", "../misc/cgo/errors", "misc/cgo/errors", ".")
}
if gohostos == "linux" && t.extLink() {
t.registerTest("testsigfwd", "../misc/cgo/testsigfwd", "go", "run", "main.go")
}
}
// Doc tests only run on builders.
// They find problems approximately never.
if goos != "js" && goos != "android" && !t.iOS() && os.Getenv("GO_BUILDER_NAME") != "" {
t.registerTest("doc_progs", "../doc/progs", "go", "run", "run.go")
t.registerTest("wiki", "../doc/articles/wiki", t.goTest(), ".")
t.registerTest("codewalk", "../doc/codewalk", t.goTest(), "codewalk_test.go")
}
if goos != "android" && !t.iOS() {
// There are no tests in this directory, only benchmarks.
// Check that the test binary builds but don't bother running it.
// (It has init-time work to set up for the benchmarks that is not worth doing unnecessarily.)
t.registerTest("bench_go1", "../test/bench/go1", t.goTest(), "-c", "-o="+os.DevNull)
}
if goos != "android" && !t.iOS() {
// Only start multiple test dir shards on builders,
// where they get distributed to multiple machines.
// See issues 20141 and 31834.
nShards := 1
if os.Getenv("GO_BUILDER_NAME") != "" {
nShards = 10
}
if n, err := strconv.Atoi(os.Getenv("GO_TEST_SHARDS")); err == nil {
nShards = n
}
for shard := 0; shard < nShards; shard++ {
shard := shard
t.tests = append(t.tests, distTest{
name: fmt.Sprintf("test:%d_%d", shard, nShards),
heading: "../test",
fn: func(dt *distTest) error { return t.testDirTest(dt, shard, nShards) },
})
}
}
if goos != "android" && !t.iOS() && goos != "js" {
t.tests = append(t.tests, distTest{
name: "api",
heading: "API check",
fn: func(dt *distTest) error {
if t.compileOnly {
t.addCmd(dt, "src", "go", "build", "-o", os.DevNull, filepath.Join(goroot, "src/cmd/api/run.go"))
return nil
}
t.addCmd(dt, "src", "go", "run", filepath.Join(goroot, "src/cmd/api/run.go"))
return nil
},
})
}
// Ensure that the toolchain can bootstrap itself.
// This test adds another ~45s to all.bash if run sequentially, so run it only on the builders.
if os.Getenv("GO_BUILDER_NAME") != "" && goos != "android" && !t.iOS() {
t.registerHostTest("reboot", "../misc/reboot", "misc/reboot", ".")
}
}
// isRegisteredTestName reports whether a test named testName has already
// been registered.
func (t *tester) isRegisteredTestName(testName string) bool {
for _, tt := range t.tests {
if tt.name == testName {
return true
}
}
return false
}
func (t *tester) registerTest1(seq bool, name, dirBanner string, cmdline ...interface{}) {
bin, args := flattenCmdline(cmdline)
if bin == "time" && !t.haveTime {
bin, args = args[0], args[1:]
}
if t.isRegisteredTestName(name) {
panic("duplicate registered test name " + name)
}
t.tests = append(t.tests, distTest{
name: name,
heading: dirBanner,
fn: func(dt *distTest) error {
if seq {
t.runPending(dt)
timelog("start", name)
defer timelog("end", name)
return t.dirCmd(filepath.Join(goroot, "src", dirBanner), bin, args).Run()
}
t.addCmd(dt, filepath.Join(goroot, "src", dirBanner), bin, args)
return nil
},
})
}
func (t *tester) registerTest(name, dirBanner string, cmdline ...interface{}) {
t.registerTest1(false, name, dirBanner, cmdline...)
}
func (t *tester) registerSeqTest(name, dirBanner string, cmdline ...interface{}) {
t.registerTest1(true, name, dirBanner, cmdline...)
}
func (t *tester) bgDirCmd(dir, bin string, args ...string) *exec.Cmd {
cmd := exec.Command(bin, args...)
if filepath.IsAbs(dir) {
cmd.Dir = dir
} else {
cmd.Dir = filepath.Join(goroot, dir)
}
return cmd
}
func (t *tester) dirCmd(dir string, cmdline ...interface{}) *exec.Cmd {
bin, args := flattenCmdline(cmdline)
cmd := t.bgDirCmd(dir, bin, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if vflag > 1 {
errprintf("%s\n", strings.Join(cmd.Args, " "))
}
return cmd
}
// flattenCmdline flattens a mixture of string and []string as single list
// and then interprets it as a command line: first element is binary, then args.
func flattenCmdline(cmdline []interface{}) (bin string, args []string) {
var list []string
for _, x := range cmdline {
switch x := x.(type) {
case string:
list = append(list, x)
case []string:
list = append(list, x...)
default:
panic("invalid addCmd argument type: " + reflect.TypeOf(x).String())
}
}
// The go command is too picky about duplicated flags.
// Drop all but the last of the allowed duplicated flags.
drop := make([]bool, len(list))
have := map[string]int{}
for i := 1; i < len(list); i++ {
j := strings.Index(list[i], "=")
if j < 0 {
continue
}
flag := list[i][:j]
switch flag {
case "-run", "-tags":
if have[flag] != 0 {
drop[have[flag]] = true
}
have[flag] = i
}
}
out := list[:0]
for i, x := range list {
if !drop[i] {
out = append(out, x)
}
}
list = out
return list[0], list[1:]
}
func (t *tester) addCmd(dt *distTest, dir string, cmdline ...interface{}) *exec.Cmd {
bin, args := flattenCmdline(cmdline)
w := &work{
dt: dt,
cmd: t.bgDirCmd(dir, bin, args...),
}
t.worklist = append(t.worklist, w)
return w.cmd
}
func (t *tester) iOS() bool {
return goos == "darwin" && (goarch == "arm" || goarch == "arm64")
}
func (t *tester) out(v string) {
if t.banner == "" {
return
}
fmt.Println("\n" + t.banner + v)
}
func (t *tester) extLink() bool {
pair := gohostos + "-" + goarch
switch pair {
case "aix-ppc64",
"android-arm",
"darwin-386", "darwin-amd64", "darwin-arm", "darwin-arm64",
"dragonfly-amd64",
"freebsd-386", "freebsd-amd64", "freebsd-arm",
"linux-386", "linux-amd64", "linux-arm", "linux-arm64", "linux-ppc64le", "linux-mips64", "linux-mips64le", "linux-mips", "linux-mipsle", "linux-s390x",
"netbsd-386", "netbsd-amd64",
"openbsd-386", "openbsd-amd64",
"windows-386", "windows-amd64":
return true
}
return false
}
func (t *tester) internalLink() bool {
if gohostos == "dragonfly" {
// linkmode=internal fails on dragonfly since errno is a TLS relocation.
return false
}
if gohostarch == "ppc64le" {
// linkmode=internal fails on ppc64le because cmd/link doesn't
// handle the TOC correctly (issue 15409).
return false
}
if goos == "android" {
return false
}
if goos == "darwin" && (goarch == "arm" || goarch == "arm64") {
return false
}
// Internally linking cgo is incomplete on some architectures.
// https://golang.org/issue/10373
// https://golang.org/issue/14449
if goarch == "mips64" || goarch == "mips64le" || goarch == "mips" || goarch == "mipsle" {
return false
}
if goos == "aix" {
// linkmode=internal isn't supported.
return false
}
return true
}
func (t *tester) supportedBuildmode(mode string) bool {
pair := goos + "-" + goarch
switch mode {
case "c-archive":
if !t.extLink() {
return false
}
switch pair {
case "aix-ppc64",
"darwin-386", "darwin-amd64", "darwin-arm", "darwin-arm64",
"linux-amd64", "linux-386", "linux-ppc64le", "linux-s390x",
"freebsd-amd64",
"windows-amd64", "windows-386":
return true
}
return false
case "c-shared":
switch pair {
case "linux-386", "linux-amd64", "linux-arm", "linux-arm64", "linux-ppc64le", "linux-s390x",
"darwin-amd64", "darwin-386",
"freebsd-amd64",
"android-arm", "android-arm64", "android-386",
"windows-amd64", "windows-386":
return true
}
return false
case "shared":
switch pair {
case "linux-386", "linux-amd64", "linux-arm", "linux-arm64", "linux-ppc64le", "linux-s390x":
return true
}
return false
case "plugin":
// linux-arm64 is missing because it causes the external linker
// to crash, see https://golang.org/issue/17138
switch pair {
case "linux-386", "linux-amd64", "linux-arm", "linux-s390x", "linux-ppc64le":
return true
case "darwin-amd64":
return true
case "freebsd-amd64":
return true
}
return false
case "pie":
switch pair {
case "aix/ppc64",
"linux-386", "linux-amd64", "linux-arm", "linux-arm64", "linux-ppc64le", "linux-s390x",
"android-amd64", "android-arm", "android-arm64", "android-386":
return true
case "darwin-amd64":
return true
}
return false
default:
fatalf("internal error: unknown buildmode %s", mode)
return false
}
}
func (t *tester) registerHostTest(name, heading, dir, pkg string) {
t.tests = append(t.tests, distTest{
name: name,
heading: heading,
fn: func(dt *distTest) error {
t.runPending(dt)
timelog("start", name)
defer timelog("end", name)
return t.runHostTest(dir, pkg)
},
})
}
func (t *tester) runHostTest(dir, pkg string) error {
out, err := exec.Command("go", "env", "GOEXE", "GOTMPDIR").Output()
if err != nil {
return err
}
parts := strings.Split(string(out), "\n")
if len(parts) < 2 {
return fmt.Errorf("'go env GOEXE GOTMPDIR' output contains <2 lines")
}
GOEXE := strings.TrimSpace(parts[0])
GOTMPDIR := strings.TrimSpace(parts[1])
f, err := ioutil.TempFile(GOTMPDIR, "test.test-*"+GOEXE)
if err != nil {
return err
}
f.Close()
defer os.Remove(f.Name())
cmd := t.dirCmd(dir, t.goTest(), "-c", "-o", f.Name(), pkg)
cmd.Env = append(os.Environ(), "GOARCH="+gohostarch, "GOOS="+gohostos)
if err := cmd.Run(); err != nil {
return err
}
return t.dirCmd(dir, f.Name(), "-test.short").Run()
}
func (t *tester) cgoTest(dt *distTest) error {
cmd := t.addCmd(dt, "misc/cgo/test", t.goTest())
cmd.Env = append(os.Environ(), "GOFLAGS=-ldflags=-linkmode=auto")
if t.internalLink() {
cmd := t.addCmd(dt, "misc/cgo/test", t.goTest(), "-tags=internal")
cmd.Env = append(os.Environ(), "GOFLAGS=-ldflags=-linkmode=internal")
}
pair := gohostos + "-" + goarch
switch pair {
case "darwin-386", "darwin-amd64",
"openbsd-386", "openbsd-amd64",
"windows-386", "windows-amd64":
// test linkmode=external, but __thread not supported, so skip testtls.
if !t.extLink() {
break
}
cmd := t.addCmd(dt, "misc/cgo/test", t.goTest())
cmd.Env = append(os.Environ(), "GOFLAGS=-ldflags=-linkmode=external")
cmd = t.addCmd(dt, "misc/cgo/test", t.goTest(), "-ldflags", "-linkmode=external -s")
case "aix-ppc64",
"android-arm",
"dragonfly-amd64",
"freebsd-386", "freebsd-amd64", "freebsd-arm",
"linux-386", "linux-amd64", "linux-arm", "linux-ppc64le", "linux-s390x",
"netbsd-386", "netbsd-amd64", "linux-arm64":
cmd := t.addCmd(dt, "misc/cgo/test", t.goTest())
cmd.Env = append(os.Environ(), "GOFLAGS=-ldflags=-linkmode=external")
// A -g argument in CGO_CFLAGS should not affect how the test runs.
cmd.Env = append(cmd.Env, "CGO_CFLAGS=-g0")
t.addCmd(dt, "misc/cgo/testtls", t.goTest(), "-ldflags", "-linkmode=auto")
t.addCmd(dt, "misc/cgo/testtls", t.goTest(), "-ldflags", "-linkmode=external")
switch pair {
case "aix-ppc64", "netbsd-386", "netbsd-amd64":
// no static linking
case "freebsd-arm":
// -fPIC compiled tls code will use __tls_get_addr instead
// of __aeabi_read_tp, however, on FreeBSD/ARM, __tls_get_addr
// is implemented in rtld-elf, so -fPIC isn't compatible with
// static linking on FreeBSD/ARM with clang. (cgo depends on
// -fPIC fundamentally.)
default:
cmd := t.dirCmd("misc/cgo/test",
compilerEnvLookup(defaultcc, goos, goarch), "-xc", "-o", "/dev/null", "-static", "-")
cmd.Stdin = strings.NewReader("int main() {}")
if err := cmd.Run(); err != nil {
fmt.Println("No support for static linking found (lacks libc.a?), skip cgo static linking test.")
} else {
if goos != "android" {
t.addCmd(dt, "misc/cgo/testtls", t.goTest(), "-ldflags", `-linkmode=external -extldflags "-static -pthread"`)
}
t.addCmd(dt, "misc/cgo/nocgo", t.goTest())
t.addCmd(dt, "misc/cgo/nocgo", t.goTest(), "-ldflags", `-linkmode=external`)
if goos != "android" {
t.addCmd(dt, "misc/cgo/nocgo", t.goTest(), "-ldflags", `-linkmode=external -extldflags "-static -pthread"`)
t.addCmd(dt, "misc/cgo/test", t.goTest(), "-tags=static", "-ldflags", `-linkmode=external -extldflags "-static -pthread"`)
// -static in CGO_LDFLAGS triggers a different code path
// than -static in -extldflags, so test both.
// See issue #16651.
cmd := t.addCmd(dt, "misc/cgo/test", t.goTest(), "-tags=static")
cmd.Env = append(os.Environ(), "CGO_LDFLAGS=-static -pthread")
}
}
if t.supportedBuildmode("pie") {
t.addCmd(dt, "misc/cgo/test", t.goTest(), "-buildmode=pie")
t.addCmd(dt, "misc/cgo/testtls", t.goTest(), "-buildmode=pie")
t.addCmd(dt, "misc/cgo/nocgo", t.goTest(), "-buildmode=pie")
}
}
}
return nil
}
// run pending test commands, in parallel, emitting headers as appropriate.
// When finished, emit header for nextTest, which is going to run after the
// pending commands are done (and runPending returns).
// A test should call runPending if it wants to make sure that it is not
// running in parallel with earlier tests, or if it has some other reason
// for needing the earlier tests to be done.
func (t *tester) runPending(nextTest *distTest) {
checkNotStale("go", "std")
worklist := t.worklist
t.worklist = nil
for _, w := range worklist {
w.start = make(chan bool)
w.end = make(chan bool)
go func(w *work) {
if !<-w.start {
timelog("skip", w.dt.name)
w.out = []byte(fmt.Sprintf("skipped due to earlier error\n"))
} else {
timelog("start", w.dt.name)
w.out, w.err = w.cmd.CombinedOutput()
if w.err != nil {
if isUnsupportedVMASize(w) {
timelog("skip", w.dt.name)
w.out = []byte(fmt.Sprintf("skipped due to unsupported VMA\n"))
w.err = nil
}
}
}
timelog("end", w.dt.name)
w.end <- true
}(w)
}
started := 0
ended := 0
var last *distTest
for ended < len(worklist) {
for started < len(worklist) && started-ended < maxbg {
w := worklist[started]
started++
w.start <- !t.failed || t.keepGoing
}
w := worklist[ended]
dt := w.dt
if dt.heading != "" && t.lastHeading != dt.heading {
t.lastHeading = dt.heading
t.out(dt.heading)
}
if dt != last {
// Assumes all the entries for a single dt are in one worklist.
last = w.dt
if vflag > 0 {
fmt.Printf("# go tool dist test -run=^%s$\n", dt.name)
}
}
if vflag > 1 {
errprintf("%s\n", strings.Join(w.cmd.Args, " "))
}
ended++
<-w.end
os.Stdout.Write(w.out)
if w.err != nil {
log.Printf("Failed: %v", w.err)
t.failed = true
}
checkNotStale("go", "std")
}
if t.failed && !t.keepGoing {
fatalf("FAILED")
}
if dt := nextTest; dt != nil {
if dt.heading != "" && t.lastHeading != dt.heading {
t.lastHeading = dt.heading
t.out(dt.heading)
}
if vflag > 0 {
fmt.Printf("# go tool dist test -run=^%s$\n", dt.name)
}
}
}
func (t *tester) hasBash() bool {
switch gohostos {
case "windows", "plan9":
return false
}
return true
}
func (t *tester) hasCxx() bool {
cxx, _ := exec.LookPath(compilerEnvLookup(defaultcxx, goos, goarch))
return cxx != ""
}
func (t *tester) hasSwig() bool {
swig, err := exec.LookPath("swig")
if err != nil {
return false
}
// Check that swig was installed with Go support by checking
// that a go directory exists inside the swiglib directory.
// See https://golang.org/issue/23469.
output, err := exec.Command(swig, "-go", "-swiglib").Output()
if err != nil {
return false
}
swigDir := strings.TrimSpace(string(output))
_, err = os.Stat(filepath.Join(swigDir, "go"))
if err != nil {
return false
}
// Check that swig has a new enough version.
// See https://golang.org/issue/22858.
out, err := exec.Command(swig, "-version").CombinedOutput()
if err != nil {
return false
}
re := regexp.MustCompile(`[vV]ersion +([\d]+)([.][\d]+)?([.][\d]+)?`)
matches := re.FindSubmatch(out)
if matches == nil {
// Can't find version number; hope for the best.
return true
}
major, err := strconv.Atoi(string(matches[1]))
if err != nil {
// Can't find version number; hope for the best.
return true
}
if major < 3 {
return false
}
if major > 3 {
// 4.0 or later
return true
}
// We have SWIG version 3.x.
if len(matches[2]) > 0 {
minor, err := strconv.Atoi(string(matches[2][1:]))
if err != nil {
return true
}
if minor > 0 {
// 3.1 or later
return true
}
}
// We have SWIG version 3.0.x.
if len(matches[3]) > 0 {
patch, err := strconv.Atoi(string(matches[3][1:]))
if err != nil {
return true
}
if patch < 6 {
// Before 3.0.6.
return false
}
}
return true
}
func (t *tester) raceDetectorSupported() bool {
if gohostos != goos {
return false
}
if !t.cgoEnabled {
return false
}
if !raceDetectorSupported(goos, goarch) {
return false
}
// The race detector doesn't work on Alpine Linux:
// golang.org/issue/14481
if isAlpineLinux() {
return false
}
// NetBSD support is unfinished.
// golang.org/issue/26403
if goos == "netbsd" {
return false
}
return true
}
func isAlpineLinux() bool {
if runtime.GOOS != "linux" {
return false
}
fi, err := os.Lstat("/etc/alpine-release")
return err == nil && fi.Mode().IsRegular()
}
func (t *tester) runFlag(rx string) string {
if t.compileOnly {
return "-run=^$"
}
return "-run=" + rx
}
func (t *tester) raceTest(dt *distTest) error {
t.addCmd(dt, "src", t.goTest(), "-race", "-i", "runtime/race", "flag", "os", "os/exec")
t.addCmd(dt, "src", t.goTest(), "-race", t.runFlag("Output"), "runtime/race")
t.addCmd(dt, "src", t.goTest(), "-race", t.runFlag("TestParse|TestEcho|TestStdinCloseRace|TestClosedPipeRace|TestTypeRace|TestFdRace|TestFdReadRace|TestFileCloseRace"), "flag", "net", "os", "os/exec", "encoding/gob")
// We don't want the following line, because it
// slows down all.bash (by 10 seconds on my laptop).
// The race builder should catch any error here, but doesn't.
// TODO(iant): Figure out how to catch this.
// t.addCmd(dt, "src", t.goTest(), "-race", "-run=TestParallelTest", "cmd/go")
if t.cgoEnabled {
// Building misc/cgo/test takes a long time.
// There are already cgo-enabled packages being tested with the race detector.
// We shouldn't need to redo all of misc/cgo/test too.
// The race buildler will take care of this.
// cmd := t.addCmd(dt, "misc/cgo/test", t.goTest(), "-race")
// cmd.Env = append(os.Environ(), "GOTRACEBACK=2")
}
if t.extLink() {
// Test with external linking; see issue 9133.
t.addCmd(dt, "src", t.goTest(), "-race", "-ldflags=-linkmode=external", t.runFlag("TestParse|TestEcho|TestStdinCloseRace"), "flag", "os/exec")
}
return nil
}
var runtest struct {
sync.Once
exe string
err error
}
func (t *tester) testDirTest(dt *distTest, shard, shards int) error {
runtest.Do(func() {
const exe = "runtest.exe" // named exe for Windows, but harmless elsewhere
cmd := t.dirCmd("test", "go", "build", "-o", exe, "run.go")
cmd.Env = append(os.Environ(), "GOOS="+gohostos, "GOARCH="+gohostarch)
runtest.exe = filepath.Join(cmd.Dir, exe)
if err := cmd.Run(); err != nil {
runtest.err = err
return
}
xatexit(func() {
os.Remove(runtest.exe)
})
})
if runtest.err != nil {
return runtest.err
}
if t.compileOnly {
return nil
}
t.addCmd(dt, "test", runtest.exe,
fmt.Sprintf("--shard=%d", shard),
fmt.Sprintf("--shards=%d", shards),
)
return nil
}
// cgoPackages is the standard packages that use cgo.
var cgoPackages = []string{
"crypto/x509",
"net",
"os/user",
}
var funcBenchmark = []byte("\nfunc Benchmark")
// packageHasBenchmarks reports whether pkg has benchmarks.
// On any error, it conservatively returns true.
//
// This exists just to eliminate work on the builders, since compiling
// a test in race mode just to discover it has no benchmarks costs a
// second or two per package, and this function returns false for
// about 100 packages.
func (t *tester) packageHasBenchmarks(pkg string) bool {
pkgDir := filepath.Join(goroot, "src", pkg)
d, err := os.Open(pkgDir)
if err != nil {
return true // conservatively
}
defer d.Close()
names, err := d.Readdirnames(-1)
if err != nil {
return true // conservatively
}
for _, name := range names {
if !strings.HasSuffix(name, "_test.go") {
continue
}
slurp, err := ioutil.ReadFile(filepath.Join(pkgDir, name))
if err != nil {
return true // conservatively
}
if bytes.Contains(slurp, funcBenchmark) {
return true
}
}
return false
}
// makeGOROOTUnwritable makes all $GOROOT files & directories non-writable to
// check that no tests accidentally write to $GOROOT.
func (t *tester) makeGOROOTUnwritable() (undo func()) {
dir := os.Getenv("GOROOT")
if dir == "" {
panic("GOROOT not set")
}
type pathMode struct {
path string
mode os.FileMode
}
var dirs []pathMode // in lexical order
undo = func() {
for i := range dirs {
os.Chmod(dirs[i].path, dirs[i].mode) // best effort
}
}
gocache := os.Getenv("GOCACHE")
if gocache == "" {
panic("GOCACHE not set")
}
gocacheSubdir, _ := filepath.Rel(dir, gocache)
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if suffix := strings.TrimPrefix(path, dir+string(filepath.Separator)); suffix != "" {
if suffix == gocacheSubdir {
// Leave GOCACHE writable: we may need to write test binaries into it.
return filepath.SkipDir
}
if suffix == ".git" {
// Leave Git metadata in whatever state it was in. It may contain a lot
// of files, and it is highly unlikely that a test will try to modify
// anything within that directory.
return filepath.SkipDir
}
}
if err == nil {
mode := info.Mode()
if mode&0222 != 0 && (mode.IsDir() || mode.IsRegular()) {
dirs = append(dirs, pathMode{path, mode})
}
}
return nil
})
// Run over list backward to chmod children before parents.
for i := len(dirs) - 1; i >= 0; i-- {
err := os.Chmod(dirs[i].path, dirs[i].mode&^0222)
if err != nil {
dirs = dirs[i:] // Only undo what we did so far.
undo()
fatalf("failed to make GOROOT read-only: %v", err)
}
}
return undo
}
// shouldUsePrecompiledStdTest reports whether "dist test" should use
// a pre-compiled go test binary on disk rather than running "go test"
// and compiling it again. This is used by our slow qemu-based builder
// that do full processor emulation where we cross-compile the
// make.bash step as well as pre-compile each std test binary.
//
// This only reports true if dist is run with an single go_test:foo
// argument (as the build coordinator does with our slow qemu-based
// builders), we're in a builder environment ("GO_BUILDER_NAME" is set),
// and the pre-built test binary exists.
func (t *tester) shouldUsePrecompiledStdTest() bool {
bin := t.prebuiltGoPackageTestBinary()
if bin == "" {
return false
}
_, err := os.Stat(bin)
return err == nil
}
func (t *tester) shouldTestCmd() bool {
if t.race {
return false
}
if goos == "js" && goarch == "wasm" {
// Issues 25911, 35220
return false
}
return true
}
// prebuiltGoPackageTestBinary returns the path where we'd expect
// the pre-built go test binary to be on disk when dist test is run with
// a single argument.
// It returns an empty string if a pre-built binary should not be used.
func (t *tester) prebuiltGoPackageTestBinary() string {
if len(stdMatches) != 1 || t.race || t.compileOnly || os.Getenv("GO_BUILDER_NAME") == "" {
return ""
}
pkg := stdMatches[0]
return filepath.Join(os.Getenv("GOROOT"), "src", pkg, path.Base(pkg)+".test")
}
// runPrecompiledStdTest runs the pre-compiled standard library package test binary.
// See shouldUsePrecompiledStdTest above; it must return true for this to be called.
func (t *tester) runPrecompiledStdTest(timeout time.Duration) error {
bin := t.prebuiltGoPackageTestBinary()
fmt.Fprintf(os.Stderr, "# %s: using pre-built %s...\n", stdMatches[0], bin)
cmd := exec.Command(bin, "-test.short", "-test.timeout="+timeout.String())
cmd.Dir = filepath.Dir(bin)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return err
}
// And start a timer to kill the process if it doesn't kill
// itself in the prescribed timeout.
const backupKillFactor = 1.05 // add 5%
timer := time.AfterFunc(time.Duration(float64(timeout)*backupKillFactor), func() {
fmt.Fprintf(os.Stderr, "# %s: timeout running %s; killing...\n", stdMatches[0], bin)
cmd.Process.Kill()
})
defer timer.Stop()
return cmd.Wait()
}
// raceDetectorSupported is a copy of the function
// cmd/internal/sys.RaceDetectorSupported, which can't be used here
// because cmd/dist has to be buildable by Go 1.4.
// The race detector only supports 48-bit VMA on arm64. But we don't have
// a good solution to check VMA size(See https://golang.org/issue/29948)
// raceDetectorSupported will always return true for arm64. But race
// detector tests may abort on non 48-bit VMA configuration, the tests
// will be marked as "skipped" in this case.
func raceDetectorSupported(goos, goarch string) bool {
switch goos {
case "linux":
return goarch == "amd64" || goarch == "ppc64le" || goarch == "arm64"
case "darwin", "freebsd", "netbsd", "windows":
return goarch == "amd64"
default:
return false
}
}
// mSanSupported is a copy of the function cmd/internal/sys.MSanSupported,
// which can't be used here because cmd/dist has to be buildable by Go 1.4.
func mSanSupported(goos, goarch string) bool {
switch goos {
case "linux":
return goarch == "amd64" || goarch == "arm64"
default:
return false
}
}
// isUnsupportedVMASize reports whether the failure is caused by an unsupported
// VMA for the race detector (for example, running the race detector on an
// arm64 machine configured with 39-bit VMA)
func isUnsupportedVMASize(w *work) bool {
unsupportedVMA := []byte("unsupported VMA range")
return w.dt.name == "race" && bytes.Contains(w.out, unsupportedVMA)
}
|
[
"\"GO_GCFLAGS\"",
"\"GOTESTONLY\"",
"\"PATH\"",
"\"GO_BUILDER_NAME\"",
"\"GO_TEST_TIMEOUT_SCALE\"",
"\"GOROOT_FINAL\"",
"\"GO_BUILDER_NAME\"",
"\"GO_TEST_SHORT\"",
"\"GOROOT\"",
"\"GO_BUILDER_NAME\"",
"\"FC\"",
"\"GO_BUILDER_NAME\"",
"\"GO_BUILDER_NAME\"",
"\"GO_TEST_SHARDS\"",
"\"GO_BUILDER_NAME\"",
"\"GOROOT\"",
"\"GOCACHE\"",
"\"GO_BUILDER_NAME\"",
"\"GOROOT\""
] |
[] |
[
"GO_GCFLAGS",
"FC",
"GOTESTONLY",
"GO_BUILDER_NAME",
"GO_TEST_TIMEOUT_SCALE",
"GOROOT_FINAL",
"GO_TEST_SHORT",
"GOROOT",
"GOCACHE",
"PATH",
"GO_TEST_SHARDS"
] |
[]
|
["GO_GCFLAGS", "FC", "GOTESTONLY", "GO_BUILDER_NAME", "GO_TEST_TIMEOUT_SCALE", "GOROOT_FINAL", "GO_TEST_SHORT", "GOROOT", "GOCACHE", "PATH", "GO_TEST_SHARDS"]
|
go
| 11 | 0 | |
tests/feature_test.go
|
// +build acceptance
package tests
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"math/rand"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"testing"
"text/template"
"time"
expect "github.com/Netflix/go-expect"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/cloudformation/cloudformationiface"
"github.com/cucumber/godog"
"github.com/cucumber/godog/colors"
"github.com/cucumber/messages-go/v10"
assembly "github.com/molecule-man/stack-assembly"
saaws "github.com/molecule-man/stack-assembly/aws"
"github.com/molecule-man/stack-assembly/aws/mock"
"github.com/molecule-man/stack-assembly/cli"
"github.com/molecule-man/stack-assembly/cmd/commands"
"github.com/molecule-man/stack-assembly/conf"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
yaml "gopkg.in/yaml.v3"
)
var opt = godog.Options{
Paths: []string{"."},
Output: colors.Colored(os.Stdout),
// Format: "pretty",
Format: "progress",
Concurrency: 4,
Randomize: time.Now().UTC().UnixNano(),
}
func init() {
godog.BindFlags("godog.", flag.CommandLine, &opt)
rand.Seed(time.Now().UnixNano())
}
func TestMain(m *testing.M) {
flag.Parse()
status := godog.RunWithOptions("stas", func(s *godog.Suite) {
FeatureContext(s)
}, opt)
if st := m.Run(); st > status {
status = st
}
os.Exit(status)
}
type feature struct {
ScenarioName string
ScenarioID string
testDir string
FeatureID string
LastOutput string
LastErr error
console *expect.Console
lastCmd *exec.Cmd
cancel context.CancelFunc
wg *sync.WaitGroup
cf cloudformationiface.CloudFormationAPI
fs vfs
}
func (f feature) aws() conf.AwsProv {
if os.Getenv("STAS_NO_MOCK") == "on" {
return &saaws.Provider{}
}
return mock.New(f.ScenarioName, f.FeatureID, f.ScenarioID)
}
func (f *feature) assertEgual(expected, actual interface{}, msgAndArgs ...interface{}) error {
result := assertionResult{}
assert.Equal(&result, expected, actual, msgAndArgs...)
return result.err
}
func (f *feature) fileExists(fname string, content *messages.PickleStepArgument_PickleDocString) error {
dir, _ := filepath.Split(fname)
err := f.fs.MkdirAll(dir, 0700)
if err != nil {
return err
}
c := f.replaceParameters(content.Content)
file, err := f.fs.Create(fname)
if err != nil {
return err
}
defer file.Close()
_, err = file.WriteString(c)
if err != nil {
return err
}
return file.Sync()
}
func (f *feature) iSuccessfullyRun(cmd string) error {
err := f.iRun(cmd)
if err != nil {
return err
}
if f.LastErr != nil {
return fmt.Errorf("err: %v, output:\n%s", f.LastErr, f.LastOutput)
}
return nil
}
func (f *feature) stackShouldHaveStatus(stackName, status string) error {
s := f.replaceParameters(stackName)
out, err := f.cf.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(s),
})
if err != nil {
return err
}
if aws.StringValue(out.Stacks[0].StackStatus) != status {
return fmt.Errorf("stack status is %s", aws.StringValue(out.Stacks[0].StackStatus))
}
return nil
}
func (f *feature) stackShouldNotExist(stackName string) error {
s := f.replaceParameters(stackName)
_, err := f.cf.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(s),
})
if err == nil {
return fmt.Errorf("stack %s is not supposed to exist", s)
}
if !strings.Contains(err.Error(), "does not exist") {
return err
}
return nil
}
func (f *feature) iModifyFile(fname string, content *messages.PickleStepArgument_PickleDocString) error {
return f.fileExists(fname, content)
}
func (f *feature) iRun(cmd string) error {
buf := bytes.NewBuffer([]byte{})
console := &cli.CLI{
Reader: buf,
Writer: buf,
Errorer: buf,
}
c := commands.Commands{
SA: assembly.New(console),
Cli: console,
CfgLoader: conf.NewLoader(f.fs, f.aws()),
}
c.AWSCommandsCfg.SA = assembly.New(&cli.CLI{
Reader: buf,
Writer: ioutil.Discard,
Errorer: ioutil.Discard,
})
root := c.RootCmd()
root.SetArgs(strings.Split(f.replaceParameters(cmd), " "))
root.SetOutput(buf)
err := root.Execute()
f.LastOutput = buf.String()
f.LastErr = err
return nil
}
func (f *feature) exitCodeShouldNotBeZero() error {
if f.LastErr == nil {
return fmt.Errorf("program returned zero exit code. Programs output: \n%s", f.LastOutput)
}
return nil
}
func (f *feature) outputShouldContain(s *messages.PickleStepArgument_PickleDocString) error {
expected := f.replaceParameters(s.Content)
if !strings.Contains(f.LastOutput, expected) {
return fmt.Errorf(
"output doesn't contain searched string:\n%s\nActual output:\n%s",
expected,
f.LastOutput)
}
return nil
}
func (f *feature) outputShouldBeExactly(s *messages.PickleStepArgument_PickleDocString) error {
if strings.TrimSpace(f.LastOutput) != strings.TrimSpace(f.replaceParameters(s.Content)) {
return fmt.Errorf("output isn't equal to expected string. Output:\n%s", f.LastOutput)
}
return nil
}
func (f *feature) nodeInJsonOutputShouldBe(nodePath string, expectedContent *messages.PickleStepArgument_PickleDocString) error {
var expected interface{}
c := f.replaceParameters(expectedContent.Content)
err := json.Unmarshal([]byte(c), &expected)
if err != nil {
return err
}
var actual interface{}
c = f.replaceParameters(f.LastOutput)
err = json.Unmarshal([]byte(c), &actual)
if err != nil {
return fmt.Errorf("err: %s, output:\n%s", err, f.LastOutput)
}
for _, key := range strings.Split(nodePath, ".") {
if key == "" {
continue
}
casted, ok := actual.(map[string]interface{})
if !ok {
return fmt.Errorf("not able to find key %s in node (which is not map):\n%#v", key, actual)
}
node, ok := casted[key]
if !ok {
return fmt.Errorf("not able to find key %s in node:\n%s", key, casted)
}
actual = node
}
return f.assertEgual(expected, actual)
}
func (f *feature) thereShouldBeStackThatMatches(stackName string, expectedContent *messages.PickleStepArgument_PickleDocString) error {
stackName = f.replaceParameters(stackName)
out, err := f.cf.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(stackName),
})
if err != nil {
return err
}
actualStackData := out.Stacks[0]
expectedStackData := struct {
StackStatus string
Resources map[string]string
Tags map[string]string
}{}
c := f.replaceParameters(expectedContent.Content)
err = yaml.Unmarshal([]byte(c), &expectedStackData)
if err != nil {
return err
}
if expectedStackData.StackStatus != "" {
actualStatus := aws.StringValue(actualStackData.StackStatus)
if actualStatus != expectedStackData.StackStatus {
return fmt.Errorf("status %s doesn't match status %s of stack %s", expectedStackData.StackStatus, actualStatus, stackName)
}
}
for expectedTagKey, expectedTagValue := range expectedStackData.Tags {
actualTagValue := f.tagValue(actualStackData, expectedTagKey)
if actualTagValue == "" {
return fmt.Errorf("tag with key %s is not found in stack %s", expectedTagKey, stackName)
}
if actualTagValue != expectedTagValue {
return fmt.Errorf("tag with key %s is expected to have value %s in stack %s. Actual value: %s", expectedTagKey, expectedTagValue, stackName, actualTagValue)
}
}
for expectedResKey, expectedResValue := range expectedStackData.Resources {
actualResource, err := f.cf.DescribeStackResource(&cloudformation.DescribeStackResourceInput{
StackName: aws.String(stackName),
LogicalResourceId: aws.String(expectedResKey),
})
if err != nil {
return err
}
s := strings.Split(aws.StringValue(actualResource.StackResourceDetail.PhysicalResourceId), ":")
actualResValue := s[len(s)-1]
if actualResValue != expectedResValue {
return fmt.Errorf("resource %s is expected to have value %s. Actual value: %s", expectedResKey, expectedResValue, actualResValue)
}
}
return nil
}
func (f *feature) iLaunched(cmdInstruction string) error {
c, err := expect.NewConsole(expect.WithDefaultTimeout(15 * time.Second))
if err != nil {
return err
}
cli := &cli.CLI{
Reader: c.Tty(),
Writer: c.Tty(),
Errorer: c.Tty(),
}
co := commands.Commands{
SA: assembly.New(cli),
Cli: cli,
CfgLoader: conf.NewLoader(f.fs, f.aws()),
}
co.AWSCommandsCfg.SA = co.SA
root := co.RootCmd()
root.SetArgs(strings.Split(f.replaceParameters(cmdInstruction), " "))
root.SetOutput(c.Tty())
f.wg = &sync.WaitGroup{}
f.wg.Add(1)
go func() {
f.LastErr = root.Execute()
f.wg.Done()
}()
f.console = c
return nil
}
func (f *feature) terminalShows(s *messages.PickleStepArgument_PickleDocString) error {
lines := strings.Split(f.replaceParameters(s.Content), "\n")
for _, l := range lines {
o, err := f.console.ExpectString(l)
if err != nil {
return fmt.Errorf("error: %v, output:\n%s", err, o)
}
}
return nil
}
func (f *feature) errorContains(s *messages.PickleStepArgument_PickleDocString) error {
str := f.replaceParameters(s.Content)
if !strings.Contains(f.LastErr.Error(), str) {
return fmt.Errorf("error %v doesn't contain %s", f.LastErr, str)
}
return nil
}
func (f *feature) iEnter(s string) error {
_, err := f.console.SendLine(s)
return err
}
func (f *feature) launchedProgramShouldExitWithZeroStatus() error {
if err := f.waitLaunched(); err != nil {
return err
}
return f.LastErr
}
func (f *feature) waitLaunched() error {
defer f.console.Close()
c := make(chan struct{})
go func() {
defer close(c)
f.wg.Wait()
}()
select {
case <-c:
return nil
case <-time.After(20 * time.Second):
return fmt.Errorf("test %s timed out", f.ScenarioID)
}
}
func (f *feature) launchedProgramShouldExitWithNonZeroStatus() error {
if err := f.waitLaunched(); err != nil {
return err
}
if f.LastErr == nil {
return errors.New("program returned zero exit code")
}
return nil
}
func (f *feature) tagValue(stack *cloudformation.Stack, tagKey string) string {
for _, t := range stack.Tags {
if aws.StringValue(t.Key) == tagKey {
return aws.StringValue(t.Value)
}
}
return ""
}
func (f *feature) replaceParameters(s string) string {
s = strings.ReplaceAll(s, "%scenarioid%", f.ScenarioID)
s = strings.ReplaceAll(s, "%featureid%", f.FeatureID)
s = strings.ReplaceAll(s, "%aws_profile%", os.Getenv("AWS_PROFILE"))
s = strings.ReplaceAll(s, "%testdir%", f.testDir)
s = strings.ReplaceAll(s, "%longstring%", strings.Repeat("s", 51200))
t, err := template.New(s).Funcs(template.FuncMap{
"StackInfo": func(stackName string) (*cloudformation.Stack, error) {
out, err := f.cf.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(stackName),
})
if err != nil {
return nil, err
}
return out.Stacks[0], nil
},
}).Delims("{%", "%}").Parse(s)
if err != nil {
panic(err)
}
var buff bytes.Buffer
if err := t.Execute(&buff, f); err != nil {
panic(err)
}
return buff.String()
}
func (f *feature) fileShouldContainExactly(fname string, content *messages.PickleStepArgument_PickleDocString) error {
c := f.replaceParameters(content.Content)
file, err := f.fs.Open(fname)
if err != nil {
return err
}
buf, err := ioutil.ReadAll(file)
if err != nil {
return err
}
if strings.TrimSpace(string(buf)) != strings.TrimSpace(c) {
return fmt.Errorf("file content is not equal to the expected string. File contents:\n%s", string(buf))
}
return nil
}
func FeatureContext(s *godog.Suite) {
f := feature{}
cfg := saaws.Config{}
cfg.Profile = os.Getenv("AWS_PROFILE")
s.Step(`^file "([^"]*)" exists:$`, f.fileExists)
s.Step(`^I successfully run "([^"]*)"$`, f.iSuccessfullyRun)
s.Step(`^stack "([^"]*)" should have status "([^"]*)"$`, f.stackShouldHaveStatus)
s.Step(`^stack "([^"]*)" should not exist$`, f.stackShouldNotExist)
s.Step(`^I modify file "([^"]*)":$`, f.iModifyFile)
s.Step(`^I run "([^"]*)"$`, f.iRun)
s.Step(`^exit code should not be zero$`, f.exitCodeShouldNotBeZero)
s.Step(`^output should contain:$`, f.outputShouldContain)
s.Step(`^output should be exactly:$`, f.outputShouldBeExactly)
s.Step(`^node "([^"]*)" in json output should be:$`, f.nodeInJsonOutputShouldBe)
s.Step(`^there should be stack "([^"]*)" that matches:$`, f.thereShouldBeStackThatMatches)
s.Step(`^I launched "([^"]*)"$`, f.iLaunched)
s.Step(`^terminal shows:$`, f.terminalShows)
s.Step(`^I enter "([^"]*)"$`, f.iEnter)
s.Step(`^launched program should exit with zero status$`, f.launchedProgramShouldExitWithZeroStatus)
s.Step(`^launched program should exit with non zero status$`, f.launchedProgramShouldExitWithNonZeroStatus)
s.Step(`^file "([^"]*)" should contain exactly:$`, f.fileShouldContainExactly)
s.Step(`^error contains:$`, f.errorContains)
re := regexp.MustCompile("\\W")
s.BeforeScenario(func(scenario *messages.Pickle) {
f.ScenarioName = re.ReplaceAllString(scenario.Name, "-")
f.ScenarioID = fmt.Sprintf("%.80s-%d", f.ScenarioName, rand.Int63())
f.cf = f.aws().Must(cfg).CF
f.testDir = filepath.Join(".tmp", "stas_test_"+f.ScenarioID)
f.fs = vfs{
afero.NewBasePathFs(afero.NewOsFs(), f.testDir),
}
})
s.AfterScenario(func(*messages.Pickle, error) {
f.fs.RemoveAll(".")
})
s.BeforeFeature(func(*messages.GherkinDocument) {
f.FeatureID = strconv.FormatInt(rand.Int63(), 10)
})
s.AfterFeature(func(*messages.GherkinDocument) {
if mock.IsMockEnabled() {
return
}
stacks, err := f.cf.DescribeStacks(&cloudformation.DescribeStacksInput{})
if err != nil {
panic(err)
}
for _, s := range stacks.Stacks {
if f.tagValue(s, "STAS_TEST") == f.FeatureID {
f.cf.DeleteStack(&cloudformation.DeleteStackInput{
StackName: s.StackName,
})
}
}
})
}
type assertionResult struct {
err error
}
func (a *assertionResult) Errorf(format string, args ...interface{}) {
a.err = fmt.Errorf(format, args...)
}
type vfs struct {
afero.Fs
}
func (fs vfs) Open(name string) (conf.ReadSeekCloser, error) { return fs.Fs.Open(name) }
|
[
"\"STAS_NO_MOCK\"",
"\"AWS_PROFILE\"",
"\"AWS_PROFILE\""
] |
[] |
[
"AWS_PROFILE",
"STAS_NO_MOCK"
] |
[]
|
["AWS_PROFILE", "STAS_NO_MOCK"]
|
go
| 2 | 0 | |
app/interface/main/app-channel/dao/bangumi/bangumi_test.go
|
package bangumi
import (
"context"
"flag"
"os"
"testing"
"time"
"go-common/app/interface/main/app-channel/conf"
. "github.com/smartystreets/goconvey/convey"
)
var (
d *Dao
)
func ctx() context.Context {
return context.Background()
}
func init() {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.app-svr.app-channel")
flag.Set("conf_token", "a920405f87c5bbcca15f3ffebf169c04")
flag.Set("tree_id", "7852")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
time.Sleep(time.Second)
}
func TestSeasons(t *testing.T) {
Convey("get Seasons all", t, func() {
_, err := d.Seasons(ctx(), []int64{1}, time.Now())
err = nil
So(err, ShouldBeNil)
})
}
func TestCardsInfoReply(t *testing.T) {
Convey("get CardsInfoReply all", t, func() {
_, err := d.CardsInfoReply(ctx(), []int32{1})
err = nil
So(err, ShouldBeNil)
})
}
func TestEpidsCardsInfoReply(t *testing.T) {
Convey("get EpidsCardsInfoReply all", t, func() {
_, err := d.EpidsCardsInfoReply(ctx(), []int32{1})
err = nil
So(err, ShouldBeNil)
})
}
|
[
"\"DEPLOY_ENV\""
] |
[] |
[
"DEPLOY_ENV"
] |
[]
|
["DEPLOY_ENV"]
|
go
| 1 | 0 | |
v3/integrations/nrgrpc/nrgrpc_server.go
|
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// This integration instruments grpc service calls via
// UnaryServerInterceptor and StreamServerInterceptor functions.
//
// The results of these calls are reported as errors or as informational
// messages (of levels OK, Info, Warning, or Error) based on the gRPC status
// code they return.
//
// In the simplest case, simply add interceptors as in the following example:
//
// app, _ := newrelic.NewApplication(
// newrelic.ConfigAppName("gRPC Server"),
// newrelic.ConfigLicense(os.Getenv("NEW_RELIC_LICENSE_KEY")),
// newrelic.ConfigDebugLogger(os.Stdout),
// )
// server := grpc.NewServer(
// grpc.UnaryInterceptor(nrgrpc.UnaryServerInterceptor(app)),
// grpc.StreamInterceptor(nrgrpc.StreamServerInterceptor(app)),
// )
//
// The disposition of each, in terms of how to report each of the various
// gRPC status codes, is determined by a built-in set of defaults. These
// may be overridden on a case-by-case basis using WithStatusHandler
// options to each UnaryServerInterceptor or StreamServerInterceptor
// call, or globally via the Configure function.
//
// Full example:
// https://github.com/Easypay/go-agent/blob/master/v3/integrations/nrgrpc/example/server/server.go
//
package nrgrpc
import (
"context"
"net/http"
"strings"
"github.com/Easypay/go-agent/v3/newrelic"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func startTransaction(ctx context.Context, app *newrelic.Application, fullMethod string) *newrelic.Transaction {
method := strings.TrimPrefix(fullMethod, "/")
var hdrs http.Header
if md, ok := metadata.FromIncomingContext(ctx); ok {
hdrs = make(http.Header, len(md))
for k, vs := range md {
for _, v := range vs {
hdrs.Add(k, v)
}
}
}
target := hdrs.Get(":authority")
url := getURL(method, target)
webReq := newrelic.WebRequest{
Header: hdrs,
URL: url,
Method: method,
Transport: newrelic.TransportHTTP,
}
txn := app.StartTransaction(method)
txn.SetWebRequest(webReq)
return txn
}
//
// ErrorHandler is the type of a gRPC status handler function.
// Normally the supplied set of ErrorHandler functions will suffice, but
// a custom handler may be crafted by the user and installed as a handler
// if needed.
//
type ErrorHandler func(context.Context, *newrelic.Transaction, *status.Status)
//
// Internal registry of handlers associated with various
// status codes.
//
type statusHandlerMap map[codes.Code]ErrorHandler
//
// interceptorStatusHandlerRegistry is the current default set of handlers
// used by each interceptor.
//
var interceptorStatusHandlerRegistry = statusHandlerMap{
codes.OK: OKInterceptorStatusHandler,
codes.Canceled: InfoInterceptorStatusHandler,
codes.Unknown: ErrorInterceptorStatusHandler,
codes.InvalidArgument: InfoInterceptorStatusHandler,
codes.DeadlineExceeded: WarningInterceptorStatusHandler,
codes.NotFound: InfoInterceptorStatusHandler,
codes.AlreadyExists: InfoInterceptorStatusHandler,
codes.PermissionDenied: WarningInterceptorStatusHandler,
codes.ResourceExhausted: WarningInterceptorStatusHandler,
codes.FailedPrecondition: WarningInterceptorStatusHandler,
codes.Aborted: WarningInterceptorStatusHandler,
codes.OutOfRange: WarningInterceptorStatusHandler,
codes.Unimplemented: ErrorInterceptorStatusHandler,
codes.Internal: ErrorInterceptorStatusHandler,
codes.Unavailable: WarningInterceptorStatusHandler,
codes.DataLoss: ErrorInterceptorStatusHandler,
codes.Unauthenticated: InfoInterceptorStatusHandler,
}
//
// HandlerOption is the type for options passed to the interceptor
// functions to specify gRPC status handlers.
//
type HandlerOption func(statusHandlerMap)
//
// WithStatusHandler indicates a handler function to be used to
// report the indicated gRPC status. Zero or more of these may be
// given to the Configure, StreamServiceInterceptor, or
// UnaryServiceInterceptor functions.
//
// The ErrorHandler parameter is generally one of the provided standard
// reporting functions:
// OKInterceptorStatusHandler // report the operation as successful
// ErrorInterceptorStatusHandler // report the operation as an error
// WarningInterceptorStatusHandler // report the operation as a warning
// InfoInterceptorStatusHandler // report the operation as an informational message
//
// The following reporting function should only be used if you know for sure
// you want this. It does not report the error in any way at all, but completely
// ignores it.
// IgnoreInterceptorStatusHandler // report the operation as successful
//
// Finally, if you have a custom reporting need that isn't covered by the standard
// handler functions, you can create your own handler function as
// func myHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) {
// ...
// }
// Within the function, do whatever you need to do with the txn parameter to report the
// gRPC status passed as s. If needed, the context is also passed to your function.
//
// If you wish to use your custom handler for a code such as codes.NotFound, you would
// include the parameter
// WithStatusHandler(codes.NotFound, myHandler)
// to your Configure, StreamServiceInterceptor, or UnaryServiceInterceptor function.
//
func WithStatusHandler(c codes.Code, h ErrorHandler) HandlerOption {
return func(m statusHandlerMap) {
m[c] = h
}
}
//
// Configure takes a list of WithStatusHandler options and sets them
// as the new default handlers for the specified gRPC status codes, in the same
// way as if WithStatusHandler were given to the StreamServiceInterceptor
// or UnaryServiceInterceptor functions (q.v.); however, in this case the new handlers
// become the default for any subsequent interceptors created by the above functions.
//
func Configure(options ...HandlerOption) {
for _, option := range options {
option(interceptorStatusHandlerRegistry)
}
}
//
// IgnoreInterceptorStatusHandler is our standard handler for
// gRPC statuses which we want to ignore (in terms of any gRPC-specific
// reporting on the transaction).
//
func IgnoreInterceptorStatusHandler(_ context.Context, _ *newrelic.Transaction, _ *status.Status) {}
//
// OKInterceptorStatusHandler is our standard handler for
// gRPC statuses which we want to report as being successful, as with the
// status code OK.
//
// This adds no additional attributes on the transaction other than
// the fact that it was successful.
//
func OKInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) {
txn.SetWebResponse(nil).WriteHeader(int(codes.OK))
}
//
// ErrorInterceptorStatusHandler is our standard handler for
// gRPC statuses which we want to report as being errors,
// with the relevant error messages and
// contextual information gleaned from the error value received from the RPC call.
//
func ErrorInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) {
txn.SetWebResponse(nil).WriteHeader(int(codes.OK))
txn.NoticeError(&newrelic.Error{
Message: s.Message(),
Class: "gRPC Status: " + s.Code().String(),
})
txn.AddAttribute("GrpcStatusLevel", "error")
txn.AddAttribute("GrpcStatusMessage", s.Message())
txn.AddAttribute("GrpcStatusCode", s.Code().String())
}
//
// WarningInterceptorStatusHandler is our standard handler for
// gRPC statuses which we want to report as warnings.
//
// Reports the transaction's status with attributes containing information gleaned
// from the error value returned, but does not count this as an error.
//
func WarningInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) {
txn.SetWebResponse(nil).WriteHeader(int(codes.OK))
txn.AddAttribute("GrpcStatusLevel", "warning")
txn.AddAttribute("GrpcStatusMessage", s.Message())
txn.AddAttribute("GrpcStatusCode", s.Code().String())
}
//
// InfoInterceptorStatusHandler is our standard handler for
// gRPC statuses which we want to report as informational messages only.
//
// Reports the transaction's status with attributes containing information gleaned
// from the error value returned, but does not count this as an error.
//
func InfoInterceptorStatusHandler(ctx context.Context, txn *newrelic.Transaction, s *status.Status) {
txn.SetWebResponse(nil).WriteHeader(int(codes.OK))
txn.AddAttribute("GrpcStatusLevel", "info")
txn.AddAttribute("GrpcStatusMessage", s.Message())
txn.AddAttribute("GrpcStatusCode", s.Code().String())
}
//
// DefaultInterceptorStatusHandler indicates which of our standard handlers
// will be used for any status code which is not
// explicitly assigned a handler.
//
var DefaultInterceptorStatusHandler = InfoInterceptorStatusHandler
//
// reportInterceptorStatus is the common routine for reporting any kind of interceptor.
//
func reportInterceptorStatus(ctx context.Context, txn *newrelic.Transaction, handlers statusHandlerMap, err error) {
grpcStatus := status.Convert(err)
handler, ok := handlers[grpcStatus.Code()]
if !ok {
handler = DefaultInterceptorStatusHandler
}
handler(ctx, txn, grpcStatus)
}
// UnaryServerInterceptor instruments server unary RPCs.
//
// Use this function with grpc.UnaryInterceptor and a newrelic.Application to
// create a grpc.ServerOption to pass to grpc.NewServer. This interceptor
// records each unary call with a transaction. You must use both
// UnaryServerInterceptor and StreamServerInterceptor to instrument unary and
// streaming calls.
//
// Example:
//
// app, _ := newrelic.NewApplication(
// newrelic.ConfigAppName("gRPC Server"),
// newrelic.ConfigLicense(os.Getenv("NEW_RELIC_LICENSE_KEY")),
// newrelic.ConfigDebugLogger(os.Stdout),
// )
// server := grpc.NewServer(
// grpc.UnaryInterceptor(nrgrpc.UnaryServerInterceptor(app)),
// grpc.StreamInterceptor(nrgrpc.StreamServerInterceptor(app)),
// )
//
// These interceptors add the transaction to the call context so it may be
// accessed in your method handlers using newrelic.FromContext.
//
// The nrgrpc integration has a built-in set of handlers for each gRPC status
// code encountered. Serious errors are reported as error traces à la the
// newrelic.NoticeError function, while the others are reported but not
// counted as errors.
//
// If you wish to change this behavior, you may do so at a global level for
// all intercepted functions by calling the Configure function, passing
// any number of WithStatusHandler(code, handler) functions as parameters.
//
// You can specify a custom set of handlers with each interceptor creation by adding
// WithStatusHandler calls at the end of the <type>StreamInterceptor call's parameter list,
// like so:
// grpc.UnaryInterceptor(nrgrpc.UnaryServerInterceptor(app,
// nrgrpc.WithStatusHandler(codes.OutOfRange, nrgrpc.WarningInterceptorStatusHandler),
// nrgrpc.WithStatusHandler(codes.Unimplemented, nrgrpc.InfoInterceptorStatusHandler)))
// In this case, those two handlers are used (along with the current defaults for the other status
// codes) only for that interceptor.
//
func UnaryServerInterceptor(app *newrelic.Application, options ...HandlerOption) grpc.UnaryServerInterceptor {
if app == nil {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
return handler(ctx, req)
}
}
localHandlerMap := make(statusHandlerMap)
for code, handler := range interceptorStatusHandlerRegistry {
localHandlerMap[code] = handler
}
for _, option := range options {
option(localHandlerMap)
}
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
txn := startTransaction(ctx, app, info.FullMethod)
defer txn.End()
ctx = newrelic.NewContext(ctx, txn)
resp, err = handler(ctx, req)
reportInterceptorStatus(ctx, txn, localHandlerMap, err)
return
}
}
type wrappedServerStream struct {
grpc.ServerStream
txn *newrelic.Transaction
}
func (s wrappedServerStream) Context() context.Context {
ctx := s.ServerStream.Context()
return newrelic.NewContext(ctx, s.txn)
}
func newWrappedServerStream(stream grpc.ServerStream, txn *newrelic.Transaction) grpc.ServerStream {
return wrappedServerStream{
ServerStream: stream,
txn: txn,
}
}
// StreamServerInterceptor instruments server streaming RPCs.
//
// Use this function with grpc.StreamInterceptor and a newrelic.Application to
// create a grpc.ServerOption to pass to grpc.NewServer. This interceptor
// records each streaming call with a transaction. You must use both
// UnaryServerInterceptor and StreamServerInterceptor to instrument unary and
// streaming calls.
//
// See the notes and examples for the UnaryServerInterceptor function.
//
func StreamServerInterceptor(app *newrelic.Application, options ...HandlerOption) grpc.StreamServerInterceptor {
if app == nil {
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return handler(srv, ss)
}
}
localHandlerMap := make(statusHandlerMap)
for code, handler := range interceptorStatusHandlerRegistry {
localHandlerMap[code] = handler
}
for _, option := range options {
option(localHandlerMap)
}
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
txn := startTransaction(ss.Context(), app, info.FullMethod)
defer txn.End()
err := handler(srv, newWrappedServerStream(ss, txn))
reportInterceptorStatus(ss.Context(), txn, localHandlerMap, err)
return err
}
}
|
[
"\"NEW_RELIC_LICENSE_KEY\"",
"\"NEW_RELIC_LICENSE_KEY\""
] |
[] |
[
"NEW_RELIC_LICENSE_KEY"
] |
[]
|
["NEW_RELIC_LICENSE_KEY"]
|
go
| 1 | 0 | |
data/get-sensor-data.py
|
import sys, os
import json
from requests import get
sensorID = sys.argv[1]
SupervisorToken = os.environ["SUPERVISOR_TOKEN"]
url = "http://supervisor/core/api/states/"+sensorID
headers = {
"Authorization": "Bearer "+SupervisorToken,
"content-type": "application/json",
}
ha_sensor_data_request = get(url, headers=headers)
ha_sensor = json.loads(ha_sensor_data_request.text)
# Sensor state output
print(ha_sensor["state"])
|
[] |
[] |
[
"SUPERVISOR_TOKEN"
] |
[]
|
["SUPERVISOR_TOKEN"]
|
python
| 1 | 0 | |
src/main/java/com/redhat/cajun/navy/mission/MissionMain.java
|
package com.redhat.cajun.navy.mission;
import com.redhat.cajun.navy.mission.http.MissionRestVerticle;
import com.redhat.cajun.navy.mission.message.MissionConsumerVerticle;
import com.redhat.cajun.navy.mission.message.MissionProducerVerticle;
import com.redhat.cajun.navy.mission.message.ResponderLocConsumer;
import io.vertx.config.ConfigRetriever;
import io.vertx.config.ConfigRetrieverOptions;
import io.vertx.config.ConfigStoreOptions;
import io.vertx.core.*;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.micrometer.MicrometerMetricsOptions;
import io.vertx.micrometer.VertxPrometheusOptions;
public class MissionMain extends AbstractVerticle {
private static final Logger logger = LoggerFactory.getLogger(MissionMain.class.getName());
private static ConfigRetrieverOptions selectConfigOptions(){
ConfigRetrieverOptions options = new ConfigRetrieverOptions();
if (System.getenv("KUBERNETES_NAMESPACE") != null) {
ConfigStoreOptions appStore = new ConfigStoreOptions()
.setType("file")
.setFormat("properties")
.setConfig(new JsonObject()
.put("name", System.getenv("APP_CONFIGMAP_NAME"))
.put("key", System.getenv("APP_CONFIGMAP_KEY"))
.put("path", "/deployments/config/app-config.properties"));
options.addStore(appStore);
} else {
ConfigStoreOptions props = new ConfigStoreOptions()
.setType("file")
.setFormat("properties")
.setConfig(new JsonObject().put("path", "local-app-config.properties"));
options.addStore(props);
}
return options;
}
private static void deployVerticles(Vertx vertx, JsonObject config, Future<Void> future){
Future<String> rFuture = Future.future();
Future<String> cFuture = Future.future();
Future<String> pFuture = Future.future();
DeploymentOptions options = new DeploymentOptions();
options.setConfig(config);
vertx.deployVerticle(new MissionRestVerticle(), options, rFuture.completer());
vertx.deployVerticle(new MissionConsumerVerticle(), options, cFuture.completer());
vertx.deployVerticle(new MissionProducerVerticle(), options, cFuture.completer());
vertx.deployVerticle(new ResponderLocConsumer(), options, rFuture.completer());
CompositeFuture.all(rFuture, cFuture, pFuture).setHandler(ar -> {
if (ar.succeeded()) {
logger.info("Verticles deployed successfully.");
future.complete();
} else {
logger.error("WARNINIG: Verticles NOT deployed successfully.");
future.fail(ar.cause());
}
});
}
// Entry point for the app
public static void main(String[] args) {
io.vertx.core.Vertx vertx = io.vertx.core.Vertx.vertx(new VertxOptions().setMetricsOptions(
new MicrometerMetricsOptions()
.setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true))
.setEnabled(true)));
Future<Void> future = Future.future();
ConfigRetriever.create(vertx, selectConfigOptions())
.getConfig(ar -> {
if (ar.succeeded()) {
deployVerticles(vertx, ar.result(), future);
} else {
logger.fatal("Failed to retrieve the configuration.");
future.fail(ar.cause());
}
});
}
}
|
[
"\"KUBERNETES_NAMESPACE\"",
"\"APP_CONFIGMAP_NAME\"",
"\"APP_CONFIGMAP_KEY\""
] |
[] |
[
"KUBERNETES_NAMESPACE",
"APP_CONFIGMAP_NAME",
"APP_CONFIGMAP_KEY"
] |
[]
|
["KUBERNETES_NAMESPACE", "APP_CONFIGMAP_NAME", "APP_CONFIGMAP_KEY"]
|
java
| 3 | 0 | |
third_party/py/gflags/gflags/_helpers.py
|
#!/usr/bin/env python
# Copyright 2002 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Helper functions for //gflags."""
import collections
import os
import re
import struct
import sys
import textwrap
try:
import fcntl # pylint: disable=g-import-not-at-top
except ImportError:
fcntl = None
try:
# Importing termios will fail on non-unix platforms.
import termios # pylint: disable=g-import-not-at-top
except ImportError:
termios = None
# pylint: disable=g-import-not-at-top
import third_party.pep257 as pep257
import six
_DEFAULT_HELP_WIDTH = 80 # Default width of help output.
_MIN_HELP_WIDTH = 40 # Minimal "sane" width of help output. We assume that any
# value below 40 is unreasonable.
# Define the allowed error rate in an input string to get suggestions.
#
# We lean towards a high threshold because we tend to be matching a phrase,
# and the simple algorithm used here is geared towards correcting word
# spellings.
#
# For manual testing, consider "<command> --list" which produced a large number
# of spurious suggestions when we used "least_errors > 0.5" instead of
# "least_erros >= 0.5".
_SUGGESTION_ERROR_RATE_THRESHOLD = 0.50
# Characters that cannot appear or are highly discouraged in an XML 1.0
# document. (See http://www.w3.org/TR/REC-xml/#charsets or
# https://en.wikipedia.org/wiki/Valid_characters_in_XML#XML_1.0)
_ILLEGAL_XML_CHARS_REGEX = re.compile(
u'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]')
# This is a set of module ids for the modules that disclaim key flags.
# This module is explicitly added to this set so that we never consider it to
# define key flag.
disclaim_module_ids = set([id(sys.modules[__name__])])
# Define special flags here so that help may be generated for them.
# NOTE: Please do NOT use SPECIAL_FLAGS from outside flags module.
# Initialized inside flagvalues.py.
SPECIAL_FLAGS = None
class _ModuleObjectAndName(
collections.namedtuple('_ModuleObjectAndName', 'module module_name')):
"""Module object and name.
Fields:
- module: object, module object.
- module_name: str, module name.
"""
def GetModuleObjectAndName(globals_dict):
"""Returns the module that defines a global environment, and its name.
Args:
globals_dict: A dictionary that should correspond to an environment
providing the values of the globals.
Returns:
_ModuleObjectAndName - pair of module object & module name.
Returns (None, None) if the module could not be identified.
"""
name = globals_dict.get('__name__', None)
module = sys.modules.get(name, None)
# Pick a more informative name for the main module.
return _ModuleObjectAndName(module,
(sys.argv[0] if name == '__main__' else name))
def GetCallingModuleObjectAndName():
"""Returns the module that's calling into this module.
We generally use this function to get the name of the module calling a
DEFINE_foo... function.
Returns:
The module object that called into this one.
Raises:
AssertionError: if no calling module could be identified.
"""
range_func = range if sys.version_info[0] >= 3 else xrange
for depth in range_func(1, sys.getrecursionlimit()):
# sys._getframe is the right thing to use here, as it's the best
# way to walk up the call stack.
globals_for_frame = sys._getframe(depth).f_globals # pylint: disable=protected-access
module, module_name = GetModuleObjectAndName(globals_for_frame)
if id(module) not in disclaim_module_ids and module_name is not None:
return _ModuleObjectAndName(module, module_name)
raise AssertionError('No module was found')
def GetCallingModule():
"""Returns the name of the module that's calling into this module."""
return GetCallingModuleObjectAndName().module_name
def StrOrUnicode(value):
"""Converts a value to a python string.
Behavior of this function is intentionally different in Python2/3.
In Python2, the given value is attempted to convert to a str (byte string).
If it contains non-ASCII characters, it is converted to a unicode instead.
In Python3, the given value is always converted to a str (unicode string).
This behavior reflects the (bad) practice in Python2 to try to represent
a string as str as long as it contains ASCII characters only.
Args:
value: An object to be converted to a string.
Returns:
A string representation of the given value. See the description above
for its type.
"""
try:
return str(value)
except UnicodeEncodeError:
return unicode(value) # Python3 should never come here
def CreateXMLDOMElement(doc, name, value):
"""Returns an XML DOM element with name and text value.
Args:
doc: A minidom.Document, the DOM document it should create nodes from.
name: A string, the tag of XML element.
value: A Python object, whose string representation will be used
as the value of the XML element. Illegal or highly discouraged xml 1.0
characters are stripped.
Returns:
An instance of minidom.Element.
"""
s = StrOrUnicode(value)
if six.PY2 and not isinstance(s, unicode):
# Get a valid unicode string.
s = s.decode('utf-8', 'ignore')
if isinstance(value, bool):
# Display boolean values as the C++ flag library does: no caps.
s = s.lower()
# Remove illegal xml characters.
s = _ILLEGAL_XML_CHARS_REGEX.sub(u'', s)
e = doc.createElement(name)
e.appendChild(doc.createTextNode(s))
return e
def GetHelpWidth():
"""Returns: an integer, the width of help lines that is used in TextWrap."""
if not sys.stdout.isatty() or termios is None or fcntl is None:
return _DEFAULT_HELP_WIDTH
try:
data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')
columns = struct.unpack('hh', data)[1]
# Emacs mode returns 0.
# Here we assume that any value below 40 is unreasonable.
if columns >= _MIN_HELP_WIDTH:
return columns
# Returning an int as default is fine, int(int) just return the int.
return int(os.getenv('COLUMNS', _DEFAULT_HELP_WIDTH))
except (TypeError, IOError, struct.error):
return _DEFAULT_HELP_WIDTH
def GetFlagSuggestions(attempt, longopt_list):
"""Get helpful similar matches for an invalid flag."""
# Don't suggest on very short strings, or if no longopts are specified.
if len(attempt) <= 2 or not longopt_list:
return []
option_names = [v.split('=')[0] for v in longopt_list]
# Find close approximations in flag prefixes.
# This also handles the case where the flag is spelled right but ambiguous.
distances = [(_DamerauLevenshtein(attempt, option[0:len(attempt)]), option)
for option in option_names]
distances.sort(key=lambda t: t[0])
least_errors, _ = distances[0]
# Don't suggest excessively bad matches.
if least_errors >= _SUGGESTION_ERROR_RATE_THRESHOLD * len(attempt):
return []
suggestions = []
for errors, name in distances:
if errors == least_errors:
suggestions.append(name)
else:
break
return suggestions
def _DamerauLevenshtein(a, b):
"""Damerau-Levenshtein edit distance from a to b."""
memo = {}
def Distance(x, y):
"""Recursively defined string distance with memoization."""
if (x, y) in memo:
return memo[x, y]
if not x:
d = len(y)
elif not y:
d = len(x)
else:
d = min(
Distance(x[1:], y) + 1, # correct an insertion error
Distance(x, y[1:]) + 1, # correct a deletion error
Distance(x[1:], y[1:]) + (x[0] != y[0])) # correct a wrong character
if len(x) >= 2 and len(y) >= 2 and x[0] == y[1] and x[1] == y[0]:
# Correct a transposition.
t = Distance(x[2:], y[2:]) + 1
if d > t:
d = t
memo[x, y] = d
return d
return Distance(a, b)
def TextWrap(text, length=None, indent='', firstline_indent=None):
"""Wraps a given text to a maximum line length and returns it.
It turns lines that only contain whitespace into empty lines, keeps new lines,
and expands tabs using 4 spaces.
Args:
text: str, Text to wrap.
length: int, Maximum length of a line, includes indentation.
If this is None then use GetHelpWidth()
indent: str, Indent for all but first line.
firstline_indent: str, Indent for first line; if None, fall back to indent.
Returns:
Wrapped text.
Raises:
ValueError: if indent or firstline_indent not shorter than length.
"""
# Get defaults where callee used None
if length is None:
length = GetHelpWidth()
if indent is None:
indent = ''
if firstline_indent is None:
firstline_indent = indent
if len(indent) >= length:
raise ValueError('Length of indent exceeds length')
if len(firstline_indent) >= length:
raise ValueError('Length of first line indent exceeds length')
text = text.expandtabs(4)
result = []
# Create one wrapper for the first paragraph and one for subsequent
# paragraphs that does not have the initial wrapping.
wrapper = textwrap.TextWrapper(
width=length, initial_indent=firstline_indent, subsequent_indent=indent)
subsequent_wrapper = textwrap.TextWrapper(
width=length, initial_indent=indent, subsequent_indent=indent)
# textwrap does not have any special treatment for newlines. From the docs:
# "...newlines may appear in the middle of a line and cause strange output.
# For this reason, text should be split into paragraphs (using
# str.splitlines() or similar) which are wrapped separately."
for paragraph in (p.strip() for p in text.splitlines()):
if paragraph:
result.extend(wrapper.wrap(paragraph))
else:
result.append('') # Keep empty lines.
# Replace initial wrapper with wrapper for subsequent paragraphs.
wrapper = subsequent_wrapper
return '\n'.join(result)
def FlagDictToArgs(flag_map):
"""Convert a dict of values into process call parameters.
This method is used to convert a dictionary into a sequence of parameters
for a binary that parses arguments using this module.
Args:
flag_map: a mapping where the keys are flag names (strings).
values are treated according to their type:
* If value is None, then only the name is emitted.
* If value is True, then only the name is emitted.
* If value is False, then only the name prepended with 'no' is emitted.
* If value is a string then --name=value is emitted.
* If value is a collection, this will emit --name=value1,value2,value3.
* Everything else is converted to string an passed as such.
Yields:
sequence of string suitable for a subprocess execution.
"""
for key, value in six.iteritems(flag_map):
if value is None:
yield '--%s' % key
elif isinstance(value, bool):
if value:
yield '--%s' % key
else:
yield '--no%s' % key
elif isinstance(value, (bytes, type(u''))):
# We don't want strings to be handled like python collections.
yield '--%s=%s' % (key, value)
else:
# Now we attempt to deal with collections.
try:
yield '--%s=%s' % (key, ','.join(str(item) for item in value))
except TypeError:
# Default case.
yield '--%s=%s' % (key, value)
def DocToHelp(doc):
"""Takes a __doc__ string and reformats it as help."""
# Get rid of starting and ending white space. Using lstrip() or even
# strip() could drop more than maximum of first line and right space
# of last line.
doc = doc.strip()
# Get rid of all empty lines.
whitespace_only_line = re.compile('^[ \t]+$', re.M)
doc = whitespace_only_line.sub('', doc)
# Cut out common space at line beginnings.
doc = pep257.trim(doc)
# Just like this module's comment, comments tend to be aligned somehow.
# In other words they all start with the same amount of white space.
# 1) keep double new lines;
# 2) keep ws after new lines if not empty line;
# 3) all other new lines shall be changed to a space;
# Solution: Match new lines between non white space and replace with space.
doc = re.sub(r'(?<=\S)\n(?=\S)', ' ', doc, flags=re.M)
return doc
def IsRunningTest():
"""Tries to detect whether we are inside of the test."""
modules = set(sys.modules)
test_modules = {
'unittest',
'unittest2',
'pytest',
}
return bool(test_modules & modules)
# TODO(b/31830082): Migrate all users to PEP8-style methods and remove this.
def define_both_methods(class_name, class_dict, old_name, new_name): # pylint: disable=invalid-name
"""Function to help CamelCase to PEP8 style class methods migration.
For any class definition:
1. Assert it does not define both old and new methods,
otherwise it does not work.
2. If it defines the old method, create the same new method.
3. If it defines the new method, create the same old method.
Args:
class_name: the class name.
class_dict: the class dictionary.
old_name: old method's name.
new_name: new method's name.
Raises:
AssertionError: raised when the class defines both the old_name and
new_name.
"""
assert old_name not in class_dict or new_name not in class_dict, (
'Class "{}" cannot define both "{}" and "{}" methods.'.format(
class_name, old_name, new_name))
if old_name in class_dict:
class_dict[new_name] = class_dict[old_name]
elif new_name in class_dict:
class_dict[old_name] = class_dict[new_name]
|
[] |
[] |
[
"COLUMNS"
] |
[]
|
["COLUMNS"]
|
python
| 1 | 0 | |
backend/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', 'haynesbook_32597.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 | |
src/ariketa1/Solution.java
|
package ariketa1;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
//Bi konstante emaitza definitzeko
private final static String EMAITZAZUZENA="YES";
private final static String EMAITZAOKERRA="NO";
//bikoteakDira funtzio lagungarria
public static boolean bikoteaDira(char a, char b) {
if (a=='('&&b==')') {
return true;
}
else if (a=='['&&b==']') {
return true;
}
else if (a=='{'&&b=='}') {
return true;
}
else {
return false;
}
}
static String isBalanced(String s) {
Stack<Character> pila=new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char karakterea=s.charAt(i);
if (karakterea=='('||karakterea=='{'||karakterea=='[') {
pila.push(karakterea);
}
else if (karakterea==')'||karakterea=='}'||karakterea==']') {
if (pila.isEmpty()) {
return EMAITZAOKERRA;
}
if (bikoteaDira(pila.pop(), karakterea)==false) {
return EMAITZAOKERRA;
}
}
}
if (pila.isEmpty()) {
return EMAITZAZUZENA;
}
else {
return EMAITZAOKERRA;
}
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int t = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int tItr = 0; tItr < t; tItr++) {
String s = scanner.nextLine();
String result = isBalanced(s);
bufferedWriter.write(result);
bufferedWriter.newLine();
}
bufferedWriter.close();
scanner.close();
}
}
|
[
"\"OUTPUT_PATH\""
] |
[] |
[
"OUTPUT_PATH"
] |
[]
|
["OUTPUT_PATH"]
|
java
| 1 | 0 | |
settings.py
|
import os
from django.conf import settings
def configure_settings():
"""
Configures settings for manage.py and for run_tests.py.
"""
if not settings.configured:
# Determine the database settings depending on if a test_db var is set in CI mode or not
test_db = os.environ.get('DB', None)
if test_db is None:
db_config = {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'ambition',
'USER': 'ambition',
'PASSWORD': 'ambition',
'HOST': 'db'
}
elif test_db == 'postgres':
db_config = {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': 'postgres',
'NAME': 'django_kmatch',
}
else:
raise RuntimeError('Unsupported test DB {0}'.format(test_db))
settings.configure(
TEST_RUNNER='django_nose.NoseTestSuiteRunner',
NOSE_ARGS=['--nocapture', '--nologcapture', '--verbosity=1'],
MIDDLEWARE_CLASSES=(),
DATABASES={
'default': db_config,
},
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django_kmatch',
'django_kmatch.tests',
),
ROOT_URLCONF='django_kmatch.urls',
DEBUG=False,
)
|
[] |
[] |
[
"DB"
] |
[]
|
["DB"]
|
python
| 1 | 0 | |
python/ray/worker.py
|
from contextlib import contextmanager
import colorama
import atexit
import faulthandler
import hashlib
import inspect
import io
import json
import logging
import os
import redis
from six.moves import queue
import sys
import threading
import time
import traceback
# Ray modules
import ray.cloudpickle as pickle
import ray.gcs_utils
import ray.memory_monitor as memory_monitor
import ray.node
import ray.job_config
import ray.parameter
import ray.ray_constants as ray_constants
import ray.remote_function
import ray.serialization as serialization
import ray._private.services as services
import ray
import setproctitle
import ray.signature
import ray.state
from ray import (
ActorID,
JobID,
ObjectRef,
Language,
)
from ray import import_thread
from ray import profiling
from ray.exceptions import (
RaySystemError,
RayError,
RayTaskError,
ObjectStoreFullError,
)
from ray.function_manager import FunctionActorManager
from ray.utils import (_random_string, check_oversized_pickle, is_cython,
setup_logger, create_and_init_new_worker_log, open_log)
SCRIPT_MODE = 0
WORKER_MODE = 1
LOCAL_MODE = 2
IO_WORKER_MODE = 3
ERROR_KEY_PREFIX = b"Error:"
# Logger for this module. It should be configured at the entry point
# into the program using Ray. Ray provides a default configuration at
# entry/init points.
logger = logging.getLogger(__name__)
class ActorCheckpointInfo:
"""Information used to maintain actor checkpoints."""
__slots__ = [
# Number of tasks executed since last checkpoint.
"num_tasks_since_last_checkpoint",
# Timestamp of the last checkpoint, in milliseconds.
"last_checkpoint_timestamp",
# IDs of the previous checkpoints.
"checkpoint_ids",
]
def __init__(self, num_tasks_since_last_checkpoint,
last_checkpoint_timestamp, checkpoint_ids):
self.num_tasks_since_last_checkpoint = num_tasks_since_last_checkpoint
self.last_checkpoint_timestamp = last_checkpoint_timestamp
self.checkpoint_ids = checkpoint_ids
class Worker:
"""A class used to define the control flow of a worker process.
Note:
The methods in this class are considered unexposed to the user. The
functions outside of this class are considered exposed.
Attributes:
connected (bool): True if Ray has been started and False otherwise.
node (ray.node.Node): The node this worker is attached to.
mode: The mode of the worker. One of SCRIPT_MODE, LOCAL_MODE, and
WORKER_MODE.
cached_functions_to_run (List): A list of functions to run on all of
the workers that should be exported as soon as connect is called.
"""
def __init__(self):
"""Initialize a Worker object."""
self.node = None
self.mode = None
self.cached_functions_to_run = []
self.actor_init_error = None
self.actors = {}
# Information used to maintain actor checkpoints.
self.actor_checkpoint_info = {}
# When the worker is constructed. Record the original value of the
# CUDA_VISIBLE_DEVICES environment variable.
self.original_gpu_ids = ray.utils.get_cuda_visible_devices()
self.memory_monitor = memory_monitor.MemoryMonitor()
# A dictionary that maps from driver id to SerializationContext
# TODO: clean up the SerializationContext once the job finished.
self.serialization_context_map = {}
self.function_actor_manager = FunctionActorManager(self)
# This event is checked regularly by all of the threads so that they
# know when to exit.
self.threads_stopped = threading.Event()
# Index of the current session. This number will
# increment every time when `ray.shutdown` is called.
self._session_index = 0
# Functions to run to process the values returned by ray.get. Each
# postprocessor must take two arguments ("object_refs", and "values").
self._post_get_hooks = []
@property
def connected(self):
return self.node is not None
@property
def node_ip_address(self):
self.check_connected()
return self.node.node_ip_address
@property
def load_code_from_local(self):
self.check_connected()
return self.node.load_code_from_local
@property
def current_job_id(self):
if hasattr(self, "core_worker"):
return self.core_worker.get_current_job_id()
return JobID.nil()
@property
def actor_id(self):
if hasattr(self, "core_worker"):
return self.core_worker.get_actor_id()
return ActorID.nil()
@property
def current_task_id(self):
return self.core_worker.get_current_task_id()
@property
def current_node_id(self):
return self.core_worker.get_current_node_id()
@property
def placement_group_id(self):
return self.core_worker.get_placement_group_id()
@property
def should_capture_child_tasks_in_placement_group(self):
return self.core_worker.should_capture_child_tasks_in_placement_group()
@property
def current_session_and_job(self):
"""Get the current session index and job id as pair."""
assert isinstance(self._session_index, int)
assert isinstance(self.current_job_id, ray.JobID)
return self._session_index, self.current_job_id
def mark_actor_init_failed(self, error):
"""Called to mark this actor as failed during initialization."""
self.actor_init_error = error
def reraise_actor_init_error(self):
"""Raises any previous actor initialization error."""
if self.actor_init_error is not None:
raise self.actor_init_error
def get_serialization_context(self, job_id=None):
"""Get the SerializationContext of the job that this worker is processing.
Args:
job_id: The ID of the job that indicates which job to get
the serialization context for.
Returns:
The serialization context of the given job.
"""
# This function needs to be protected by a lock, because it will be
# called by`register_class_for_serialization`, as well as the import
# thread, from different threads. Also, this function will recursively
# call itself, so we use RLock here.
if job_id is None:
job_id = self.current_job_id
with self.lock:
if job_id not in self.serialization_context_map:
self.serialization_context_map[
job_id] = serialization.SerializationContext(self)
return self.serialization_context_map[job_id]
def check_connected(self):
"""Check if the worker is connected.
Raises:
Exception: An exception is raised if the worker is not connected.
"""
if not self.connected:
raise RaySystemError("Ray has not been started yet. You can "
"start Ray with 'ray.init()'.")
def set_mode(self, mode):
"""Set the mode of the worker.
The mode SCRIPT_MODE should be used if this Worker is a driver that is
being run as a Python script or interactively in a shell. It will print
information about task failures.
The mode WORKER_MODE should be used if this Worker is not a driver. It
will not print information about tasks.
The mode LOCAL_MODE should be used if this Worker is a driver and if
you want to run the driver in a manner equivalent to serial Python for
debugging purposes. It will not send remote function calls to the
scheduler and will instead execute them in a blocking fashion.
Args:
mode: One of SCRIPT_MODE, WORKER_MODE, and LOCAL_MODE.
"""
self.mode = mode
def put_object(self, value, object_ref=None, pin_object=True):
"""Put value in the local object store with object reference `object_ref`.
This assumes that the value for `object_ref` has not yet been placed in
the local object store. If the plasma store is full, the worker will
automatically retry up to DEFAULT_PUT_OBJECT_RETRIES times. Each
retry will delay for an exponentially doubling amount of time,
starting with DEFAULT_PUT_OBJECT_DELAY. After this, exception
will be raised.
Args:
value: The value to put in the object store.
object_ref (ObjectRef): The object ref of the value to be
put. If None, one will be generated.
pin_object: If set, the object will be pinned at the raylet.
Returns:
ObjectRef: The object ref the object was put under.
Raises:
ray.exceptions.ObjectStoreFullError: This is raised if the attempt
to store the object fails because the object store is full even
after multiple retries.
"""
# Make sure that the value is not an object ref.
if isinstance(value, ObjectRef):
raise TypeError(
"Calling 'put' on an ray.ObjectRef is not allowed "
"(similarly, returning an ray.ObjectRef from a remote "
"function is not allowed). If you really want to "
"do this, you can wrap the ray.ObjectRef in a list and "
"call 'put' on it (or return it).")
if self.mode == LOCAL_MODE:
assert object_ref is None, ("Local Mode does not support "
"inserting with an ObjectRef")
serialized_value = self.get_serialization_context().serialize(value)
# This *must* be the first place that we construct this python
# ObjectRef because an entry with 0 local references is created when
# the object is Put() in the core worker, expecting that this python
# reference will be created. If another reference is created and
# removed before this one, it will corrupt the state in the
# reference counter.
return ray.ObjectRef(
self.core_worker.put_serialized_object(
serialized_value, object_ref=object_ref,
pin_object=pin_object))
def deserialize_objects(self, data_metadata_pairs, object_refs):
context = self.get_serialization_context()
return context.deserialize_objects(data_metadata_pairs, object_refs)
def get_objects(self, object_refs, timeout=None):
"""Get the values in the object store associated with the IDs.
Return the values from the local object store for object_refs. This
will block until all the values for object_refs have been written to
the local object store.
Args:
object_refs (List[object_ref.ObjectRef]): A list of the object refs
whose values should be retrieved.
timeout (float): timeout (float): The maximum amount of time in
seconds to wait before returning.
"""
# Make sure that the values are object refs.
for object_ref in object_refs:
if not isinstance(object_ref, ObjectRef):
raise TypeError(
f"Attempting to call `get` on the value {object_ref}, "
"which is not an ray.ObjectRef.")
timeout_ms = int(timeout * 1000) if timeout else -1
data_metadata_pairs = self.core_worker.get_objects(
object_refs, self.current_task_id, timeout_ms)
return self.deserialize_objects(data_metadata_pairs, object_refs)
def run_function_on_all_workers(self, function,
run_on_other_drivers=False):
"""Run arbitrary code on all of the workers.
This function will first be run on the driver, and then it will be
exported to all of the workers to be run. It will also be run on any
new workers that register later. If ray.init has not been called yet,
then cache the function and export it later.
Args:
function (Callable): The function to run on all of the workers. It
takes only one argument, a worker info dict. If it returns
anything, its return values will not be used.
run_on_other_drivers: The boolean that indicates whether we want to
run this function on other drivers. One case is we may need to
share objects across drivers.
"""
# If ray.init has not been called yet, then cache the function and
# export it when connect is called. Otherwise, run the function on all
# workers.
if self.mode is None:
self.cached_functions_to_run.append(function)
else:
# Attempt to pickle the function before we need it. This could
# fail, and it is more convenient if the failure happens before we
# actually run the function locally.
pickled_function = pickle.dumps(function)
function_to_run_id = hashlib.sha1(pickled_function).digest()
key = b"FunctionsToRun:" + function_to_run_id
# First run the function on the driver.
# We always run the task locally.
function({"worker": self})
# Check if the function has already been put into redis.
function_exported = self.redis_client.setnx(b"Lock:" + key, 1)
if not function_exported:
# In this case, the function has already been exported, so
# we don't need to export it again.
return
check_oversized_pickle(pickled_function, function.__name__,
"function", self)
# Run the function on all workers.
self.redis_client.hmset(
key, {
"job_id": self.current_job_id.binary(),
"function_id": function_to_run_id,
"function": pickled_function,
"run_on_other_drivers": str(run_on_other_drivers),
})
self.redis_client.rpush("Exports", key)
# TODO(rkn): If the worker fails after it calls setnx and before it
# successfully completes the hmset and rpush, then the program will
# most likely hang. This could be fixed by making these three
# operations into a transaction (or by implementing a custom
# command that does all three things).
def main_loop(self):
"""The main loop a worker runs to receive and execute tasks."""
def sigterm_handler(signum, frame):
shutdown(True)
sys.exit(1)
ray.utils.set_sigterm_handler(sigterm_handler)
self.core_worker.run_task_loop()
sys.exit(0)
def get_gpu_ids():
"""Get the IDs of the GPUs that are available to the worker.
If the CUDA_VISIBLE_DEVICES environment variable was set when the worker
started up, then the IDs returned by this method will be a subset of the
IDs in CUDA_VISIBLE_DEVICES. If not, the IDs will fall in the range
[0, NUM_GPUS - 1], where NUM_GPUS is the number of GPUs that the node has.
Returns:
A list of GPU IDs.
"""
worker = global_worker
worker.check_connected()
# TODO(ilr) Handle inserting resources in local mode
all_resource_ids = global_worker.core_worker.resource_ids()
assigned_ids = []
for resource, assignment in all_resource_ids.items():
# Handle both normal and placement group GPU resources.
if resource == "GPU" or resource.startswith("GPU_group_"):
for resource_id, _ in assignment:
assigned_ids.append(resource_id)
# If the user had already set CUDA_VISIBLE_DEVICES, then respect that (in
# the sense that only GPU IDs that appear in CUDA_VISIBLE_DEVICES should be
# returned).
if global_worker.original_gpu_ids is not None:
assigned_ids = [
global_worker.original_gpu_ids[gpu_id] for gpu_id in assigned_ids
]
# Give all GPUs in local_mode.
if global_worker.mode == LOCAL_MODE:
max_gpus = global_worker.node.get_resource_spec().num_gpus
assigned_ids = global_worker.original_gpu_ids[:max_gpus]
return assigned_ids
def get_resource_ids():
"""Get the IDs of the resources that are available to the worker.
Returns:
A dictionary mapping the name of a resource to a list of pairs, where
each pair consists of the ID of a resource and the fraction of that
resource reserved for this worker.
"""
worker = global_worker
worker.check_connected()
if _mode() == LOCAL_MODE:
raise RuntimeError("ray.get_resource_ids() currently does not work in "
"local_mode.")
return global_worker.core_worker.resource_ids()
def get_dashboard_url():
"""Get the URL to access the Ray dashboard.
Note that the URL does not specify which node the dashboard is on.
Returns:
The URL of the dashboard as a string.
"""
worker = global_worker
worker.check_connected()
return _global_node.webui_url
global_worker = Worker()
"""Worker: The global Worker object for this worker process.
We use a global Worker object to ensure that there is a single worker object
per worker process.
"""
_global_node = None
"""ray.node.Node: The global node object that is created by ray.init()."""
def print_failed_task(task_status):
"""Print information about failed tasks.
Args:
task_status (Dict): A dictionary containing the name, operationid, and
error message for a failed task.
"""
logger.error(f"""
Error: Task failed
Function Name: {task_status["function_name"]}
Task ID: {task_status["operationid"]}
Error Message: \n{task_status["error_message"]}
""")
def init(
address=None,
*,
num_cpus=None,
num_gpus=None,
resources=None,
object_store_memory=None,
local_mode=False,
ignore_reinit_error=False,
include_dashboard=None,
dashboard_host=ray_constants.DEFAULT_DASHBOARD_IP,
dashboard_port=ray_constants.DEFAULT_DASHBOARD_PORT,
job_config=None,
configure_logging=True,
logging_level=logging.INFO,
logging_format=ray_constants.LOGGER_FORMAT,
log_to_driver=True,
# The following are unstable parameters and their use is discouraged.
_enable_object_reconstruction=False,
_redis_max_memory=None,
_plasma_directory=None,
_node_ip_address=ray_constants.NODE_DEFAULT_IP,
_driver_object_store_memory=None,
_memory=None,
_redis_password=ray_constants.REDIS_DEFAULT_PASSWORD,
_java_worker_options=None,
_code_search_path=None,
_temp_dir=None,
_load_code_from_local=False,
_lru_evict=False,
_metrics_export_port=None,
_object_spilling_config=None,
_system_config=None):
"""
Connect to an existing Ray cluster or start one and connect to it.
This method handles two cases; either a Ray cluster already exists and we
just attach this driver to it or we start all of the processes associated
with a Ray cluster and attach to the newly started cluster.
To start Ray and all of the relevant processes, use this as follows:
.. code-block:: python
ray.init()
To connect to an existing Ray cluster, use this as follows (substituting
in the appropriate address):
.. code-block:: python
ray.init(address="123.45.67.89:6379")
You can also define an environment variable called `RAY_ADDRESS` in
the same format as the `address` parameter to connect to an existing
cluster with ray.init().
Args:
address (str): The address of the Ray cluster to connect to. If
this address is not provided, then this command will start Redis,
a raylet, a plasma store, a plasma manager, and some workers.
It will also kill these processes when Python exits. If the driver
is running on a node in a Ray cluster, using `auto` as the value
tells the driver to detect the the cluster, removing the need to
specify a specific node address.
num_cpus (int): Number of CPUs the user wishes to assign to each
raylet. By default, this is set based on virtual cores.
num_gpus (int): Number of GPUs the user wishes to assign to each
raylet. By default, this is set based on detected GPUs.
resources: A dictionary mapping the names of custom resources to the
quantities for them available.
object_store_memory: The amount of memory (in bytes) to start the
object store with. By default, this is automatically set based on
available system memory.
local_mode (bool): If true, the code will be executed serially. This
is useful for debugging.
ignore_reinit_error: If true, Ray suppresses errors from calling
ray.init() a second time. Ray won't be restarted.
include_dashboard: Boolean flag indicating whether or not to start the
Ray dashboard, which displays the status of the Ray
cluster. If this argument is None, then the UI will be started if
the relevant dependencies are present.
dashboard_host: The host to bind the dashboard server to. Can either be
localhost (127.0.0.1) or 0.0.0.0 (available from all interfaces).
By default, this is set to localhost to prevent access from
external machines.
dashboard_port: The port to bind the dashboard server to. Defaults to
8265.
job_config (ray.job_config.JobConfig): The job configuration.
configure_logging: True (default) if configuration of logging is
allowed here. Otherwise, the user may want to configure it
separately.
logging_level: Logging level, defaults to logging.INFO. Ignored unless
"configure_logging" is true.
logging_format: Logging format, defaults to string containing a
timestamp, filename, line number, and message. See the source file
ray_constants.py for details. Ignored unless "configure_logging"
is true.
log_to_driver (bool): If true, the output from all of the worker
processes on all nodes will be directed to the driver.
_enable_object_reconstruction (bool): If True, when an object stored in
the distributed plasma store is lost due to node failure, Ray will
attempt to reconstruct the object by re-executing the task that
created the object. Arguments to the task will be recursively
reconstructed. If False, then ray.ObjectLostError will be
thrown.
_redis_max_memory: Redis max memory.
_plasma_directory: Override the plasma mmap file directory.
_node_ip_address (str): The IP address of the node that we are on.
_driver_object_store_memory (int): Limit the amount of memory the
driver can use in the object store for creating objects.
_memory: Amount of reservable memory resource to create.
_redis_password (str): Prevents external clients without the password
from connecting to Redis if provided.
_temp_dir (str): If provided, specifies the root temporary
directory for the Ray process. Defaults to an OS-specific
conventional location, e.g., "/tmp/ray".
_load_code_from_local: Whether code should be loaded from a local
module or from the GCS.
_java_worker_options: Overwrite the options to start Java workers.
_code_search_path (list): Java classpath or python import path.
_lru_evict (bool): If True, when an object store is full, it will evict
objects in LRU order to make more space and when under memory
pressure, ray.ObjectLostError may be thrown. If False, then
reference counting will be used to decide which objects are safe
to evict and when under memory pressure, ray.ObjectStoreFullError
may be thrown.
_metrics_export_port(int): Port number Ray exposes system metrics
through a Prometheus endpoint. It is currently under active
development, and the API is subject to change.
_object_spilling_config (str): The configuration json string for object
spilling I/O worker.
_system_config (str): JSON configuration for overriding
RayConfig defaults. For testing purposes ONLY.
Returns:
Address information about the started processes.
Raises:
Exception: An exception is raised if an inappropriate combination of
arguments is passed in.
"""
if "RAY_ADDRESS" in os.environ:
if address is None or address == "auto":
address = os.environ["RAY_ADDRESS"]
else:
raise RuntimeError(
"Cannot use both the RAY_ADDRESS environment variable and "
"the address argument of ray.init simultaneously. If you "
"use RAY_ADDRESS to connect to a specific Ray cluster, "
"please call ray.init() or ray.init(address=\"auto\") on the "
"driver.")
# Convert hostnames to numerical IP address.
if _node_ip_address is not None:
node_ip_address = services.address_to_ip(_node_ip_address)
raylet_ip_address = node_ip_address
if address:
redis_address, _, _ = services.validate_redis_address(address)
else:
redis_address = None
if configure_logging:
setup_logger(logging_level, logging_format)
if redis_address is not None:
logger.info(
f"Connecting to existing Ray cluster at address: {redis_address}")
if local_mode:
driver_mode = LOCAL_MODE
else:
driver_mode = SCRIPT_MODE
if global_worker.connected:
if ignore_reinit_error:
logger.error("Calling ray.init() again after it has already been "
"called.")
return
else:
raise RuntimeError("Maybe you called ray.init twice by accident? "
"This error can be suppressed by passing in "
"'ignore_reinit_error=True' or by calling "
"'ray.shutdown()' prior to 'ray.init()'.")
_system_config = _system_config or {}
if not isinstance(_system_config, dict):
raise TypeError("The _system_config must be a dict.")
global _global_node
if redis_address is None:
# In this case, we need to start a new cluster.
ray_params = ray.parameter.RayParams(
redis_address=redis_address,
node_ip_address=node_ip_address,
raylet_ip_address=raylet_ip_address,
object_ref_seed=None,
driver_mode=driver_mode,
redirect_worker_output=None,
redirect_output=None,
num_cpus=num_cpus,
num_gpus=num_gpus,
resources=resources,
num_redis_shards=None,
redis_max_clients=None,
redis_password=_redis_password,
plasma_directory=_plasma_directory,
huge_pages=None,
include_dashboard=include_dashboard,
dashboard_host=dashboard_host,
dashboard_port=dashboard_port,
memory=_memory,
object_store_memory=object_store_memory,
redis_max_memory=_redis_max_memory,
plasma_store_socket_name=None,
temp_dir=_temp_dir,
load_code_from_local=_load_code_from_local,
java_worker_options=_java_worker_options,
code_search_path=_code_search_path,
start_initial_python_workers_for_first_job=True,
_system_config=_system_config,
lru_evict=_lru_evict,
enable_object_reconstruction=_enable_object_reconstruction,
metrics_export_port=_metrics_export_port,
object_spilling_config=_object_spilling_config)
# Start the Ray processes. We set shutdown_at_exit=False because we
# shutdown the node in the ray.shutdown call that happens in the atexit
# handler. We still spawn a reaper process in case the atexit handler
# isn't called.
_global_node = ray.node.Node(
head=True,
shutdown_at_exit=False,
spawn_reaper=True,
ray_params=ray_params)
else:
# In this case, we are connecting to an existing cluster.
if num_cpus is not None or num_gpus is not None:
raise ValueError(
"When connecting to an existing cluster, num_cpus "
"and num_gpus must not be provided.")
if resources is not None:
raise ValueError("When connecting to an existing cluster, "
"resources must not be provided.")
if object_store_memory is not None:
raise ValueError("When connecting to an existing cluster, "
"object_store_memory must not be provided.")
if _system_config is not None and len(_system_config) != 0:
raise ValueError("When connecting to an existing cluster, "
"_system_config must not be provided.")
if _lru_evict:
raise ValueError("When connecting to an existing cluster, "
"_lru_evict must not be provided.")
if _enable_object_reconstruction:
raise ValueError(
"When connecting to an existing cluster, "
"_enable_object_reconstruction must not be provided.")
# In this case, we only need to connect the node.
ray_params = ray.parameter.RayParams(
node_ip_address=node_ip_address,
raylet_ip_address=raylet_ip_address,
redis_address=redis_address,
redis_password=_redis_password,
object_ref_seed=None,
temp_dir=_temp_dir,
load_code_from_local=_load_code_from_local,
_system_config=_system_config,
lru_evict=_lru_evict,
enable_object_reconstruction=_enable_object_reconstruction,
metrics_export_port=_metrics_export_port)
_global_node = ray.node.Node(
ray_params,
head=False,
shutdown_at_exit=False,
spawn_reaper=False,
connect_only=True)
connect(
_global_node,
mode=driver_mode,
log_to_driver=log_to_driver,
worker=global_worker,
driver_object_store_memory=_driver_object_store_memory,
job_id=None,
job_config=job_config)
for hook in _post_init_hooks:
hook()
node_id = global_worker.core_worker.get_current_node_id()
return dict(_global_node.address_info, node_id=node_id.hex())
# Functions to run as callback after a successful ray init.
_post_init_hooks = []
def shutdown(_exiting_interpreter=False):
"""Disconnect the worker, and terminate processes started by ray.init().
This will automatically run at the end when a Python process that uses Ray
exits. It is ok to run this twice in a row. The primary use case for this
function is to cleanup state between tests.
Note that this will clear any remote function definitions, actor
definitions, and existing actors, so if you wish to use any previously
defined remote functions or actors after calling ray.shutdown(), then you
need to redefine them. If they were defined in an imported module, then you
will need to reload the module.
Args:
_exiting_interpreter (bool): True if this is called by the atexit hook
and false otherwise. If we are exiting the interpreter, we will
wait a little while to print any extra error messages.
"""
if _exiting_interpreter and global_worker.mode == SCRIPT_MODE:
# This is a duration to sleep before shutting down everything in order
# to make sure that log messages finish printing.
time.sleep(0.5)
disconnect(_exiting_interpreter)
# We need to destruct the core worker here because after this function,
# we will tear down any processes spawned by ray.init() and the background
# IO thread in the core worker doesn't currently handle that gracefully.
if hasattr(global_worker, "core_worker"):
del global_worker.core_worker
# Disconnect global state from GCS.
ray.state.state.disconnect()
# Shut down the Ray processes.
global _global_node
if _global_node is not None:
_global_node.kill_all_processes(check_alive=False, allow_graceful=True)
_global_node = None
# TODO(rkn): Instead of manually resetting some of the worker fields, we
# should simply set "global_worker" to equal "None" or something like that.
global_worker.set_mode(None)
global_worker._post_get_hooks = []
atexit.register(shutdown, True)
# TODO(edoakes): this should only be set in the driver.
def sigterm_handler(signum, frame):
sys.exit(signum)
try:
ray.utils.set_sigterm_handler(sigterm_handler)
except ValueError:
logger.warning("Failed to set SIGTERM handler, processes might"
"not be cleaned up properly on exit.")
# Define a custom excepthook so that if the driver exits with an exception, we
# can push that exception to Redis.
normal_excepthook = sys.excepthook
def custom_excepthook(type, value, tb):
# If this is a driver, push the exception to GCS worker table.
if global_worker.mode == SCRIPT_MODE:
error_message = "".join(traceback.format_tb(tb))
worker_id = global_worker.worker_id
worker_type = ray.gcs_utils.DRIVER
worker_info = {"exception": error_message}
ray.state.state.add_worker(worker_id, worker_type, worker_info)
# Call the normal excepthook.
normal_excepthook(type, value, tb)
sys.excepthook = custom_excepthook
# The last time we raised a TaskError in this process. We use this value to
# suppress redundant error messages pushed from the workers.
last_task_error_raise_time = 0
# The max amount of seconds to wait before printing out an uncaught error.
UNCAUGHT_ERROR_GRACE_PERIOD = 5
def _set_log_file(file_name, worker_pid, old_obj, setter_func):
# Line-buffer the output (mode 1).
f = create_and_init_new_worker_log(file_name, worker_pid)
# TODO (Alex): Python seems to always flush when writing. If that is no
# longer true, then we need to manually flush the old buffer.
# old_obj.flush()
# TODO (Alex): Flush the c/c++ userspace buffers if necessary.
# `fflush(stdout); cout.flush();`
fileno = old_obj.fileno()
# C++ logging requires redirecting the stdout file descriptor. Note that
# dup2 will automatically close the old file descriptor before overriding
# it.
os.dup2(f.fileno(), fileno)
# We also manually set sys.stdout and sys.stderr because that seems to
# have an effect on the output buffering. Without doing this, stdout
# and stderr are heavily buffered resulting in seemingly lost logging
# statements. We never want to close the stdout file descriptor, dup2 will
# close it when necessary and we don't want python's GC to close it.
setter_func(open_log(fileno, unbuffered=True, closefd=False))
return os.path.abspath(f.name)
def set_log_file(stdout_name, stderr_name):
"""Sets up logging for the current worker, creating the (fd backed) file and
flushing buffers as is necessary.
Args:
stdout_name (str): The file name that stdout should be written to.
stderr_name(str): The file name that stderr should be written to.
Returns:
(tuple) The absolute paths of the files that stdout and stderr will be
written to.
"""
stdout_path = ""
stderr_path = ""
worker_pid = os.getpid()
# lambda cannot contain assignment
def stdout_setter(x):
sys.stdout = x
def stderr_setter(x):
sys.stderr = x
if stdout_name:
_set_log_file(stdout_name, worker_pid, sys.stdout, stdout_setter)
# The stderr case should be analogous to the stdout case
if stderr_name:
_set_log_file(stderr_name, worker_pid, sys.stderr, stderr_setter)
return stdout_path, stderr_path
def print_logs(redis_client, threads_stopped, job_id):
"""Prints log messages from workers on all of the nodes.
Args:
redis_client: A client to the primary Redis shard.
threads_stopped (threading.Event): A threading event used to signal to
the thread that it should exit.
job_id (JobID): The id of the driver's job
"""
pubsub_client = redis_client.pubsub(ignore_subscribe_messages=True)
pubsub_client.subscribe(ray.gcs_utils.LOG_FILE_CHANNEL)
localhost = services.get_node_ip_address()
try:
# Keep track of the number of consecutive log messages that have been
# received with no break in between. If this number grows continually,
# then the worker is probably not able to process the log messages as
# rapidly as they are coming in.
num_consecutive_messages_received = 0
while True:
# Exit if we received a signal that we should stop.
if threads_stopped.is_set():
return
msg = pubsub_client.get_message()
if msg is None:
num_consecutive_messages_received = 0
threads_stopped.wait(timeout=0.01)
continue
num_consecutive_messages_received += 1
if (num_consecutive_messages_received % 100 == 0
and num_consecutive_messages_received > 0):
logger.warning(
"The driver may not be able to keep up with the "
"stdout/stderr of the workers. To avoid forwarding logs "
"to the driver, use 'ray.init(log_to_driver=False)'.")
data = json.loads(ray.utils.decode(msg["data"]))
# Don't show logs from other drivers.
if data["job"] and ray.utils.binary_to_hex(
job_id.binary()) != data["job"]:
continue
print_file = sys.stderr if data["is_err"] else sys.stdout
def color_for(data):
if data["pid"] == "raylet":
return colorama.Fore.YELLOW
else:
return colorama.Fore.CYAN
if data["ip"] == localhost:
for line in data["lines"]:
print(
"{}{}(pid={}){} {}".format(
colorama.Style.DIM, color_for(data), data["pid"],
colorama.Style.RESET_ALL, line),
file=print_file)
else:
for line in data["lines"]:
print(
"{}{}(pid={}, ip={}){} {}".format(
colorama.Style.DIM, color_for(data), data["pid"],
data["ip"], colorama.Style.RESET_ALL, line),
file=print_file)
except (OSError, redis.exceptions.ConnectionError) as e:
logger.error(f"print_logs: {e}")
finally:
# Close the pubsub client to avoid leaking file descriptors.
pubsub_client.close()
def print_error_messages_raylet(task_error_queue, threads_stopped):
"""Prints message received in the given output queue.
This checks periodically if any un-raised errors occurred in the
background.
Args:
task_error_queue (queue.Queue): A queue used to receive errors from the
thread that listens to Redis.
threads_stopped (threading.Event): A threading event used to signal to
the thread that it should exit.
"""
while True:
# Exit if we received a signal that we should stop.
if threads_stopped.is_set():
return
try:
error, t = task_error_queue.get(block=False)
except queue.Empty:
threads_stopped.wait(timeout=0.01)
continue
# Delay errors a little bit of time to attempt to suppress redundant
# messages originating from the worker.
while t + UNCAUGHT_ERROR_GRACE_PERIOD > time.time():
threads_stopped.wait(timeout=1)
if threads_stopped.is_set():
break
if t < last_task_error_raise_time + UNCAUGHT_ERROR_GRACE_PERIOD:
logger.debug(f"Suppressing error from worker: {error}")
else:
logger.error(f"Possible unhandled error from worker: {error}")
def listen_error_messages_raylet(worker, task_error_queue, threads_stopped):
"""Listen to error messages in the background on the driver.
This runs in a separate thread on the driver and pushes (error, time)
tuples to the output queue.
Args:
worker: The worker class that this thread belongs to.
task_error_queue (queue.Queue): A queue used to communicate with the
thread that prints the errors found by this thread.
threads_stopped (threading.Event): A threading event used to signal to
the thread that it should exit.
"""
worker.error_message_pubsub_client = worker.redis_client.pubsub(
ignore_subscribe_messages=True)
# Exports that are published after the call to
# error_message_pubsub_client.subscribe and before the call to
# error_message_pubsub_client.listen will still be processed in the loop.
# Really we should just subscribe to the errors for this specific job.
# However, currently all errors seem to be published on the same channel.
error_pubsub_channel = ray.gcs_utils.RAY_ERROR_PUBSUB_PATTERN
worker.error_message_pubsub_client.psubscribe(error_pubsub_channel)
try:
# Get the errors that occurred before the call to subscribe.
while True:
# Exit if we received a signal that we should stop.
if threads_stopped.is_set():
return
msg = worker.error_message_pubsub_client.get_message()
if msg is None:
threads_stopped.wait(timeout=0.01)
continue
pubsub_msg = ray.gcs_utils.PubSubMessage.FromString(msg["data"])
error_data = ray.gcs_utils.ErrorTableData.FromString(
pubsub_msg.data)
job_id = error_data.job_id
if job_id not in [
worker.current_job_id.binary(),
JobID.nil().binary(),
]:
continue
error_message = error_data.error_message
if (error_data.type == ray_constants.TASK_PUSH_ERROR):
# Delay it a bit to see if we can suppress it
task_error_queue.put((error_message, time.time()))
else:
logger.warning(error_message)
except (OSError, redis.exceptions.ConnectionError) as e:
logger.error(f"listen_error_messages_raylet: {e}")
finally:
# Close the pubsub client to avoid leaking file descriptors.
worker.error_message_pubsub_client.close()
def is_initialized():
"""Check if ray.init has been called yet.
Returns:
True if ray.init has already been called and false otherwise.
"""
return ray.worker.global_worker.connected
def connect(node,
mode=WORKER_MODE,
log_to_driver=False,
worker=global_worker,
driver_object_store_memory=None,
job_id=None,
job_config=None):
"""Connect this worker to the raylet, to Plasma, and to Redis.
Args:
node (ray.node.Node): The node to connect.
mode: The mode of the worker. One of SCRIPT_MODE, WORKER_MODE, and
LOCAL_MODE.
log_to_driver (bool): If true, then output from all of the worker
processes on all nodes will be directed to the driver.
worker: The ray.Worker instance.
driver_object_store_memory: Limit the amount of memory the driver can
use in the object store when creating objects.
job_id: The ID of job. If it's None, then we will generate one.
job_config (ray.job_config.JobConfig): The job configuration.
"""
# Do some basic checking to make sure we didn't call ray.init twice.
error_message = "Perhaps you called ray.init twice by accident?"
assert not worker.connected, error_message
assert worker.cached_functions_to_run is not None, error_message
# Enable nice stack traces on SIGSEGV etc.
try:
if not faulthandler.is_enabled():
faulthandler.enable(all_threads=False)
except io.UnsupportedOperation:
pass # ignore
# Create a Redis client to primary.
# The Redis client can safely be shared between threads. However,
# that is not true of Redis pubsub clients. See the documentation at
# https://github.com/andymccurdy/redis-py#thread-safety.
worker.redis_client = node.create_redis_client()
# Initialize some fields.
if mode in (WORKER_MODE, IO_WORKER_MODE):
# We should not specify the job_id if it's `WORKER_MODE`.
assert job_id is None
job_id = JobID.nil()
# TODO(qwang): Rename this to `worker_id_str` or type to `WorkerID`
worker.worker_id = _random_string()
else:
# This is the code path of driver mode.
if job_id is None:
# TODO(qwang): use `GcsClient::GenerateJobId()` here.
job_id = JobID.from_int(
int(worker.redis_client.incr("JobCounter")))
# When tasks are executed on remote workers in the context of multiple
# drivers, the current job ID is used to keep track of which job is
# responsible for the task so that error messages will be propagated to
# the correct driver.
worker.worker_id = ray.utils.compute_driver_id_from_job(
job_id).binary()
if mode is not SCRIPT_MODE and setproctitle:
process_name = ray_constants.WORKER_PROCESS_TYPE_IDLE_WORKER
if mode is IO_WORKER_MODE:
process_name = ray_constants.WORKER_PROCESS_TYPE_IO_WORKER
setproctitle.setproctitle(process_name)
if not isinstance(job_id, JobID):
raise TypeError("The type of given job id must be JobID.")
# All workers start out as non-actors. A worker can be turned into an actor
# after it is created.
worker.node = node
worker.set_mode(mode)
# For driver's check that the version information matches the version
# information that the Ray cluster was started with.
try:
ray._private.services.check_version_info(worker.redis_client)
except Exception as e:
if mode == SCRIPT_MODE:
raise e
elif mode == WORKER_MODE:
traceback_str = traceback.format_exc()
ray.utils.push_error_to_driver_through_redis(
worker.redis_client,
ray_constants.VERSION_MISMATCH_PUSH_ERROR,
traceback_str,
job_id=None)
worker.lock = threading.RLock()
driver_name = ""
log_stdout_file_path = ""
log_stderr_file_path = ""
if mode == SCRIPT_MODE:
import __main__ as main
driver_name = (main.__file__
if hasattr(main, "__file__") else "INTERACTIVE MODE")
elif mode == WORKER_MODE or mode == IO_WORKER_MODE:
# Check the RedirectOutput key in Redis and based on its value redirect
# worker output and error to their own files.
# This key is set in services.py when Redis is started.
redirect_worker_output_val = worker.redis_client.get("RedirectOutput")
if (redirect_worker_output_val is not None
and int(redirect_worker_output_val) == 1):
log_stdout_file_name, log_stderr_file_name = (
node.get_job_redirected_log_file(worker.worker_id))
try:
log_stdout_file_path, log_stderr_file_path = \
set_log_file(log_stdout_file_name, log_stderr_file_name)
except IOError:
raise IOError(
"Workers must be able to redirect their output at"
"the file descriptor level.")
elif not LOCAL_MODE:
raise ValueError(
"Invalid worker mode. Expected DRIVER, WORKER or LOCAL.")
# TODO (Alex): `current_logging_job` tracks the current job so that we know
# when to switch log files. If all logging functionaility was moved to c++,
# the functionaility in `_raylet.pyx::switch_worker_log_if_necessary` could
# be moved to `CoreWorker::SetCurrentTaskId()`.
worker.current_logging_job_id = None
redis_address, redis_port = node.redis_address.split(":")
gcs_options = ray._raylet.GcsClientOptions(
redis_address,
int(redis_port),
node.redis_password,
)
if job_config is None:
job_config = ray.job_config.JobConfig()
serialized_job_config = job_config.serialize()
worker.core_worker = ray._raylet.CoreWorker(
mode, node.plasma_store_socket_name, node.raylet_socket_name, job_id,
gcs_options, node.get_logs_dir_path(), node.node_ip_address,
node.node_manager_port, node.raylet_ip_address, (mode == LOCAL_MODE),
driver_name, log_stdout_file_path, log_stderr_file_path,
serialized_job_config, node.metrics_agent_port)
# Create an object for interfacing with the global state.
# Note, global state should be intialized after `CoreWorker`, because it
# will use glog, which is intialized in `CoreWorker`.
ray.state.state._initialize_global_state(
node.redis_address, redis_password=node.redis_password)
if driver_object_store_memory is not None:
worker.core_worker.set_object_store_client_options(
f"ray_driver_{os.getpid()}", driver_object_store_memory)
# Start the import thread
worker.import_thread = import_thread.ImportThread(worker, mode,
worker.threads_stopped)
worker.import_thread.start()
# If this is a driver running in SCRIPT_MODE, start a thread to print error
# messages asynchronously in the background. Ideally the scheduler would
# push messages to the driver's worker service, but we ran into bugs when
# trying to properly shutdown the driver's worker service, so we are
# temporarily using this implementation which constantly queries the
# scheduler for new error messages.
if mode == SCRIPT_MODE:
q = queue.Queue()
worker.listener_thread = threading.Thread(
target=listen_error_messages_raylet,
name="ray_listen_error_messages",
args=(worker, q, worker.threads_stopped))
worker.printer_thread = threading.Thread(
target=print_error_messages_raylet,
name="ray_print_error_messages",
args=(q, worker.threads_stopped))
worker.listener_thread.daemon = True
worker.listener_thread.start()
worker.printer_thread.daemon = True
worker.printer_thread.start()
if log_to_driver:
worker.logger_thread = threading.Thread(
target=print_logs,
name="ray_print_logs",
args=(worker.redis_client, worker.threads_stopped, job_id))
worker.logger_thread.daemon = True
worker.logger_thread.start()
if mode == SCRIPT_MODE:
# Add the directory containing the script that is running to the Python
# paths of the workers. Also add the current directory. Note that this
# assumes that the directory structures on the machines in the clusters
# are the same.
script_directory = os.path.abspath(os.path.dirname(sys.argv[0]))
current_directory = os.path.abspath(os.path.curdir)
worker.run_function_on_all_workers(
lambda worker_info: sys.path.insert(1, script_directory))
worker.run_function_on_all_workers(
lambda worker_info: sys.path.insert(1, current_directory))
# TODO(rkn): Here we first export functions to run, then remote
# functions. The order matters. For example, one of the functions to
# run may set the Python path, which is needed to import a module used
# to define a remote function. We may want to change the order to
# simply be the order in which the exports were defined on the driver.
# In addition, we will need to retain the ability to decide what the
# first few exports are (mostly to set the Python path). Additionally,
# note that the first exports to be defined on the driver will be the
# ones defined in separate modules that are imported by the driver.
# Export cached functions_to_run.
for function in worker.cached_functions_to_run:
worker.run_function_on_all_workers(function)
worker.cached_functions_to_run = None
def disconnect(exiting_interpreter=False):
"""Disconnect this worker from the raylet and object store."""
# Reset the list of cached remote functions and actors so that if more
# remote functions or actors are defined and then connect is called again,
# the remote functions will be exported. This is mostly relevant for the
# tests.
worker = global_worker
if worker.connected:
# Shutdown all of the threads that we've started. TODO(rkn): This
# should be handled cleanly in the worker object's destructor and not
# in this disconnect method.
worker.threads_stopped.set()
if hasattr(worker, "import_thread"):
worker.import_thread.join_import_thread()
if hasattr(worker, "listener_thread"):
worker.listener_thread.join()
if hasattr(worker, "printer_thread"):
worker.printer_thread.join()
if hasattr(worker, "logger_thread"):
worker.logger_thread.join()
worker.threads_stopped.clear()
worker._session_index += 1
worker.node = None # Disconnect the worker from the node.
worker.cached_functions_to_run = []
worker.serialization_context_map.clear()
try:
ray_actor = ray.actor
except AttributeError:
ray_actor = None # This can occur during program termination
if ray_actor is not None:
ray_actor.ActorClassMethodMetadata.reset_cache()
@contextmanager
def _changeproctitle(title, next_title):
setproctitle.setproctitle(title)
try:
yield
finally:
setproctitle.setproctitle(next_title)
def show_in_dashboard(message, key="", dtype="text"):
"""Display message in dashboard.
Display message for the current task or actor in the dashboard.
For example, this can be used to display the status of a long-running
computation.
Args:
message (str): Message to be displayed.
key (str): The key name for the message. Multiple message under
different keys will be displayed at the same time. Messages
under the same key will be overriden.
data_type (str): The type of message for rendering. One of the
following: text, html.
"""
worker = global_worker
worker.check_connected()
acceptable_dtypes = {"text", "html"}
assert dtype in acceptable_dtypes, (
f"dtype accepts only: {acceptable_dtypes}")
message_wrapped = {"message": message, "dtype": dtype}
message_encoded = json.dumps(message_wrapped).encode()
worker.core_worker.set_webui_display(key.encode(), message_encoded)
# Global varaible to make sure we only send out the warning once
blocking_get_inside_async_warned = False
def get(object_refs, *, timeout=None):
"""Get a remote object or a list of remote objects from the object store.
This method blocks until the object corresponding to the object ref is
available in the local object store. If this object is not in the local
object store, it will be shipped from an object store that has it (once the
object has been created). If object_refs is a list, then the objects
corresponding to each object in the list will be returned.
This method will issue a warning if it's running inside async context,
you can use ``await object_ref`` instead of ``ray.get(object_ref)``. For
a list of object refs, you can use ``await asyncio.gather(*object_refs)``.
Args:
object_refs: Object ref of the object to get or a list of object refs
to get.
timeout (Optional[float]): The maximum amount of time in seconds to
wait before returning.
Returns:
A Python object or a list of Python objects.
Raises:
GetTimeoutError: A GetTimeoutError is raised if a timeout is set and
the get takes longer than timeout to return.
Exception: An exception is raised if the task that created the object
or that created one of the objects raised an exception.
"""
worker = global_worker
worker.check_connected()
if hasattr(
worker,
"core_worker") and worker.core_worker.current_actor_is_asyncio():
global blocking_get_inside_async_warned
if not blocking_get_inside_async_warned:
logger.warning("Using blocking ray.get inside async actor. "
"This blocks the event loop. Please use `await` "
"on object ref with asyncio.gather if you want to "
"yield execution to the event loop instead.")
blocking_get_inside_async_warned = True
with profiling.profile("ray.get"):
is_individual_id = isinstance(object_refs, ray.ObjectRef)
if is_individual_id:
object_refs = [object_refs]
if not isinstance(object_refs, list):
raise ValueError("'object_refs' must either be an object ref "
"or a list of object refs.")
global last_task_error_raise_time
# TODO(ujvl): Consider how to allow user to retrieve the ready objects.
values = worker.get_objects(object_refs, timeout=timeout)
for i, value in enumerate(values):
if isinstance(value, RayError):
last_task_error_raise_time = time.time()
if isinstance(value, ray.exceptions.ObjectLostError):
worker.core_worker.dump_object_store_memory_usage()
if isinstance(value, RayTaskError):
raise value.as_instanceof_cause()
else:
raise value
# Run post processors.
for post_processor in worker._post_get_hooks:
values = post_processor(object_refs, values)
if is_individual_id:
values = values[0]
return values
def put(value):
"""Store an object in the object store.
The object may not be evicted while a reference to the returned ID exists.
Args:
value: The Python object to be stored.
Returns:
The object ref assigned to this value.
"""
worker = global_worker
worker.check_connected()
with profiling.profile("ray.put"):
try:
object_ref = worker.put_object(value, pin_object=True)
except ObjectStoreFullError:
logger.info(
"Put failed since the value was either too large or the "
"store was full of pinned objects.")
raise
return object_ref
# Global variable to make sure we only send out the warning once.
blocking_wait_inside_async_warned = False
def wait(object_refs, *, num_returns=1, timeout=None):
"""Return a list of IDs that are ready and a list of IDs that are not.
If timeout is set, the function returns either when the requested number of
IDs are ready or when the timeout is reached, whichever occurs first. If it
is not set, the function simply waits until that number of objects is ready
and returns that exact number of object refs.
This method returns two lists. The first list consists of object refs that
correspond to objects that are available in the object store. The second
list corresponds to the rest of the object refs (which may or may not be
ready).
Ordering of the input list of object refs is preserved. That is, if A
precedes B in the input list, and both are in the ready list, then A will
precede B in the ready list. This also holds true if A and B are both in
the remaining list.
This method will issue a warning if it's running inside an async context.
Instead of ``ray.wait(object_refs)``, you can use
``await asyncio.wait(object_refs)``.
Args:
object_refs (List[ObjectRef]): List of object refs for objects that may
or may not be ready. Note that these IDs must be unique.
num_returns (int): The number of object refs that should be returned.
timeout (float): The maximum amount of time in seconds to wait before
returning.
Returns:
A list of object refs that are ready and a list of the remaining object
IDs.
"""
worker = global_worker
worker.check_connected()
if hasattr(worker,
"core_worker") and worker.core_worker.current_actor_is_asyncio(
) and timeout != 0:
global blocking_wait_inside_async_warned
if not blocking_wait_inside_async_warned:
logger.debug("Using blocking ray.wait inside async method. "
"This blocks the event loop. Please use `await` "
"on object ref with asyncio.wait. ")
blocking_wait_inside_async_warned = True
if isinstance(object_refs, ObjectRef):
raise TypeError(
"wait() expected a list of ray.ObjectRef, got a single "
"ray.ObjectRef")
if not isinstance(object_refs, list):
raise TypeError("wait() expected a list of ray.ObjectRef, "
f"got {type(object_refs)}")
if timeout is not None and timeout < 0:
raise ValueError("The 'timeout' argument must be nonnegative. "
f"Received {timeout}")
for object_ref in object_refs:
if not isinstance(object_ref, ObjectRef):
raise TypeError("wait() expected a list of ray.ObjectRef, "
f"got list containing {type(object_ref)}")
worker.check_connected()
# TODO(swang): Check main thread.
with profiling.profile("ray.wait"):
# TODO(rkn): This is a temporary workaround for
# https://github.com/ray-project/ray/issues/997. However, it should be
# fixed in Arrow instead of here.
if len(object_refs) == 0:
return [], []
if len(object_refs) != len(set(object_refs)):
raise ValueError("Wait requires a list of unique object refs.")
if num_returns <= 0:
raise ValueError(
"Invalid number of objects to return %d." % num_returns)
if num_returns > len(object_refs):
raise ValueError("num_returns cannot be greater than the number "
"of objects provided to ray.wait.")
timeout = timeout if timeout is not None else 10**6
timeout_milliseconds = int(timeout * 1000)
ready_ids, remaining_ids = worker.core_worker.wait(
object_refs,
num_returns,
timeout_milliseconds,
worker.current_task_id,
)
return ready_ids, remaining_ids
def get_actor(name):
"""Get a handle to a detached actor.
Gets a handle to a detached actor with the given name. The actor must
have been created with Actor.options(name="name").remote().
Returns:
ActorHandle to the actor.
Raises:
ValueError if the named actor does not exist.
"""
worker = global_worker
worker.check_connected()
handle = worker.core_worker.get_named_actor_handle(name)
return handle
def kill(actor, *, no_restart=True):
"""Kill an actor forcefully.
This will interrupt any running tasks on the actor, causing them to fail
immediately. Any atexit handlers installed in the actor will still be run.
If you want to kill the actor but let pending tasks finish,
you can call ``actor.__ray_terminate__.remote()`` instead to queue a
termination task.
If the actor is a detached actor, subsequent calls to get its handle via
ray.get_actor will fail.
Args:
actor (ActorHandle): Handle to the actor to kill.
no_restart (bool): Whether or not this actor should be restarted if
it's a restartable actor.
"""
worker = global_worker
worker.check_connected()
if not isinstance(actor, ray.actor.ActorHandle):
raise ValueError("ray.kill() only supported for actors. "
"Got: {}.".format(type(actor)))
worker.core_worker.kill_actor(actor._ray_actor_id, no_restart)
def cancel(object_ref, *, force=False):
"""Cancels a task according to the following conditions.
If the specified task is pending execution, it will not be executed. If
the task is currently executing, the behavior depends on the ``force``
flag. When ``force=False``, a KeyboardInterrupt will be raised in Python
and when ``force=True``, the executing the task will immediately exit. If
the task is already finished, nothing will happen.
Only non-actor tasks can be canceled. Canceled tasks will not be
retried (max_retries will not be respected).
Calling ray.get on a canceled task will raise a TaskCancelledError or a
WorkerCrashedError if ``force=True``.
Args:
object_ref (ObjectRef): ObjectRef returned by the task
that should be canceled.
force (boolean): Whether to force-kill a running task by killing
the worker that is running the task.
Raises:
TypeError: This is also raised for actor tasks.
"""
worker = ray.worker.global_worker
worker.check_connected()
if not isinstance(object_ref, ray.ObjectRef):
raise TypeError(
"ray.cancel() only supported for non-actor object refs. "
f"Got: {type(object_ref)}.")
return worker.core_worker.cancel_task(object_ref, force)
def _mode(worker=global_worker):
"""This is a wrapper around worker.mode.
We use this wrapper so that in the remote decorator, we can call _mode()
instead of worker.mode. The difference is that when we attempt to
serialize remote functions, we don't attempt to serialize the worker
object, which cannot be serialized.
"""
return worker.mode
def make_decorator(num_returns=None,
num_cpus=None,
num_gpus=None,
memory=None,
object_store_memory=None,
resources=None,
accelerator_type=None,
max_calls=None,
max_retries=None,
max_restarts=None,
max_task_retries=None,
worker=None,
placement_group=None,
placement_group_bundle_index=-1,
placement_group_capture_child_tasks=True):
def decorator(function_or_class):
if (inspect.isfunction(function_or_class)
or is_cython(function_or_class)):
# Set the remote function default resources.
if max_restarts is not None:
raise ValueError("The keyword 'max_restarts' is not "
"allowed for remote functions.")
if max_task_retries is not None:
raise ValueError("The keyword 'max_task_retries' is not "
"allowed for remote functions.")
if num_returns is not None and (not isinstance(num_returns, int)
or num_returns < 0):
raise ValueError(
"The keyword 'num_returns' only accepts 0 or a"
" positive integer")
if max_retries is not None and (not isinstance(max_retries, int)
or max_retries < -1):
raise ValueError(
"The keyword 'max_retries' only accepts 0, -1 or a"
" positive integer")
if max_calls is not None and (not isinstance(max_calls, int)
or max_calls < 0):
raise ValueError(
"The keyword 'max_calls' only accepts 0 or a positive"
" integer")
return ray.remote_function.RemoteFunction(
Language.PYTHON, function_or_class, None, num_cpus, num_gpus,
memory, object_store_memory, resources, accelerator_type,
num_returns, max_calls, max_retries, placement_group,
placement_group_bundle_index,
placement_group_capture_child_tasks)
if inspect.isclass(function_or_class):
if num_returns is not None:
raise TypeError("The keyword 'num_returns' is not "
"allowed for actors.")
if max_calls is not None:
raise TypeError("The keyword 'max_calls' is not "
"allowed for actors.")
if max_restarts is not None and (not isinstance(max_restarts, int)
or max_restarts < -1):
raise ValueError(
"The keyword 'max_restarts' only accepts -1, 0 or a"
" positive integer")
if max_task_retries is not None and (not isinstance(
max_task_retries, int) or max_task_retries < -1):
raise ValueError(
"The keyword 'max_task_retries' only accepts -1, 0 or a"
" positive integer")
return ray.actor.make_actor(function_or_class, num_cpus, num_gpus,
memory, object_store_memory, resources,
accelerator_type, max_restarts,
max_task_retries)
raise TypeError("The @ray.remote decorator must be applied to "
"either a function or to a class.")
return decorator
def remote(*args, **kwargs):
"""Defines a remote function or an actor class.
This can be used with no arguments to define a remote function or actor as
follows:
.. code-block:: python
@ray.remote
def f():
return 1
@ray.remote
class Foo:
def method(self):
return 1
It can also be used with specific keyword arguments as follows:
.. code-block:: python
@ray.remote(num_gpus=1, max_calls=1, num_returns=2)
def f():
return 1, 2
@ray.remote(num_cpus=2, resources={"CustomResource": 1})
class Foo:
def method(self):
return 1
Remote task and actor objects returned by @ray.remote can also be
dynamically modified with the same arguments as above using
``.options()`` as follows:
.. code-block:: python
@ray.remote(num_gpus=1, max_calls=1, num_returns=2)
def f():
return 1, 2
g = f.options(num_gpus=2, max_calls=None)
@ray.remote(num_cpus=2, resources={"CustomResource": 1})
class Foo:
def method(self):
return 1
Bar = Foo.options(num_cpus=1, resources=None)
Running remote actors will be terminated when the actor handle to them
in Python is deleted, which will cause them to complete any outstanding
work and then shut down. If you want to kill them immediately, you can
also call ``ray.kill(actor)``.
Args:
num_returns (int): This is only for *remote functions*. It specifies
the number of object refs returned by
the remote function invocation.
num_cpus (float): The quantity of CPU cores to reserve
for this task or for the lifetime of the actor.
num_gpus (int): The quantity of GPUs to reserve
for this task or for the lifetime of the actor.
resources (Dict[str, float]): The quantity of various custom resources
to reserve for this task or for the lifetime of the actor.
This is a dictionary mapping strings (resource names) to floats.
accelerator_type: If specified, requires that the task or actor run
on a node with the specified type of accelerator.
See `ray.accelerators` for accelerator types.
max_calls (int): Only for *remote functions*. This specifies the
maximum number of times that a given worker can execute
the given remote function before it must exit
(this can be used to address memory leaks in third-party
libraries or to reclaim resources that cannot easily be
released, e.g., GPU memory that was acquired by TensorFlow).
By default this is infinite.
max_restarts (int): Only for *actors*. This specifies the maximum
number of times that the actor should be restarted when it dies
unexpectedly. The minimum valid value is 0 (default),
which indicates that the actor doesn't need to be restarted.
A value of -1 indicates that an actor should be restarted
indefinitely.
max_task_retries (int): Only for *actors*. How many times to
retry an actor task if the task fails due to a system error,
e.g., the actor has died. If set to -1, the system will
retry the failed task until the task succeeds, or the actor
has reached its max_restarts limit. If set to `n > 0`, the
system will retry the failed task up to n times, after which the
task will throw a `RayActorError` exception upon :obj:`ray.get`.
Note that Python exceptions are not considered system errors
and will not trigger retries.
max_retries (int): Only for *remote functions*. This specifies
the maximum number of times that the remote function
should be rerun when the worker process executing it
crashes unexpectedly. The minimum valid value is 0,
the default is 4 (default), and a value of -1 indicates
infinite retries.
placement_group (:obj:`PlacementGroup`): The placement group
this task belongs to, or ``None`` if it doesn't belong
to any group.
placement_group_bundle_index (int): The index of the bundle
if the task belongs to a placement group, which may be
-1 to indicate any available bundle.
placement_group_capture_child_tasks (bool): Default True.
If True, all the child tasks (including actor creation)
are scheduled in the same placement group.
"""
worker = global_worker
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
# This is the case where the decorator is just @ray.remote.
return make_decorator(worker=worker)(args[0])
# Parse the keyword arguments from the decorator.
error_string = ("The @ray.remote decorator must be applied either "
"with no arguments and no parentheses, for example "
"'@ray.remote', or it must be applied using some of "
"the arguments 'num_returns', 'num_cpus', 'num_gpus', "
"'memory', 'object_store_memory', 'resources', "
"'max_calls', or 'max_restarts', like "
"'@ray.remote(num_returns=2, "
"resources={\"CustomResource\": 1})'.")
assert len(args) == 0 and len(kwargs) > 0, error_string
for key in kwargs:
assert key in [
"num_returns",
"num_cpus",
"num_gpus",
"memory",
"object_store_memory",
"resources",
"accelerator_type",
"max_calls",
"max_restarts",
"max_task_retries",
"max_retries",
"placement_group",
"placement_group_bundle_index",
"placement_group_capture_child_tasks",
], error_string
num_cpus = kwargs["num_cpus"] if "num_cpus" in kwargs else None
num_gpus = kwargs["num_gpus"] if "num_gpus" in kwargs else None
resources = kwargs.get("resources")
if not isinstance(resources, dict) and resources is not None:
raise TypeError("The 'resources' keyword argument must be a "
f"dictionary, but received type {type(resources)}.")
if resources is not None:
assert "CPU" not in resources, "Use the 'num_cpus' argument."
assert "GPU" not in resources, "Use the 'num_gpus' argument."
accelerator_type = kwargs.get("accelerator_type")
# Handle other arguments.
num_returns = kwargs.get("num_returns")
max_calls = kwargs.get("max_calls")
max_restarts = kwargs.get("max_restarts")
max_task_retries = kwargs.get("max_task_retries")
memory = kwargs.get("memory")
object_store_memory = kwargs.get("object_store_memory")
max_retries = kwargs.get("max_retries")
return make_decorator(
num_returns=num_returns,
num_cpus=num_cpus,
num_gpus=num_gpus,
memory=memory,
object_store_memory=object_store_memory,
resources=resources,
accelerator_type=accelerator_type,
max_calls=max_calls,
max_restarts=max_restarts,
max_task_retries=max_task_retries,
max_retries=max_retries,
worker=worker)
|
[] |
[] |
[
"RAY_ADDRESS"
] |
[]
|
["RAY_ADDRESS"]
|
python
| 1 | 0 | |
host/signer.go
|
package host
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net"
"os"
"strings"
"syscall"
"github.com/ScaleFT/sshkeys"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/terminal"
)
const (
errCannotDecodeEncryptedPrivateKeys = "cannot decode encrypted private keys"
)
type errDescryptingPrivateKey struct {
file string
}
func (e *errDescryptingPrivateKey) Error() string {
return fmt.Sprintf("error decrypting private key %s", e.file)
}
func AuthorizedKeys(file string) ([]ssh.PublicKey, error) {
authorizedKeysBytes, err := ioutil.ReadFile(file)
if err != nil {
return nil, nil
}
var authorizedKeys []ssh.PublicKey
for len(authorizedKeysBytes) > 0 {
pubKey, _, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes)
if err != nil {
return nil, err
}
authorizedKeys = append(authorizedKeys, pubKey)
authorizedKeysBytes = rest
}
return authorizedKeys, nil
}
func Signers(privateKeys []string) (signers []ssh.Signer, cleanup func(), err error) {
cleanup = func() {}
socket := os.Getenv("SSH_AUTH_SOCK")
if socket == "" {
signers, err = SignersFromFiles(privateKeys)
} else {
signers, cleanup, err = SignersFromSSHAgent(socket, privateKeys)
}
return signers, cleanup, err
}
func SignersFromFiles(privateKeys []string) ([]ssh.Signer, error) {
var signers []ssh.Signer
for _, file := range privateKeys {
s, err := signerFromFile(file, promptForPassphrase)
if err == nil {
signers = append(signers, s)
}
}
return signers, nil
}
func SignersFromSSHAgent(socket string, privateKeys []string) (signers []ssh.Signer, cancel func(), err error) {
conn, err := net.Dial("unix", socket)
if err != nil {
return nil, nil, fmt.Errorf("error connecting to ssh-agent %s: %w", socket, err)
}
cancel = func() { conn.Close() }
agentClient := agent.NewClient(conn)
keys, err := agentClient.List()
if err != nil {
return nil, cancel, err
}
// fallback to read from files if ssh-agent doesn't match number of keys
if len(keys) != len(privateKeys) {
signers, err = SignersFromFiles(privateKeys)
if err != nil {
return nil, cancel, err
}
} else {
signers, err = agentClient.Signers()
if err != nil {
return signers, cancel, err
}
}
return signers, cancel, nil
}
func signerFromFile(file string, promptForPassphrase func(file string) ([]byte, error)) (ssh.Signer, error) {
pb, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
s, err := ssh.ParsePrivateKey(pb)
if err == nil {
return s, err
}
var e *ssh.PassphraseMissingError
if !errors.As(err, &e) && !strings.Contains(err.Error(), errCannotDecodeEncryptedPrivateKeys) {
return nil, err
}
// simulate ssh client to retry 3 times
for i := 0; i < 3; i++ {
pass, err := promptForPassphrase(file)
if err != nil {
return nil, err
}
// TODO: crypto/ssh can't properly parse openssh private key with passphrase
// Contribute https://github.com/ScaleFT/sshkeys upstream
s, err := sshkeys.ParseEncryptedPrivateKey(pb, bytes.TrimSpace(pass))
if err == nil {
return s, err
}
if !errors.Is(err, sshkeys.ErrIncorrectPassword) {
return nil, err
}
}
return nil, &errDescryptingPrivateKey{file}
}
func promptForPassphrase(file string) ([]byte, error) {
defer fmt.Println("") // clear return
fmt.Printf("Enter passphrase for key '%s': ", file)
return terminal.ReadPassword(int(syscall.Stdin))
}
|
[
"\"SSH_AUTH_SOCK\""
] |
[] |
[
"SSH_AUTH_SOCK"
] |
[]
|
["SSH_AUTH_SOCK"]
|
go
| 1 | 0 | |
options.go
|
package main
import (
"os"
"strings"
)
type options struct {
ConfigFile string
Base string
Symbol string
Name bool
}
func newOptions(docopts map[string]interface{}) (options, error) {
// ConfigFile
var configFile string
if docopts["--config"] != nil {
configFile = docopts["--config"].(string)
} else {
configFile = os.Getenv("HOME") + "/.config/cdash.yml"
}
// Base currency
base := strings.ToUpper(docopts["--base"].(string))
// Currency symbol
symbol, err := cSym(base)
if err != nil {
return options{}, err
}
// initialize an options object
opts := options{
ConfigFile: configFile,
Base: base,
Symbol: symbol,
Name: docopts["--name"].(bool),
}
// return the opts object
return opts, nil
}
|
[
"\"HOME\""
] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
go
| 1 | 0 | |
poc-3/data/test/synthetic/utils.py
|
import matplotlib; matplotlib.use("Agg")
import torch
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import glob
import os
import shutil
import time
import sys
import collections
pjoin = os.path.join
class LogPrint():
def __init__(self, file, ExpID, print_to_screen):
self.file = file
self.ExpID = ExpID
self.print_to_screen = print_to_screen
def __call__(self, some_str):
sstr = "[%s %s %s " % (self.ExpID[-6:], os.getpid(), time.strftime("%Y/%m/%d-%H:%M:%S]")) + str(some_str)
print(sstr, file=self.file, flush=True)
if self.print_to_screen:
print(sstr)
def check_path(x):
if x:
complete_path = glob.glob(x)
assert(len(complete_path) == 1), "The provided path points to more than 1 entity. Please check."
x = complete_path[0]
return x
def my_makedirs(d):
if not os.path.exists(d):
os.makedirs(d)
def set_up_dir(project_name, resume, debug):
TimeID = time.strftime("%Y%m%d-%H%M%S")
if "SERVER" in os.environ.keys():
ExpID = "SERVER" + os.environ["SERVER"] + "-" + TimeID
else:
ExpID = TimeID
project_path = "Debug_Dir" if debug else pjoin("Experiments", ExpID + "_" + project_name)
rec_img_path = pjoin(project_path, "reconstructed_images")
weights_path = pjoin(project_path, "weights")
my_makedirs(rec_img_path)
my_makedirs(weights_path)
log_path = pjoin(weights_path, "log_" + ExpID + ".txt")
log = open(log_path, "w+")
print(" ".join(["CUDA_VISIBLE_DEVICES=0 python", *sys.argv]),
file=log, flush=True) # save the script
return TimeID, ExpID, rec_img_path, weights_path, log
def get_CodeID():
script = "git log --pretty=oneline >> wh_CodeID_file.tmp"
os.system(script)
x = open("wh_CodeID_file.tmp").readline()
os.remove("wh_CodeID_file.tmp")
return x[:8]
def is_img(x):
return any(x.endswith(extension) for extension in [".png", ".jpg", ".jpeg"])
def load_param_from_t7(model, in_layer_index, out_layer):
out_layer.weight = torch.nn.Parameter(
model.get(in_layer_index).weight.float())
out_layer.bias = torch.nn.Parameter(model.get(in_layer_index).bias.float())
class LogHub(object):
def __init__(self, momentum=0):
self.losses = {}
self.momentum = momentum
def update(self, name, value):
if name not in self.losses:
self.losses[name] = value
else:
self.losses[name] = self.losses[name] * \
self.momentum + value * (1 - self.momentum)
def format(self):
keys = self.losses.keys()
keys = sorted(keys)
logtmp = ""
for k in keys:
logtmp += "%s: %.3f | " % (k, self.losses[k])
return logtmp[:-3]
def smart_load(model_path):
sth = torch.load(model_path, map_location=lambda storage, location: storage)
if isinstance(sth, collections.OrderedDict): # state_dict
return sth
elif isinstance(sth, dict): # dict which has a value of state_dict
for k, v in sth.items():
if isinstance(v, collections.OrderedDict):
return v
print("smart load failed, please manually check the given model")
|
[] |
[] |
[
"SERVER"
] |
[]
|
["SERVER"]
|
python
| 1 | 0 | |
manage.py
|
#!/usr/bin/env python
import os
import sys
from pathlib import Path
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
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 # noqa
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
# This allows easy placement of apps within the interior
# hongstagram directory.
current_path = Path(__file__).parent.resolve()
sys.path.append(str(current_path / "hongstagram"))
execute_from_command_line(sys.argv)
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
test/environment.go
|
package test
import (
"fmt"
"os"
"testing"
"github.com/google/go-containerregistry/pkg/name"
"github.com/joho/godotenv"
)
func init() {
if err := godotenv.Load("../.env"); err != nil {
fmt.Print("Failed to load environment variables from `.env` file. ")
}
}
func GetContainerRegistry(t *testing.T) (val string) {
if val = os.Getenv("STARLIGHT_CONTAINER_REGISTRY"); val == "" {
val = "http://registry:5000"
t.Fatalf("Environment variable STARLIGHT_CONTAINER_REGISTRY is undefined, using %s", val)
}
return val
}
func GetSandboxDirectory(t *testing.T) (val string) {
if val = os.Getenv("STARLIGHT_SANDBOX_DIR"); val == "" {
val = "./.sandbox"
t.Fatalf("Environment variable STARLIGHT_SANDBOX_DIR is undefined, using %s", val)
}
return val
}
func GetProxyDBName() string {
return "proxy_metadata.db"
}
func GetRegistryOptions() (opt []name.Option) {
return []name.Option{
// most of the testing environment does not have porper HTTPS certificate.
// therefore, use HTTP
name.Insecure,
}
}
|
[
"\"STARLIGHT_CONTAINER_REGISTRY\"",
"\"STARLIGHT_SANDBOX_DIR\""
] |
[] |
[
"STARLIGHT_CONTAINER_REGISTRY",
"STARLIGHT_SANDBOX_DIR"
] |
[]
|
["STARLIGHT_CONTAINER_REGISTRY", "STARLIGHT_SANDBOX_DIR"]
|
go
| 2 | 0 | |
socialaccountlogin/sociallogin/sociallogin/asgi.py
|
"""
ASGI config for sociallogin 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.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sociallogin.settings')
application = get_asgi_application()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
hbase-server/src/main/java/org/apache/hadoop/hbase/ZNodeClearer.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer;
import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
import org.apache.hadoop.hbase.zookeeper.ZNodePaths;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>Contains a set of methods for the collaboration between the start/stop scripts and the
* servers. It allows to delete immediately the znode when the master or the regions server crashes.
* The region server / master writes a specific file when it starts / becomes main master. When they
* end properly, they delete the file.</p>
* <p>In the script, we check for the existence of these files when the program ends. If they still
* exist we conclude that the server crashed, likely without deleting their znode. To have a faster
* recovery we delete immediately the znode.</p>
* <p>The strategy depends on the server type. For a region server we store the znode path in the
* file, and use it to delete it. for a master, as the znode path constant whatever the server, we
* check its content to make sure that the backup server is not now in charge.</p>
*/
@InterfaceAudience.Private
public final class ZNodeClearer {
private static final Logger LOG = LoggerFactory.getLogger(ZNodeClearer.class);
private ZNodeClearer() {}
/**
* Logs the errors without failing on exception.
*/
public static void writeMyEphemeralNodeOnDisk(String fileContent) {
String fileName = ZNodeClearer.getMyEphemeralNodeFileName();
if (fileName == null) {
LOG.warn("Environment variable HBASE_ZNODE_FILE not set; znodes will not be cleared " +
"on crash by start scripts (Longer MTTR!)");
return;
}
FileWriter fstream;
try {
fstream = new FileWriter(fileName);
} catch (IOException e) {
LOG.warn("Can't write znode file "+fileName, e);
return;
}
BufferedWriter out = new BufferedWriter(fstream);
try {
try {
out.write(fileContent + "\n");
} finally {
try {
out.close();
} finally {
fstream.close();
}
}
} catch (IOException e) {
LOG.warn("Can't write znode file "+fileName, e);
}
}
/**
* read the content of znode file, expects a single line.
*/
public static String readMyEphemeralNodeOnDisk() throws IOException {
String fileName = getMyEphemeralNodeFileName();
if (fileName == null){
throw new FileNotFoundException("No filename; set environment variable HBASE_ZNODE_FILE");
}
FileReader znodeFile = new FileReader(fileName);
BufferedReader br = null;
try {
br = new BufferedReader(znodeFile);
String file_content = br.readLine();
return file_content;
} finally {
if (br != null) br.close();
}
}
/**
* Get the name of the file used to store the znode contents
*/
public static String getMyEphemeralNodeFileName() {
return System.getenv().get("HBASE_ZNODE_FILE");
}
/**
* delete the znode file
*/
public static void deleteMyEphemeralNodeOnDisk() {
String fileName = getMyEphemeralNodeFileName();
if (fileName != null) {
new File(fileName).delete();
}
}
/**
* See HBASE-14861. We are extracting master ServerName from rsZnodePath
* example: "/hbase/rs/server.example.com,16020,1448266496481"
* @param rsZnodePath from HBASE_ZNODE_FILE
* @return String representation of ServerName or null if fails
*/
public static String parseMasterServerName(String rsZnodePath) {
String masterServerName = null;
try {
String[] rsZnodeParts = rsZnodePath.split("/");
masterServerName = rsZnodeParts[rsZnodeParts.length -1];
} catch (IndexOutOfBoundsException e) {
LOG.warn("String " + rsZnodePath + " has wrong format", e);
}
return masterServerName;
}
/**
* @return true if cluster is configured with master-rs collocation
* @deprecated since 2.4.0, will be removed in 3.0.0.
* @see <a href="https://issues.apache.org/jira/browse/HBASE-15549">HBASE-15549</a>
*/
@Deprecated
private static boolean tablesOnMaster(Configuration conf) {
boolean tablesOnMaster = true;
String confValue = conf.get(BaseLoadBalancer.TABLES_ON_MASTER);
if (confValue != null && confValue.equalsIgnoreCase("none")) {
tablesOnMaster = false;
}
return tablesOnMaster;
}
/**
* Delete the master znode if its content (ServerName string) is the same
* as the one in the znode file. (env: HBASE_ZNODE_FILE). I case of master-rs
* colloaction we extract ServerName string from rsZnode path.(HBASE-14861)
* @return true on successful deletion, false otherwise.
*/
public static boolean clear(Configuration conf) {
Configuration tempConf = new Configuration(conf);
tempConf.setInt("zookeeper.recovery.retry", 0);
ZKWatcher zkw;
try {
zkw = new ZKWatcher(tempConf, "clean znode for master",
new Abortable() {
@Override public void abort(String why, Throwable e) {}
@Override public boolean isAborted() { return false; }
});
} catch (IOException e) {
LOG.warn("Can't connect to zookeeper to read the master znode", e);
return false;
}
String znodeFileContent;
try {
znodeFileContent = ZNodeClearer.readMyEphemeralNodeOnDisk();
if (ZNodeClearer.tablesOnMaster(conf)) {
// In case of master crash also remove rsZnode since master is also regionserver
ZKUtil.deleteNodeFailSilent(zkw,
ZNodePaths.joinZNode(zkw.getZNodePaths().rsZNode, znodeFileContent));
return MasterAddressTracker.deleteIfEquals(zkw,
ZNodeClearer.parseMasterServerName(znodeFileContent));
} else {
return MasterAddressTracker.deleteIfEquals(zkw, znodeFileContent);
}
} catch (FileNotFoundException fnfe) {
// If no file, just keep going -- return success.
LOG.warn("Can't find the znode file; presume non-fatal", fnfe);
return true;
} catch (IOException e) {
LOG.warn("Can't read the content of the znode file", e);
return false;
} catch (KeeperException e) {
LOG.warn("ZooKeeper exception deleting znode", e);
return false;
} finally {
zkw.close();
}
}
}
|
[] |
[] |
[] |
[]
|
[]
|
java
| 0 | 0 | |
python/pyspark/sql.py
|
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
import types
import itertools
import warnings
import decimal
import datetime
import keyword
import warnings
from array import array
from operator import itemgetter
from pyspark.rdd import RDD
from pyspark.serializers import BatchedSerializer, PickleSerializer, CloudPickleSerializer
from pyspark.storagelevel import StorageLevel
from pyspark.traceback_utils import SCCallSiteSync
from itertools import chain, ifilter, imap
from py4j.protocol import Py4JError
from py4j.java_collections import ListConverter, MapConverter
__all__ = [
"StringType", "BinaryType", "BooleanType", "TimestampType", "DecimalType",
"DoubleType", "FloatType", "ByteType", "IntegerType", "LongType",
"ShortType", "ArrayType", "MapType", "StructField", "StructType",
"SQLContext", "HiveContext", "SchemaRDD", "Row"]
class DataType(object):
"""Spark SQL DataType"""
def __repr__(self):
return self.__class__.__name__
def __hash__(self):
return hash(str(self))
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.__dict__ == other.__dict__)
def __ne__(self, other):
return not self.__eq__(other)
class PrimitiveTypeSingleton(type):
"""Metaclass for PrimitiveType"""
_instances = {}
def __call__(cls):
if cls not in cls._instances:
cls._instances[cls] = super(PrimitiveTypeSingleton, cls).__call__()
return cls._instances[cls]
class PrimitiveType(DataType):
"""Spark SQL PrimitiveType"""
__metaclass__ = PrimitiveTypeSingleton
def __eq__(self, other):
# because they should be the same object
return self is other
class StringType(PrimitiveType):
"""Spark SQL StringType
The data type representing string values.
"""
class BinaryType(PrimitiveType):
"""Spark SQL BinaryType
The data type representing bytearray values.
"""
class BooleanType(PrimitiveType):
"""Spark SQL BooleanType
The data type representing bool values.
"""
class TimestampType(PrimitiveType):
"""Spark SQL TimestampType
The data type representing datetime.datetime values.
"""
class DecimalType(PrimitiveType):
"""Spark SQL DecimalType
The data type representing decimal.Decimal values.
"""
class DoubleType(PrimitiveType):
"""Spark SQL DoubleType
The data type representing float values.
"""
class FloatType(PrimitiveType):
"""Spark SQL FloatType
The data type representing single precision floating-point values.
"""
class ByteType(PrimitiveType):
"""Spark SQL ByteType
The data type representing int values with 1 singed byte.
"""
class IntegerType(PrimitiveType):
"""Spark SQL IntegerType
The data type representing int values.
"""
class LongType(PrimitiveType):
"""Spark SQL LongType
The data type representing long values. If the any value is
beyond the range of [-9223372036854775808, 9223372036854775807],
please use DecimalType.
"""
class ShortType(PrimitiveType):
"""Spark SQL ShortType
The data type representing int values with 2 signed bytes.
"""
class ArrayType(DataType):
"""Spark SQL ArrayType
The data type representing list values. An ArrayType object
comprises two fields, elementType (a DataType) and containsNull (a bool).
The field of elementType is used to specify the type of array elements.
The field of containsNull is used to specify if the array has None values.
"""
def __init__(self, elementType, containsNull=True):
"""Creates an ArrayType
:param elementType: the data type of elements.
:param containsNull: indicates whether the list contains None values.
>>> ArrayType(StringType) == ArrayType(StringType, True)
True
>>> ArrayType(StringType, False) == ArrayType(StringType)
False
"""
self.elementType = elementType
self.containsNull = containsNull
def __str__(self):
return "ArrayType(%s,%s)" % (self.elementType,
str(self.containsNull).lower())
class MapType(DataType):
"""Spark SQL MapType
The data type representing dict values. A MapType object comprises
three fields, keyType (a DataType), valueType (a DataType) and
valueContainsNull (a bool).
The field of keyType is used to specify the type of keys in the map.
The field of valueType is used to specify the type of values in the map.
The field of valueContainsNull is used to specify if values of this
map has None values.
For values of a MapType column, keys are not allowed to have None values.
"""
def __init__(self, keyType, valueType, valueContainsNull=True):
"""Creates a MapType
:param keyType: the data type of keys.
:param valueType: the data type of values.
:param valueContainsNull: indicates whether values contains
null values.
>>> (MapType(StringType, IntegerType)
... == MapType(StringType, IntegerType, True))
True
>>> (MapType(StringType, IntegerType, False)
... == MapType(StringType, FloatType))
False
"""
self.keyType = keyType
self.valueType = valueType
self.valueContainsNull = valueContainsNull
def __repr__(self):
return "MapType(%s,%s,%s)" % (self.keyType, self.valueType,
str(self.valueContainsNull).lower())
class StructField(DataType):
"""Spark SQL StructField
Represents a field in a StructType.
A StructField object comprises three fields, name (a string),
dataType (a DataType) and nullable (a bool). The field of name
is the name of a StructField. The field of dataType specifies
the data type of a StructField.
The field of nullable specifies if values of a StructField can
contain None values.
"""
def __init__(self, name, dataType, nullable):
"""Creates a StructField
:param name: the name of this field.
:param dataType: the data type of this field.
:param nullable: indicates whether values of this field
can be null.
>>> (StructField("f1", StringType, True)
... == StructField("f1", StringType, True))
True
>>> (StructField("f1", StringType, True)
... == StructField("f2", StringType, True))
False
"""
self.name = name
self.dataType = dataType
self.nullable = nullable
def __repr__(self):
return "StructField(%s,%s,%s)" % (self.name, self.dataType,
str(self.nullable).lower())
class StructType(DataType):
"""Spark SQL StructType
The data type representing rows.
A StructType object comprises a list of L{StructField}.
"""
def __init__(self, fields):
"""Creates a StructType
>>> struct1 = StructType([StructField("f1", StringType, True)])
>>> struct2 = StructType([StructField("f1", StringType, True)])
>>> struct1 == struct2
True
>>> struct1 = StructType([StructField("f1", StringType, True)])
>>> struct2 = StructType([StructField("f1", StringType, True),
... [StructField("f2", IntegerType, False)]])
>>> struct1 == struct2
False
"""
self.fields = fields
def __repr__(self):
return ("StructType(List(%s))" %
",".join(str(field) for field in self.fields))
def _parse_datatype_list(datatype_list_string):
"""Parses a list of comma separated data types."""
index = 0
datatype_list = []
start = 0
depth = 0
while index < len(datatype_list_string):
if depth == 0 and datatype_list_string[index] == ",":
datatype_string = datatype_list_string[start:index].strip()
datatype_list.append(_parse_datatype_string(datatype_string))
start = index + 1
elif datatype_list_string[index] == "(":
depth += 1
elif datatype_list_string[index] == ")":
depth -= 1
index += 1
# Handle the last data type
datatype_string = datatype_list_string[start:index].strip()
datatype_list.append(_parse_datatype_string(datatype_string))
return datatype_list
_all_primitive_types = dict((k, v) for k, v in globals().iteritems()
if type(v) is PrimitiveTypeSingleton and v.__base__ == PrimitiveType)
def _parse_datatype_string(datatype_string):
"""Parses the given data type string.
>>> def check_datatype(datatype):
... scala_datatype = sqlCtx._ssql_ctx.parseDataType(str(datatype))
... python_datatype = _parse_datatype_string(
... scala_datatype.toString())
... return datatype == python_datatype
>>> all(check_datatype(cls()) for cls in _all_primitive_types.values())
True
>>> # Simple ArrayType.
>>> simple_arraytype = ArrayType(StringType(), True)
>>> check_datatype(simple_arraytype)
True
>>> # Simple MapType.
>>> simple_maptype = MapType(StringType(), LongType())
>>> check_datatype(simple_maptype)
True
>>> # Simple StructType.
>>> simple_structtype = StructType([
... StructField("a", DecimalType(), False),
... StructField("b", BooleanType(), True),
... StructField("c", LongType(), True),
... StructField("d", BinaryType(), False)])
>>> check_datatype(simple_structtype)
True
>>> # Complex StructType.
>>> complex_structtype = StructType([
... StructField("simpleArray", simple_arraytype, True),
... StructField("simpleMap", simple_maptype, True),
... StructField("simpleStruct", simple_structtype, True),
... StructField("boolean", BooleanType(), False)])
>>> check_datatype(complex_structtype)
True
>>> # Complex ArrayType.
>>> complex_arraytype = ArrayType(complex_structtype, True)
>>> check_datatype(complex_arraytype)
True
>>> # Complex MapType.
>>> complex_maptype = MapType(complex_structtype,
... complex_arraytype, False)
>>> check_datatype(complex_maptype)
True
"""
index = datatype_string.find("(")
if index == -1:
# It is a primitive type.
index = len(datatype_string)
type_or_field = datatype_string[:index]
rest_part = datatype_string[index + 1:len(datatype_string) - 1].strip()
if type_or_field in _all_primitive_types:
return _all_primitive_types[type_or_field]()
elif type_or_field == "ArrayType":
last_comma_index = rest_part.rfind(",")
containsNull = True
if rest_part[last_comma_index + 1:].strip().lower() == "false":
containsNull = False
elementType = _parse_datatype_string(
rest_part[:last_comma_index].strip())
return ArrayType(elementType, containsNull)
elif type_or_field == "MapType":
last_comma_index = rest_part.rfind(",")
valueContainsNull = True
if rest_part[last_comma_index + 1:].strip().lower() == "false":
valueContainsNull = False
keyType, valueType = _parse_datatype_list(
rest_part[:last_comma_index].strip())
return MapType(keyType, valueType, valueContainsNull)
elif type_or_field == "StructField":
first_comma_index = rest_part.find(",")
name = rest_part[:first_comma_index].strip()
last_comma_index = rest_part.rfind(",")
nullable = True
if rest_part[last_comma_index + 1:].strip().lower() == "false":
nullable = False
dataType = _parse_datatype_string(
rest_part[first_comma_index + 1:last_comma_index].strip())
return StructField(name, dataType, nullable)
elif type_or_field == "StructType":
# rest_part should be in the format like
# List(StructField(field1,IntegerType,false)).
field_list_string = rest_part[rest_part.find("(") + 1:-1]
fields = _parse_datatype_list(field_list_string)
return StructType(fields)
# Mapping Python types to Spark SQL DateType
_type_mappings = {
bool: BooleanType,
int: IntegerType,
long: LongType,
float: DoubleType,
str: StringType,
unicode: StringType,
bytearray: BinaryType,
decimal.Decimal: DecimalType,
datetime.datetime: TimestampType,
datetime.date: TimestampType,
datetime.time: TimestampType,
}
def _infer_type(obj):
"""Infer the DataType from obj"""
if obj is None:
raise ValueError("Can not infer type for None")
dataType = _type_mappings.get(type(obj))
if dataType is not None:
return dataType()
if isinstance(obj, dict):
if not obj:
raise ValueError("Can not infer type for empty dict")
key, value = obj.iteritems().next()
return MapType(_infer_type(key), _infer_type(value), True)
elif isinstance(obj, (list, array)):
if not obj:
raise ValueError("Can not infer type for empty list/array")
return ArrayType(_infer_type(obj[0]), True)
else:
try:
return _infer_schema(obj)
except ValueError:
raise ValueError("not supported type: %s" % type(obj))
def _infer_schema(row):
"""Infer the schema from dict/namedtuple/object"""
if isinstance(row, dict):
items = sorted(row.items())
elif isinstance(row, tuple):
if hasattr(row, "_fields"): # namedtuple
items = zip(row._fields, tuple(row))
elif hasattr(row, "__FIELDS__"): # Row
items = zip(row.__FIELDS__, tuple(row))
elif all(isinstance(x, tuple) and len(x) == 2 for x in row):
items = row
else:
raise ValueError("Can't infer schema from tuple")
elif hasattr(row, "__dict__"): # object
items = sorted(row.__dict__.items())
else:
raise ValueError("Can not infer schema for type: %s" % type(row))
fields = [StructField(k, _infer_type(v), True) for k, v in items]
return StructType(fields)
def _create_converter(obj, dataType):
"""Create an converter to drop the names of fields in obj """
if isinstance(dataType, ArrayType):
conv = _create_converter(obj[0], dataType.elementType)
return lambda row: map(conv, row)
elif isinstance(dataType, MapType):
value = obj.values()[0]
conv = _create_converter(value, dataType.valueType)
return lambda row: dict((k, conv(v)) for k, v in row.iteritems())
elif not isinstance(dataType, StructType):
return lambda x: x
# dataType must be StructType
names = [f.name for f in dataType.fields]
if isinstance(obj, dict):
conv = lambda o: tuple(o.get(n) for n in names)
elif isinstance(obj, tuple):
if hasattr(obj, "_fields"): # namedtuple
conv = tuple
elif hasattr(obj, "__FIELDS__"):
conv = tuple
elif all(isinstance(x, tuple) and len(x) == 2 for x in obj):
conv = lambda o: tuple(v for k, v in o)
else:
raise ValueError("unexpected tuple")
elif hasattr(obj, "__dict__"): # object
conv = lambda o: [o.__dict__.get(n, None) for n in names]
if all(isinstance(f.dataType, PrimitiveType) for f in dataType.fields):
return conv
row = conv(obj)
convs = [_create_converter(v, f.dataType)
for v, f in zip(row, dataType.fields)]
def nested_conv(row):
return tuple(f(v) for f, v in zip(convs, conv(row)))
return nested_conv
def _drop_schema(rows, schema):
""" all the names of fields, becoming tuples"""
iterator = iter(rows)
row = iterator.next()
converter = _create_converter(row, schema)
yield converter(row)
for i in iterator:
yield converter(i)
_BRACKETS = {'(': ')', '[': ']', '{': '}'}
def _split_schema_abstract(s):
"""
split the schema abstract into fields
>>> _split_schema_abstract("a b c")
['a', 'b', 'c']
>>> _split_schema_abstract("a(a b)")
['a(a b)']
>>> _split_schema_abstract("a b[] c{a b}")
['a', 'b[]', 'c{a b}']
>>> _split_schema_abstract(" ")
[]
"""
r = []
w = ''
brackets = []
for c in s:
if c == ' ' and not brackets:
if w:
r.append(w)
w = ''
else:
w += c
if c in _BRACKETS:
brackets.append(c)
elif c in _BRACKETS.values():
if not brackets or c != _BRACKETS[brackets.pop()]:
raise ValueError("unexpected " + c)
if brackets:
raise ValueError("brackets not closed: %s" % brackets)
if w:
r.append(w)
return r
def _parse_field_abstract(s):
"""
Parse a field in schema abstract
>>> _parse_field_abstract("a")
StructField(a,None,true)
>>> _parse_field_abstract("b(c d)")
StructField(b,StructType(...c,None,true),StructField(d...
>>> _parse_field_abstract("a[]")
StructField(a,ArrayType(None,true),true)
>>> _parse_field_abstract("a{[]}")
StructField(a,MapType(None,ArrayType(None,true),true),true)
"""
if set(_BRACKETS.keys()) & set(s):
idx = min((s.index(c) for c in _BRACKETS if c in s))
name = s[:idx]
return StructField(name, _parse_schema_abstract(s[idx:]), True)
else:
return StructField(s, None, True)
def _parse_schema_abstract(s):
"""
parse abstract into schema
>>> _parse_schema_abstract("a b c")
StructType...a...b...c...
>>> _parse_schema_abstract("a[b c] b{}")
StructType...a,ArrayType...b...c...b,MapType...
>>> _parse_schema_abstract("c{} d{a b}")
StructType...c,MapType...d,MapType...a...b...
>>> _parse_schema_abstract("a b(t)").fields[1]
StructField(b,StructType(List(StructField(t,None,true))),true)
"""
s = s.strip()
if not s:
return
elif s.startswith('('):
return _parse_schema_abstract(s[1:-1])
elif s.startswith('['):
return ArrayType(_parse_schema_abstract(s[1:-1]), True)
elif s.startswith('{'):
return MapType(None, _parse_schema_abstract(s[1:-1]))
parts = _split_schema_abstract(s)
fields = [_parse_field_abstract(p) for p in parts]
return StructType(fields)
def _infer_schema_type(obj, dataType):
"""
Fill the dataType with types infered from obj
>>> schema = _parse_schema_abstract("a b c")
>>> row = (1, 1.0, "str")
>>> _infer_schema_type(row, schema)
StructType...IntegerType...DoubleType...StringType...
>>> row = [[1], {"key": (1, 2.0)}]
>>> schema = _parse_schema_abstract("a[] b{c d}")
>>> _infer_schema_type(row, schema)
StructType...a,ArrayType...b,MapType(StringType,...c,IntegerType...
"""
if dataType is None:
return _infer_type(obj)
if not obj:
raise ValueError("Can not infer type from empty value")
if isinstance(dataType, ArrayType):
eType = _infer_schema_type(obj[0], dataType.elementType)
return ArrayType(eType, True)
elif isinstance(dataType, MapType):
k, v = obj.iteritems().next()
return MapType(_infer_type(k),
_infer_schema_type(v, dataType.valueType))
elif isinstance(dataType, StructType):
fs = dataType.fields
assert len(fs) == len(obj), \
"Obj(%s) have different length with fields(%s)" % (obj, fs)
fields = [StructField(f.name, _infer_schema_type(o, f.dataType), True)
for o, f in zip(obj, fs)]
return StructType(fields)
else:
raise ValueError("Unexpected dataType: %s" % dataType)
_acceptable_types = {
BooleanType: (bool,),
ByteType: (int, long),
ShortType: (int, long),
IntegerType: (int, long),
LongType: (int, long),
FloatType: (float,),
DoubleType: (float,),
DecimalType: (decimal.Decimal,),
StringType: (str, unicode),
BinaryType: (bytearray,),
TimestampType: (datetime.datetime,),
ArrayType: (list, tuple, array),
MapType: (dict,),
StructType: (tuple, list),
}
def _verify_type(obj, dataType):
"""
Verify the type of obj against dataType, raise an exception if
they do not match.
>>> _verify_type(None, StructType([]))
>>> _verify_type("", StringType())
>>> _verify_type(0, IntegerType())
>>> _verify_type(range(3), ArrayType(ShortType()))
>>> _verify_type(set(), ArrayType(StringType())) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError:...
>>> _verify_type({}, MapType(StringType(), IntegerType()))
>>> _verify_type((), StructType([]))
>>> _verify_type([], StructType([]))
>>> _verify_type([1], StructType([])) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError:...
"""
# all objects are nullable
if obj is None:
return
_type = type(dataType)
assert _type in _acceptable_types, "unkown datatype: %s" % dataType
# subclass of them can not be deserialized in JVM
if type(obj) not in _acceptable_types[_type]:
raise TypeError("%s can not accept abject in type %s"
% (dataType, type(obj)))
if isinstance(dataType, ArrayType):
for i in obj:
_verify_type(i, dataType.elementType)
elif isinstance(dataType, MapType):
for k, v in obj.iteritems():
_verify_type(k, dataType.keyType)
_verify_type(v, dataType.valueType)
elif isinstance(dataType, StructType):
if len(obj) != len(dataType.fields):
raise ValueError("Length of object (%d) does not match with"
"length of fields (%d)" % (len(obj), len(dataType.fields)))
for v, f in zip(obj, dataType.fields):
_verify_type(v, f.dataType)
_cached_cls = {}
def _restore_object(dataType, obj):
""" Restore object during unpickling. """
# use id(dataType) as key to speed up lookup in dict
# Because of batched pickling, dataType will be the
# same object in mose cases.
k = id(dataType)
cls = _cached_cls.get(k)
if cls is None:
# use dataType as key to avoid create multiple class
cls = _cached_cls.get(dataType)
if cls is None:
cls = _create_cls(dataType)
_cached_cls[dataType] = cls
_cached_cls[k] = cls
return cls(obj)
def _create_object(cls, v):
""" Create an customized object with class `cls`. """
return cls(v) if v is not None else v
def _create_getter(dt, i):
""" Create a getter for item `i` with schema """
cls = _create_cls(dt)
def getter(self):
return _create_object(cls, self[i])
return getter
def _has_struct(dt):
"""Return whether `dt` is or has StructType in it"""
if isinstance(dt, StructType):
return True
elif isinstance(dt, ArrayType):
return _has_struct(dt.elementType)
elif isinstance(dt, MapType):
return _has_struct(dt.valueType)
return False
def _create_properties(fields):
"""Create properties according to fields"""
ps = {}
for i, f in enumerate(fields):
name = f.name
if (name.startswith("__") and name.endswith("__")
or keyword.iskeyword(name)):
warnings.warn("field name %s can not be accessed in Python,"
"use position to access it instead" % name)
if _has_struct(f.dataType):
# delay creating object until accessing it
getter = _create_getter(f.dataType, i)
else:
getter = itemgetter(i)
ps[name] = property(getter)
return ps
def _create_cls(dataType):
"""
Create an class by dataType
The created class is similar to namedtuple, but can have nested schema.
>>> schema = _parse_schema_abstract("a b c")
>>> row = (1, 1.0, "str")
>>> schema = _infer_schema_type(row, schema)
>>> obj = _create_cls(schema)(row)
>>> import pickle
>>> pickle.loads(pickle.dumps(obj))
Row(a=1, b=1.0, c='str')
>>> row = [[1], {"key": (1, 2.0)}]
>>> schema = _parse_schema_abstract("a[] b{c d}")
>>> schema = _infer_schema_type(row, schema)
>>> obj = _create_cls(schema)(row)
>>> pickle.loads(pickle.dumps(obj))
Row(a=[1], b={'key': Row(c=1, d=2.0)})
>>> pickle.loads(pickle.dumps(obj.a))
[1]
>>> pickle.loads(pickle.dumps(obj.b))
{'key': Row(c=1, d=2.0)}
"""
if isinstance(dataType, ArrayType):
cls = _create_cls(dataType.elementType)
def List(l):
if l is None:
return
return [_create_object(cls, v) for v in l]
return List
elif isinstance(dataType, MapType):
cls = _create_cls(dataType.valueType)
def Dict(d):
if d is None:
return
return dict((k, _create_object(cls, v)) for k, v in d.items())
return Dict
elif not isinstance(dataType, StructType):
raise Exception("unexpected data type: %s" % dataType)
class Row(tuple):
""" Row in SchemaRDD """
__DATATYPE__ = dataType
__FIELDS__ = tuple(f.name for f in dataType.fields)
__slots__ = ()
# create property for fast access
locals().update(_create_properties(dataType.fields))
def __repr__(self):
# call collect __repr__ for nested objects
return ("Row(%s)" % ", ".join("%s=%r" % (n, getattr(self, n))
for n in self.__FIELDS__))
def __reduce__(self):
return (_restore_object, (self.__DATATYPE__, tuple(self)))
return Row
class SQLContext(object):
"""Main entry point for Spark SQL functionality.
A SQLContext can be used create L{SchemaRDD}, register L{SchemaRDD} as
tables, execute SQL over tables, cache tables, and read parquet files.
"""
def __init__(self, sparkContext, sqlContext=None):
"""Create a new SQLContext.
@param sparkContext: The SparkContext to wrap.
@param sqlContext: An optional JVM Scala SQLContext. If set, we do not instatiate a new
SQLContext in the JVM, instead we make all calls to this object.
>>> srdd = sqlCtx.inferSchema(rdd)
>>> sqlCtx.inferSchema(srdd) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError:...
>>> bad_rdd = sc.parallelize([1,2,3])
>>> sqlCtx.inferSchema(bad_rdd) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError:...
>>> from datetime import datetime
>>> allTypes = sc.parallelize([Row(i=1, s="string", d=1.0, l=1L,
... b=True, list=[1, 2, 3], dict={"s": 0}, row=Row(a=1),
... time=datetime(2014, 8, 1, 14, 1, 5))])
>>> srdd = sqlCtx.inferSchema(allTypes)
>>> srdd.registerTempTable("allTypes")
>>> sqlCtx.sql('select i+1, d+1, not b, list[1], dict["s"], time, row.a '
... 'from allTypes where b and i > 0').collect()
[Row(c0=2, c1=2.0, c2=False, c3=2, c4=0...8, 1, 14, 1, 5), a=1)]
>>> srdd.map(lambda x: (x.i, x.s, x.d, x.l, x.b, x.time,
... x.row.a, x.list)).collect()
[(1, u'string', 1.0, 1, True, ...(2014, 8, 1, 14, 1, 5), 1, [1, 2, 3])]
"""
self._sc = sparkContext
self._jsc = self._sc._jsc
self._jvm = self._sc._jvm
self._pythonToJava = self._jvm.PythonRDD.pythonToJavaArray
self._scala_SQLContext = sqlContext
@property
def _ssql_ctx(self):
"""Accessor for the JVM Spark SQL context.
Subclasses can override this property to provide their own
JVM Contexts.
"""
if self._scala_SQLContext is None:
self._scala_SQLContext = self._jvm.SQLContext(self._jsc.sc())
return self._scala_SQLContext
def registerFunction(self, name, f, returnType=StringType()):
"""Registers a lambda function as a UDF so it can be used in SQL statements.
In addition to a name and the function itself, the return type can be optionally specified.
When the return type is not given it default to a string and conversion will automatically
be done. For any other return type, the produced object must match the specified type.
>>> sqlCtx.registerFunction("stringLengthString", lambda x: len(x))
>>> sqlCtx.sql("SELECT stringLengthString('test')").collect()
[Row(c0=u'4')]
>>> sqlCtx.registerFunction("stringLengthInt", lambda x: len(x), IntegerType())
>>> sqlCtx.sql("SELECT stringLengthInt('test')").collect()
[Row(c0=4)]
"""
func = lambda _, it: imap(lambda x: f(*x), it)
command = (func,
BatchedSerializer(PickleSerializer(), 1024),
BatchedSerializer(PickleSerializer(), 1024))
ser = CloudPickleSerializer()
pickled_command = ser.dumps(command)
if pickled_command > (1 << 20): # 1M
broadcast = self._sc.broadcast(pickled_command)
pickled_command = ser.dumps(broadcast)
broadcast_vars = ListConverter().convert(
[x._jbroadcast for x in self._sc._pickled_broadcast_vars],
self._sc._gateway._gateway_client)
self._sc._pickled_broadcast_vars.clear()
env = MapConverter().convert(self._sc.environment,
self._sc._gateway._gateway_client)
includes = ListConverter().convert(self._sc._python_includes,
self._sc._gateway._gateway_client)
self._ssql_ctx.registerPython(name,
bytearray(pickled_command),
env,
includes,
self._sc.pythonExec,
broadcast_vars,
self._sc._javaAccumulator,
str(returnType))
def inferSchema(self, rdd):
"""Infer and apply a schema to an RDD of L{Row}.
We peek at the first row of the RDD to determine the fields' names
and types. Nested collections are supported, which include array,
dict, list, Row, tuple, namedtuple, or object.
All the rows in `rdd` should have the same type with the first one,
or it will cause runtime exceptions.
Each row could be L{pyspark.sql.Row} object or namedtuple or objects,
using dict is deprecated.
>>> rdd = sc.parallelize(
... [Row(field1=1, field2="row1"),
... Row(field1=2, field2="row2"),
... Row(field1=3, field2="row3")])
>>> srdd = sqlCtx.inferSchema(rdd)
>>> srdd.collect()[0]
Row(field1=1, field2=u'row1')
>>> NestedRow = Row("f1", "f2")
>>> nestedRdd1 = sc.parallelize([
... NestedRow(array('i', [1, 2]), {"row1": 1.0}),
... NestedRow(array('i', [2, 3]), {"row2": 2.0})])
>>> srdd = sqlCtx.inferSchema(nestedRdd1)
>>> srdd.collect()
[Row(f1=[1, 2], f2={u'row1': 1.0}), ..., f2={u'row2': 2.0})]
>>> nestedRdd2 = sc.parallelize([
... NestedRow([[1, 2], [2, 3]], [1, 2]),
... NestedRow([[2, 3], [3, 4]], [2, 3])])
>>> srdd = sqlCtx.inferSchema(nestedRdd2)
>>> srdd.collect()
[Row(f1=[[1, 2], [2, 3]], f2=[1, 2]), ..., f2=[2, 3])]
"""
if isinstance(rdd, SchemaRDD):
raise TypeError("Cannot apply schema to SchemaRDD")
first = rdd.first()
if not first:
raise ValueError("The first row in RDD is empty, "
"can not infer schema")
if type(first) is dict:
warnings.warn("Using RDD of dict to inferSchema is deprecated,"
"please use pyspark.sql.Row instead")
schema = _infer_schema(first)
rdd = rdd.mapPartitions(lambda rows: _drop_schema(rows, schema))
return self.applySchema(rdd, schema)
def applySchema(self, rdd, schema):
"""
Applies the given schema to the given RDD of L{tuple} or L{list}.
These tuples or lists can contain complex nested structures like
lists, maps or nested rows.
The schema should be a StructType.
It is important that the schema matches the types of the objects
in each row or exceptions could be thrown at runtime.
>>> rdd2 = sc.parallelize([(1, "row1"), (2, "row2"), (3, "row3")])
>>> schema = StructType([StructField("field1", IntegerType(), False),
... StructField("field2", StringType(), False)])
>>> srdd = sqlCtx.applySchema(rdd2, schema)
>>> sqlCtx.registerRDDAsTable(srdd, "table1")
>>> srdd2 = sqlCtx.sql("SELECT * from table1")
>>> srdd2.collect()
[Row(field1=1, field2=u'row1'),..., Row(field1=3, field2=u'row3')]
>>> from datetime import datetime
>>> rdd = sc.parallelize([(127, -128L, -32768, 32767, 2147483647L, 1.0,
... datetime(2010, 1, 1, 1, 1, 1),
... {"a": 1}, (2,), [1, 2, 3], None)])
>>> schema = StructType([
... StructField("byte1", ByteType(), False),
... StructField("byte2", ByteType(), False),
... StructField("short1", ShortType(), False),
... StructField("short2", ShortType(), False),
... StructField("int", IntegerType(), False),
... StructField("float", FloatType(), False),
... StructField("time", TimestampType(), False),
... StructField("map",
... MapType(StringType(), IntegerType(), False), False),
... StructField("struct",
... StructType([StructField("b", ShortType(), False)]), False),
... StructField("list", ArrayType(ByteType(), False), False),
... StructField("null", DoubleType(), True)])
>>> srdd = sqlCtx.applySchema(rdd, schema)
>>> results = srdd.map(
... lambda x: (x.byte1, x.byte2, x.short1, x.short2, x.int, x.float, x.time,
... x.map["a"], x.struct.b, x.list, x.null))
>>> results.collect()[0]
(127, -128, -32768, 32767, 2147483647, 1.0, ...(2010, 1, 1, 1, 1, 1), 1, 2, [1, 2, 3], None)
>>> srdd.registerTempTable("table2")
>>> sqlCtx.sql(
... "SELECT byte1 - 1 AS byte1, byte2 + 1 AS byte2, " +
... "short1 + 1 AS short1, short2 - 1 AS short2, int - 1 AS int, " +
... "float + 1.5 as float FROM table2").collect()
[Row(byte1=126, byte2=-127, short1=-32767, short2=32766, int=2147483646, float=2.5)]
>>> rdd = sc.parallelize([(127, -32768, 1.0,
... datetime(2010, 1, 1, 1, 1, 1),
... {"a": 1}, (2,), [1, 2, 3])])
>>> abstract = "byte short float time map{} struct(b) list[]"
>>> schema = _parse_schema_abstract(abstract)
>>> typedSchema = _infer_schema_type(rdd.first(), schema)
>>> srdd = sqlCtx.applySchema(rdd, typedSchema)
>>> srdd.collect()
[Row(byte=127, short=-32768, float=1.0, time=..., list=[1, 2, 3])]
"""
if isinstance(rdd, SchemaRDD):
raise TypeError("Cannot apply schema to SchemaRDD")
if not isinstance(schema, StructType):
raise TypeError("schema should be StructType")
# take the first few rows to verify schema
rows = rdd.take(10)
# Row() cannot been deserialized by Pyrolite
if rows and isinstance(rows[0], tuple) and rows[0].__class__.__name__ == 'Row':
rdd = rdd.map(tuple)
rows = rdd.take(10)
for row in rows:
_verify_type(row, schema)
batched = isinstance(rdd._jrdd_deserializer, BatchedSerializer)
jrdd = self._pythonToJava(rdd._jrdd, batched)
srdd = self._ssql_ctx.applySchemaToPythonRDD(jrdd.rdd(), str(schema))
return SchemaRDD(srdd.toJavaSchemaRDD(), self)
def registerRDDAsTable(self, rdd, tableName):
"""Registers the given RDD as a temporary table in the catalog.
Temporary tables exist only during the lifetime of this instance of
SQLContext.
>>> srdd = sqlCtx.inferSchema(rdd)
>>> sqlCtx.registerRDDAsTable(srdd, "table1")
"""
if (rdd.__class__ is SchemaRDD):
srdd = rdd._jschema_rdd.baseSchemaRDD()
self._ssql_ctx.registerRDDAsTable(srdd, tableName)
else:
raise ValueError("Can only register SchemaRDD as table")
def parquetFile(self, path):
"""Loads a Parquet file, returning the result as a L{SchemaRDD}.
>>> import tempfile, shutil
>>> parquetFile = tempfile.mkdtemp()
>>> shutil.rmtree(parquetFile)
>>> srdd = sqlCtx.inferSchema(rdd)
>>> srdd.saveAsParquetFile(parquetFile)
>>> srdd2 = sqlCtx.parquetFile(parquetFile)
>>> sorted(srdd.collect()) == sorted(srdd2.collect())
True
"""
jschema_rdd = self._ssql_ctx.parquetFile(path).toJavaSchemaRDD()
return SchemaRDD(jschema_rdd, self)
def jsonFile(self, path, schema=None):
"""
Loads a text file storing one JSON object per line as a
L{SchemaRDD}.
If the schema is provided, applies the given schema to this
JSON dataset.
Otherwise, it goes through the entire dataset once to determine
the schema.
>>> import tempfile, shutil
>>> jsonFile = tempfile.mkdtemp()
>>> shutil.rmtree(jsonFile)
>>> ofn = open(jsonFile, 'w')
>>> for json in jsonStrings:
... print>>ofn, json
>>> ofn.close()
>>> srdd1 = sqlCtx.jsonFile(jsonFile)
>>> sqlCtx.registerRDDAsTable(srdd1, "table1")
>>> srdd2 = sqlCtx.sql(
... "SELECT field1 AS f1, field2 as f2, field3 as f3, "
... "field6 as f4 from table1")
>>> for r in srdd2.collect():
... print r
Row(f1=1, f2=u'row1', f3=Row(field4=11, field5=None), f4=None)
Row(f1=2, f2=None, f3=Row(field4=22,..., f4=[Row(field7=u'row2')])
Row(f1=None, f2=u'row3', f3=Row(field4=33, field5=[]), f4=None)
>>> srdd3 = sqlCtx.jsonFile(jsonFile, srdd1.schema())
>>> sqlCtx.registerRDDAsTable(srdd3, "table2")
>>> srdd4 = sqlCtx.sql(
... "SELECT field1 AS f1, field2 as f2, field3 as f3, "
... "field6 as f4 from table2")
>>> for r in srdd4.collect():
... print r
Row(f1=1, f2=u'row1', f3=Row(field4=11, field5=None), f4=None)
Row(f1=2, f2=None, f3=Row(field4=22,..., f4=[Row(field7=u'row2')])
Row(f1=None, f2=u'row3', f3=Row(field4=33, field5=[]), f4=None)
>>> schema = StructType([
... StructField("field2", StringType(), True),
... StructField("field3",
... StructType([
... StructField("field5",
... ArrayType(IntegerType(), False), True)]), False)])
>>> srdd5 = sqlCtx.jsonFile(jsonFile, schema)
>>> sqlCtx.registerRDDAsTable(srdd5, "table3")
>>> srdd6 = sqlCtx.sql(
... "SELECT field2 AS f1, field3.field5 as f2, "
... "field3.field5[0] as f3 from table3")
>>> srdd6.collect()
[Row(f1=u'row1', f2=None, f3=None)...Row(f1=u'row3', f2=[], f3=None)]
"""
if schema is None:
srdd = self._ssql_ctx.jsonFile(path)
else:
scala_datatype = self._ssql_ctx.parseDataType(str(schema))
srdd = self._ssql_ctx.jsonFile(path, scala_datatype)
return SchemaRDD(srdd.toJavaSchemaRDD(), self)
def jsonRDD(self, rdd, schema=None):
"""Loads an RDD storing one JSON object per string as a L{SchemaRDD}.
If the schema is provided, applies the given schema to this
JSON dataset.
Otherwise, it goes through the entire dataset once to determine
the schema.
>>> srdd1 = sqlCtx.jsonRDD(json)
>>> sqlCtx.registerRDDAsTable(srdd1, "table1")
>>> srdd2 = sqlCtx.sql(
... "SELECT field1 AS f1, field2 as f2, field3 as f3, "
... "field6 as f4 from table1")
>>> for r in srdd2.collect():
... print r
Row(f1=1, f2=u'row1', f3=Row(field4=11, field5=None), f4=None)
Row(f1=2, f2=None, f3=Row(field4=22..., f4=[Row(field7=u'row2')])
Row(f1=None, f2=u'row3', f3=Row(field4=33, field5=[]), f4=None)
>>> srdd3 = sqlCtx.jsonRDD(json, srdd1.schema())
>>> sqlCtx.registerRDDAsTable(srdd3, "table2")
>>> srdd4 = sqlCtx.sql(
... "SELECT field1 AS f1, field2 as f2, field3 as f3, "
... "field6 as f4 from table2")
>>> for r in srdd4.collect():
... print r
Row(f1=1, f2=u'row1', f3=Row(field4=11, field5=None), f4=None)
Row(f1=2, f2=None, f3=Row(field4=22..., f4=[Row(field7=u'row2')])
Row(f1=None, f2=u'row3', f3=Row(field4=33, field5=[]), f4=None)
>>> schema = StructType([
... StructField("field2", StringType(), True),
... StructField("field3",
... StructType([
... StructField("field5",
... ArrayType(IntegerType(), False), True)]), False)])
>>> srdd5 = sqlCtx.jsonRDD(json, schema)
>>> sqlCtx.registerRDDAsTable(srdd5, "table3")
>>> srdd6 = sqlCtx.sql(
... "SELECT field2 AS f1, field3.field5 as f2, "
... "field3.field5[0] as f3 from table3")
>>> srdd6.collect()
[Row(f1=u'row1', f2=None,...Row(f1=u'row3', f2=[], f3=None)]
>>> sqlCtx.jsonRDD(sc.parallelize(['{}',
... '{"key0": {"key1": "value1"}}'])).collect()
[Row(key0=None), Row(key0=Row(key1=u'value1'))]
>>> sqlCtx.jsonRDD(sc.parallelize(['{"key0": null}',
... '{"key0": {"key1": "value1"}}'])).collect()
[Row(key0=None), Row(key0=Row(key1=u'value1'))]
"""
def func(iterator):
for x in iterator:
if not isinstance(x, basestring):
x = unicode(x)
if isinstance(x, unicode):
x = x.encode("utf-8")
yield x
keyed = rdd.mapPartitions(func)
keyed._bypass_serializer = True
jrdd = keyed._jrdd.map(self._jvm.BytesToString())
if schema is None:
srdd = self._ssql_ctx.jsonRDD(jrdd.rdd())
else:
scala_datatype = self._ssql_ctx.parseDataType(str(schema))
srdd = self._ssql_ctx.jsonRDD(jrdd.rdd(), scala_datatype)
return SchemaRDD(srdd.toJavaSchemaRDD(), self)
def sql(self, sqlQuery):
"""Return a L{SchemaRDD} representing the result of the given query.
>>> srdd = sqlCtx.inferSchema(rdd)
>>> sqlCtx.registerRDDAsTable(srdd, "table1")
>>> srdd2 = sqlCtx.sql("SELECT field1 AS f1, field2 as f2 from table1")
>>> srdd2.collect()
[Row(f1=1, f2=u'row1'), Row(f1=2, f2=u'row2'), Row(f1=3, f2=u'row3')]
"""
return SchemaRDD(self._ssql_ctx.sql(sqlQuery).toJavaSchemaRDD(), self)
def table(self, tableName):
"""Returns the specified table as a L{SchemaRDD}.
>>> srdd = sqlCtx.inferSchema(rdd)
>>> sqlCtx.registerRDDAsTable(srdd, "table1")
>>> srdd2 = sqlCtx.table("table1")
>>> sorted(srdd.collect()) == sorted(srdd2.collect())
True
"""
return SchemaRDD(self._ssql_ctx.table(tableName).toJavaSchemaRDD(), self)
def cacheTable(self, tableName):
"""Caches the specified table in-memory."""
self._ssql_ctx.cacheTable(tableName)
def uncacheTable(self, tableName):
"""Removes the specified table from the in-memory cache."""
self._ssql_ctx.uncacheTable(tableName)
class HiveContext(SQLContext):
"""A variant of Spark SQL that integrates with data stored in Hive.
Configuration for Hive is read from hive-site.xml on the classpath.
It supports running both SQL and HiveQL commands.
"""
def __init__(self, sparkContext, hiveContext=None):
"""Create a new HiveContext.
@param sparkContext: The SparkContext to wrap.
@param hiveContext: An optional JVM Scala HiveContext. If set, we do not instatiate a new
HiveContext in the JVM, instead we make all calls to this object.
"""
SQLContext.__init__(self, sparkContext)
if hiveContext:
self._scala_HiveContext = hiveContext
@property
def _ssql_ctx(self):
try:
if not hasattr(self, '_scala_HiveContext'):
self._scala_HiveContext = self._get_hive_ctx()
return self._scala_HiveContext
except Py4JError as e:
raise Exception("You must build Spark with Hive. "
"Export 'SPARK_HIVE=true' and run "
"sbt/sbt assembly", e)
def _get_hive_ctx(self):
return self._jvm.HiveContext(self._jsc.sc())
def hiveql(self, hqlQuery):
"""
DEPRECATED: Use sql()
"""
warnings.warn("hiveql() is deprecated as the sql function now parses using HiveQL by" +
"default. The SQL dialect for parsing can be set using 'spark.sql.dialect'",
DeprecationWarning)
return SchemaRDD(self._ssql_ctx.hiveql(hqlQuery).toJavaSchemaRDD(), self)
def hql(self, hqlQuery):
"""
DEPRECATED: Use sql()
"""
warnings.warn("hql() is deprecated as the sql function now parses using HiveQL by" +
"default. The SQL dialect for parsing can be set using 'spark.sql.dialect'",
DeprecationWarning)
return self.hiveql(hqlQuery)
class LocalHiveContext(HiveContext):
"""Starts up an instance of hive where metadata is stored locally.
An in-process metadata data is created with data stored in ./metadata.
Warehouse data is stored in in ./warehouse.
>>> import os
>>> hiveCtx = LocalHiveContext(sc)
>>> try:
... supress = hiveCtx.sql("DROP TABLE src")
... except Exception:
... pass
>>> kv1 = os.path.join(os.environ["SPARK_HOME"],
... 'examples/src/main/resources/kv1.txt')
>>> supress = hiveCtx.sql(
... "CREATE TABLE IF NOT EXISTS src (key INT, value STRING)")
>>> supress = hiveCtx.sql("LOAD DATA LOCAL INPATH '%s' INTO TABLE src"
... % kv1)
>>> results = hiveCtx.sql("FROM src SELECT value"
... ).map(lambda r: int(r.value.split('_')[1]))
>>> num = results.count()
>>> reduce_sum = results.reduce(lambda x, y: x + y)
>>> num
500
>>> reduce_sum
130091
"""
def __init__(self, sparkContext, sqlContext=None):
HiveContext.__init__(self, sparkContext, sqlContext)
warnings.warn("LocalHiveContext is deprecated. "
"Use HiveContext instead.", DeprecationWarning)
def _get_hive_ctx(self):
return self._jvm.LocalHiveContext(self._jsc.sc())
class TestHiveContext(HiveContext):
def _get_hive_ctx(self):
return self._jvm.TestHiveContext(self._jsc.sc())
def _create_row(fields, values):
row = Row(*values)
row.__FIELDS__ = fields
return row
class Row(tuple):
"""
A row in L{SchemaRDD}. The fields in it can be accessed like attributes.
Row can be used to create a row object by using named arguments,
the fields will be sorted by names.
>>> row = Row(name="Alice", age=11)
>>> row
Row(age=11, name='Alice')
>>> row.name, row.age
('Alice', 11)
Row also can be used to create another Row like class, then it
could be used to create Row objects, such as
>>> Person = Row("name", "age")
>>> Person
<Row(name, age)>
>>> Person("Alice", 11)
Row(name='Alice', age=11)
"""
def __new__(self, *args, **kwargs):
if args and kwargs:
raise ValueError("Can not use both args "
"and kwargs to create Row")
if args:
# create row class or objects
return tuple.__new__(self, args)
elif kwargs:
# create row objects
names = sorted(kwargs.keys())
values = tuple(kwargs[n] for n in names)
row = tuple.__new__(self, values)
row.__FIELDS__ = names
return row
else:
raise ValueError("No args or kwargs")
# let obect acs like class
def __call__(self, *args):
"""create new Row object"""
return _create_row(self, args)
def __getattr__(self, item):
if item.startswith("__"):
raise AttributeError(item)
try:
# it will be slow when it has many fields,
# but this will not be used in normal cases
idx = self.__FIELDS__.index(item)
return self[idx]
except IndexError:
raise AttributeError(item)
def __reduce__(self):
if hasattr(self, "__FIELDS__"):
return (_create_row, (self.__FIELDS__, tuple(self)))
else:
return tuple.__reduce__(self)
def __repr__(self):
if hasattr(self, "__FIELDS__"):
return "Row(%s)" % ", ".join("%s=%r" % (k, v)
for k, v in zip(self.__FIELDS__, self))
else:
return "<Row(%s)>" % ", ".join(self)
def inherit_doc(cls):
for name, func in vars(cls).items():
# only inherit docstring for public functions
if name.startswith("_"):
continue
if not func.__doc__:
for parent in cls.__bases__:
parent_func = getattr(parent, name, None)
if parent_func and getattr(parent_func, "__doc__", None):
func.__doc__ = parent_func.__doc__
break
return cls
@inherit_doc
class SchemaRDD(RDD):
"""An RDD of L{Row} objects that has an associated schema.
The underlying JVM object is a SchemaRDD, not a PythonRDD, so we can
utilize the relational query api exposed by Spark SQL.
For normal L{pyspark.rdd.RDD} operations (map, count, etc.) the
L{SchemaRDD} is not operated on directly, as it's underlying
implementation is an RDD composed of Java objects. Instead it is
converted to a PythonRDD in the JVM, on which Python operations can
be done.
This class receives raw tuples from Java but assigns a class to it in
all its data-collection methods (mapPartitionsWithIndex, collect, take,
etc) so that PySpark sees them as Row objects with named fields.
"""
def __init__(self, jschema_rdd, sql_ctx):
self.sql_ctx = sql_ctx
self._sc = sql_ctx._sc
clsName = jschema_rdd.getClass().getName()
assert clsName.endswith("JavaSchemaRDD"), "jschema_rdd must be JavaSchemaRDD"
self._jschema_rdd = jschema_rdd
self._id = None
self.is_cached = False
self.is_checkpointed = False
self.ctx = self.sql_ctx._sc
# the _jrdd is created by javaToPython(), serialized by pickle
self._jrdd_deserializer = BatchedSerializer(PickleSerializer())
@property
def _jrdd(self):
"""Lazy evaluation of PythonRDD object.
Only done when a user calls methods defined by the
L{pyspark.rdd.RDD} super class (map, filter, etc.).
"""
if not hasattr(self, '_lazy_jrdd'):
self._lazy_jrdd = self._jschema_rdd.baseSchemaRDD().javaToPython()
return self._lazy_jrdd
def id(self):
if self._id is None:
self._id = self._jrdd.id()
return self._id
def limit(self, num):
"""Limit the result count to the number specified.
>>> srdd = sqlCtx.inferSchema(rdd)
>>> srdd.limit(2).collect()
[Row(field1=1, field2=u'row1'), Row(field1=2, field2=u'row2')]
>>> srdd.limit(0).collect()
[]
"""
rdd = self._jschema_rdd.baseSchemaRDD().limit(num).toJavaSchemaRDD()
return SchemaRDD(rdd, self.sql_ctx)
def saveAsParquetFile(self, path):
"""Save the contents as a Parquet file, preserving the schema.
Files that are written out using this method can be read back in as
a SchemaRDD using the L{SQLContext.parquetFile} method.
>>> import tempfile, shutil
>>> parquetFile = tempfile.mkdtemp()
>>> shutil.rmtree(parquetFile)
>>> srdd = sqlCtx.inferSchema(rdd)
>>> srdd.saveAsParquetFile(parquetFile)
>>> srdd2 = sqlCtx.parquetFile(parquetFile)
>>> sorted(srdd2.collect()) == sorted(srdd.collect())
True
"""
self._jschema_rdd.saveAsParquetFile(path)
def registerTempTable(self, name):
"""Registers this RDD as a temporary table using the given name.
The lifetime of this temporary table is tied to the L{SQLContext}
that was used to create this SchemaRDD.
>>> srdd = sqlCtx.inferSchema(rdd)
>>> srdd.registerTempTable("test")
>>> srdd2 = sqlCtx.sql("select * from test")
>>> sorted(srdd.collect()) == sorted(srdd2.collect())
True
"""
self._jschema_rdd.registerTempTable(name)
def registerAsTable(self, name):
"""DEPRECATED: use registerTempTable() instead"""
warnings.warn("Use registerTempTable instead of registerAsTable.", DeprecationWarning)
self.registerTempTable(name)
def insertInto(self, tableName, overwrite=False):
"""Inserts the contents of this SchemaRDD into the specified table.
Optionally overwriting any existing data.
"""
self._jschema_rdd.insertInto(tableName, overwrite)
def saveAsTable(self, tableName):
"""Creates a new table with the contents of this SchemaRDD."""
self._jschema_rdd.saveAsTable(tableName)
def schema(self):
"""Returns the schema of this SchemaRDD (represented by
a L{StructType})."""
return _parse_datatype_string(self._jschema_rdd.baseSchemaRDD().schema().toString())
def schemaString(self):
"""Returns the output schema in the tree format."""
return self._jschema_rdd.schemaString()
def printSchema(self):
"""Prints out the schema in the tree format."""
print self.schemaString()
def count(self):
"""Return the number of elements in this RDD.
Unlike the base RDD implementation of count, this implementation
leverages the query optimizer to compute the count on the SchemaRDD,
which supports features such as filter pushdown.
>>> srdd = sqlCtx.inferSchema(rdd)
>>> srdd.count()
3L
>>> srdd.count() == srdd.map(lambda x: x).count()
True
"""
return self._jschema_rdd.count()
def collect(self):
"""Return a list that contains all of the rows in this RDD.
Each object in the list is a Row, the fields can be accessed as
attributes.
Unlike the base RDD implementation of collect, this implementation
leverages the query optimizer to perform a collect on the SchemaRDD,
which supports features such as filter pushdown.
>>> srdd = sqlCtx.inferSchema(rdd)
>>> srdd.collect()
[Row(field1=1, field2=u'row1'), ..., Row(field1=3, field2=u'row3')]
"""
with SCCallSiteSync(self.context) as css:
bytesInJava = self._jschema_rdd.baseSchemaRDD().collectToPython().iterator()
cls = _create_cls(self.schema())
return map(cls, self._collect_iterator_through_file(bytesInJava))
def take(self, num):
"""Take the first num rows of the RDD.
Each object in the list is a Row, the fields can be accessed as
attributes.
Unlike the base RDD implementation of take, this implementation
leverages the query optimizer to perform a collect on a SchemaRDD,
which supports features such as filter pushdown.
>>> srdd = sqlCtx.inferSchema(rdd)
>>> srdd.take(2)
[Row(field1=1, field2=u'row1'), Row(field1=2, field2=u'row2')]
"""
return self.limit(num).collect()
# Convert each object in the RDD to a Row with the right class
# for this SchemaRDD, so that fields can be accessed as attributes.
def mapPartitionsWithIndex(self, f, preservesPartitioning=False):
"""
Return a new RDD by applying a function to each partition of this RDD,
while tracking the index of the original partition.
>>> rdd = sc.parallelize([1, 2, 3, 4], 4)
>>> def f(splitIndex, iterator): yield splitIndex
>>> rdd.mapPartitionsWithIndex(f).sum()
6
"""
rdd = RDD(self._jrdd, self._sc, self._jrdd_deserializer)
schema = self.schema()
def applySchema(_, it):
cls = _create_cls(schema)
return itertools.imap(cls, it)
objrdd = rdd.mapPartitionsWithIndex(applySchema, preservesPartitioning)
return objrdd.mapPartitionsWithIndex(f, preservesPartitioning)
# We override the default cache/persist/checkpoint behavior
# as we want to cache the underlying SchemaRDD object in the JVM,
# not the PythonRDD checkpointed by the super class
def cache(self):
self.is_cached = True
self._jschema_rdd.cache()
return self
def persist(self, storageLevel=StorageLevel.MEMORY_ONLY_SER):
self.is_cached = True
javaStorageLevel = self.ctx._getJavaStorageLevel(storageLevel)
self._jschema_rdd.persist(javaStorageLevel)
return self
def unpersist(self, blocking=True):
self.is_cached = False
self._jschema_rdd.unpersist(blocking)
return self
def checkpoint(self):
self.is_checkpointed = True
self._jschema_rdd.checkpoint()
def isCheckpointed(self):
return self._jschema_rdd.isCheckpointed()
def getCheckpointFile(self):
checkpointFile = self._jschema_rdd.getCheckpointFile()
if checkpointFile.isPresent():
return checkpointFile.get()
def coalesce(self, numPartitions, shuffle=False):
rdd = self._jschema_rdd.coalesce(numPartitions, shuffle)
return SchemaRDD(rdd, self.sql_ctx)
def distinct(self, numPartitions=None):
if numPartitions is None:
rdd = self._jschema_rdd.distinct()
else:
rdd = self._jschema_rdd.distinct(numPartitions)
return SchemaRDD(rdd, self.sql_ctx)
def intersection(self, other):
if (other.__class__ is SchemaRDD):
rdd = self._jschema_rdd.intersection(other._jschema_rdd)
return SchemaRDD(rdd, self.sql_ctx)
else:
raise ValueError("Can only intersect with another SchemaRDD")
def repartition(self, numPartitions):
rdd = self._jschema_rdd.repartition(numPartitions)
return SchemaRDD(rdd, self.sql_ctx)
def subtract(self, other, numPartitions=None):
if (other.__class__ is SchemaRDD):
if numPartitions is None:
rdd = self._jschema_rdd.subtract(other._jschema_rdd)
else:
rdd = self._jschema_rdd.subtract(other._jschema_rdd,
numPartitions)
return SchemaRDD(rdd, self.sql_ctx)
else:
raise ValueError("Can only subtract another SchemaRDD")
def _test():
import doctest
from array import array
from pyspark.context import SparkContext
# let doctest run in pyspark.sql, so DataTypes can be picklable
import pyspark.sql
from pyspark.sql import Row, SQLContext
globs = pyspark.sql.__dict__.copy()
# The small batch size here ensures that we see multiple batches,
# even in these small test examples:
sc = SparkContext('local[4]', 'PythonTest', batchSize=2)
globs['sc'] = sc
globs['sqlCtx'] = SQLContext(sc)
globs['rdd'] = sc.parallelize(
[Row(field1=1, field2="row1"),
Row(field1=2, field2="row2"),
Row(field1=3, field2="row3")]
)
jsonStrings = [
'{"field1": 1, "field2": "row1", "field3":{"field4":11}}',
'{"field1" : 2, "field3":{"field4":22, "field5": [10, 11]},'
'"field6":[{"field7": "row2"}]}',
'{"field1" : null, "field2": "row3", '
'"field3":{"field4":33, "field5": []}}'
]
globs['jsonStrings'] = jsonStrings
globs['json'] = sc.parallelize(jsonStrings)
(failure_count, test_count) = doctest.testmod(
pyspark.sql, globs=globs, optionflags=doctest.ELLIPSIS)
globs['sc'].stop()
if failure_count:
exit(-1)
if __name__ == "__main__":
_test()
|
[] |
[] |
[
"SPARK_HOME"
] |
[]
|
["SPARK_HOME"]
|
python
| 1 | 0 | |
homeassistant/components/sensor/etherscan.py
|
"""Support for Etherscan sensors."""
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION, CONF_ADDRESS, CONF_NAME, CONF_TOKEN)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
REQUIREMENTS = ['python-etherscan-api==0.0.3']
ATTRIBUTION = "Data provided by etherscan.io"
CONF_TOKEN_ADDRESS = 'token_address'
SCAN_INTERVAL = timedelta(minutes=5)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_ADDRESS): cv.string,
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_TOKEN): cv.string,
vol.Optional(CONF_TOKEN_ADDRESS): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Etherscan.io sensors."""
address = config.get(CONF_ADDRESS)
name = config.get(CONF_NAME)
token = config.get(CONF_TOKEN)
token_address = config.get(CONF_TOKEN_ADDRESS)
if token:
token = token.upper()
if not name:
name = "%s Balance" % token
if not name:
name = "ETH Balance"
add_entities([EtherscanSensor(name, address, token, token_address)], True)
class EtherscanSensor(Entity):
"""Representation of an Etherscan.io sensor."""
def __init__(self, name, address, token, token_address):
"""Initialize the sensor."""
self._name = name
self._address = address
self._token_address = token_address
self._token = token
self._state = None
self._unit_of_measurement = self._token or "ETH"
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement this sensor expresses itself in."""
return self._unit_of_measurement
@property
def device_state_attributes(self):
"""Return the state attributes of the sensor."""
return {ATTR_ATTRIBUTION: ATTRIBUTION}
def update(self):
"""Get the latest state of the sensor."""
from pyetherscan import get_balance
if self._token_address:
self._state = get_balance(self._address, self._token_address)
elif self._token:
self._state = get_balance(self._address, self._token)
else:
self._state = get_balance(self._address)
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
kubetest/kind/kind.go
|
/*
Copyright 2018 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 kind
import (
"crypto/sha256"
"encoding/hex"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"k8s.io/test-infra/kubetest/process"
)
const (
// note: this is under the user's home
kindBinarySubDir = ".kubetest/kind"
kindNodeImageLatest = "kindest/node:latest"
kindBinaryBuild = "build"
kindBinaryStable = "stable"
// If a new version of kind is released this value has to be updated.
kindBinaryStableTag = "v0.7.0"
kindClusterNameDefault = "kind-kubetest"
flagLogLevel = "--verbosity=9"
)
var (
kindConfigPath = flag.String("kind-config-path", "",
"(kind only) Path to the kind configuration file.")
kindKubeconfigPath = flag.String("kind-kubeconfig-path", "",
"(kind only) Path to the kubeconfig file for kind create cluster command.")
kindBaseImage = flag.String("kind-base-image", "",
"(kind only) name:tag of the base image to use for building the node image for kind.")
kindBinaryVersion = flag.String("kind-binary-version", kindBinaryStable,
fmt.Sprintf("(kind only) This flag can be either %q (build from source) "+
"or %q (download a stable binary).", kindBinaryBuild, kindBinaryStable))
kindClusterName = flag.String("kind-cluster-name", kindClusterNameDefault,
"(kind only) Name of the kind cluster.")
kindNodeImage = flag.String("kind-node-image", "", "(kind only) name:tag of the node image to start the cluster. If build is enabled, this is ignored and built image is used.")
)
var (
kindBinaryStableHashes = map[string]string{
"kind-linux-amd64": "9a64f1774cdf24dad5f92e1299058b371c4e3f09d2f9eb281e91ed0777bd1e13",
"kind-darwin-amd64": "b6a8fe2b3b53930a1afa4f91b033cdc24b0f6c628d993abaa9e40b57d261162a",
"kind-windows-amd64": "df327d1e7f8bb41dfd5b1a69c5bc7a8d4bad95bb933562ca367a3a45b6c6ca04",
}
)
// Deployer is an object the satisfies the kubetest main deployer interface.
type Deployer struct {
control *process.Control
buildType string
configPath string
importPathK8s string
importPathKind string
kindBinaryDir string
kindBinaryVersion string
kindBinaryPath string
kindKubeconfigPath string
kindNodeImage string
kindBaseImage string
kindClusterName string
}
// NewDeployer creates a new kind deployer.
func NewDeployer(ctl *process.Control, buildType string) (*Deployer, error) {
k, err := initializeDeployer(ctl, buildType)
if err != nil {
return nil, err
}
return k, nil
}
// initializeDeployer initializers the kind deployer flags.
func initializeDeployer(ctl *process.Control, buildType string) (*Deployer, error) {
if ctl == nil {
return nil, fmt.Errorf("kind deployer received nil Control")
}
// get the user's HOME
kindBinaryDir := filepath.Join(os.Getenv("HOME"), kindBinarySubDir)
// Ensure the kind binary dir is added in $PATH.
err := os.MkdirAll(kindBinaryDir, 0770)
if err != nil {
return nil, err
}
path := os.Getenv("PATH")
if !strings.Contains(path, kindBinaryDir) {
if err := os.Setenv("PATH", kindBinaryDir+":"+path); err != nil {
return nil, err
}
}
kubeconfigPath := *kindKubeconfigPath
if kubeconfigPath == "" {
// Create directory for the cluster kube config
kindClusterDir := filepath.Join(kindBinaryDir, *kindClusterName)
if err := os.MkdirAll(kindClusterDir, 0770); err != nil {
return nil, err
}
kubeconfigPath = filepath.Join(kindClusterDir, "kubeconfig")
}
d := &Deployer{
control: ctl,
buildType: buildType,
configPath: *kindConfigPath,
kindBinaryDir: kindBinaryDir,
kindBinaryPath: filepath.Join(kindBinaryDir, "kind"),
kindBinaryVersion: *kindBinaryVersion,
kindKubeconfigPath: kubeconfigPath,
kindNodeImage: *kindNodeImage,
kindClusterName: *kindClusterName,
}
// Obtain the import paths for k8s and kind
d.importPathK8s, err = d.getImportPath("k8s.io/kubernetes")
if err != nil {
return nil, err
}
d.importPathKind, err = d.getImportPath("sigs.k8s.io/kind")
if err != nil {
return nil, err
}
if kindBaseImage != nil {
d.kindBaseImage = *kindBaseImage
}
// ensure we have the kind binary
if err := d.prepareKindBinary(); err != nil {
return nil, err
}
return d, nil
}
// getImportPath does a naive concat between GOPATH, "src" and a user provided path.
func (d *Deployer) getImportPath(path string) (string, error) {
o, err := d.control.Output(exec.Command("go", "env", "GOPATH"))
if err != nil {
return "", err
}
trimmed := strings.TrimSuffix(string(o), "\n")
log.Printf("kind.go:getImportPath(): %s", trimmed)
return filepath.Join(trimmed, "src", path), nil
}
// setKubeConfigEnv sets the KUBECONFIG environment variable.
func (d *Deployer) setKubeConfigEnv() error {
log.Println("kind.go:setKubeConfigEnv()")
return os.Setenv("KUBECONFIG", d.kindKubeconfigPath)
}
// prepareKindBinary either builds kind from source or pulls a binary from GitHub.
func (d *Deployer) prepareKindBinary() error {
log.Println("kind.go:prepareKindBinary()")
switch d.kindBinaryVersion {
case kindBinaryBuild:
log.Println("Building a kind binary from source.")
// Build the kind binary.
cmd := exec.Command("make", "install", "INSTALL_DIR="+d.kindBinaryDir)
cmd.Dir = d.importPathKind
if err := d.control.FinishRunning(cmd); err != nil {
return err
}
case kindBinaryStable:
// ensure a stable kind binary.
kindPlatformBinary := fmt.Sprintf("kind-%s-%s", runtime.GOOS, runtime.GOARCH)
if haveStableBinary(d.kindBinaryPath, kindPlatformBinary) {
log.Printf("Found stable kind binary at %q", d.kindBinaryPath)
return nil
}
// we don't have it, so download it
binary := fmt.Sprintf("kind-%s-%s", runtime.GOOS, runtime.GOARCH)
url := fmt.Sprintf("https://github.com/kubernetes-sigs/kind/releases/download/%s/%s", kindBinaryStableTag, binary)
log.Printf("Downloading a stable kind binary from GitHub: %s, tag: %s", binary, kindBinaryStableTag)
f, err := os.OpenFile(d.kindBinaryPath, os.O_RDWR|os.O_CREATE, 0770)
if err != nil {
return err
}
defer f.Close()
if err := downloadFromURL(url, f); err != nil {
return err
}
default:
return fmt.Errorf("unknown kind binary version value: %s", d.kindBinaryVersion)
}
return nil
}
// Build handles building kubernetes / kubectl / the node image.
func (d *Deployer) Build() error {
log.Println("kind.go:Build()")
// Adapt the build type if needed.
var buildType string
var buildNodeImage string
switch d.buildType {
case "":
// The default option is to use a pre-build image.
log.Println("Skipping the kind node image build.")
return nil
case "quick":
// This is the default build type in kind.
buildType = "docker"
buildNodeImage = kindNodeImageLatest
default:
// Other types and 'bazel' are handled transparently here.
buildType = d.buildType
buildNodeImage = kindNodeImageLatest
}
args := []string{"build", "node-image", "--type=" + buildType, flagLogLevel, "--kube-root=" + d.importPathK8s}
if buildNodeImage != "" {
args = append(args, "--image="+buildNodeImage)
// override user-specified node image
d.kindNodeImage = buildNodeImage
}
if d.kindBaseImage != "" {
args = append(args, "--base-image="+d.kindBaseImage)
}
// Build the node image (including kubernetes)
cmd := exec.Command("kind", args...)
if err := d.control.FinishRunning(cmd); err != nil {
return err
}
// Build binaries for the host, including kubectl, ginkgo, e2e.test
if d.buildType != "bazel" {
cmd := exec.Command(
"make", "all",
"WHAT=cmd/kubectl test/e2e/e2e.test vendor/github.com/onsi/ginkgo/ginkgo",
)
cmd.Dir = d.importPathK8s
if err := d.control.FinishRunning(cmd); err != nil {
return err
}
// Copy kubectl to the kind binary path.
cmd = exec.Command("cp", "-f", "./_output/local/go/bin/kubectl", d.kindBinaryDir)
cmd.Dir = d.importPathK8s
if err := d.control.FinishRunning(cmd); err != nil {
return err
}
} else {
// make build
cmd := exec.Command(
"bazel", "build",
"//cmd/kubectl", "//test/e2e:e2e.test",
"//vendor/github.com/onsi/ginkgo/ginkgo",
)
cmd.Dir = d.importPathK8s
if err := d.control.FinishRunning(cmd); err != nil {
return err
}
// Copy kubectl to the kind binary path.
kubectlPath := fmt.Sprintf(
"./bazel-bin/cmd/kubectl/%s_%s_pure_stripped/kubectl",
runtime.GOOS, runtime.GOARCH,
)
cmd = exec.Command("cp", "-f", kubectlPath, d.kindBinaryDir)
cmd.Dir = d.importPathK8s
if err := d.control.FinishRunning(cmd); err != nil {
return err
}
}
return nil
}
// Up creates a kind cluster. Allows passing node image and config.
func (d *Deployer) Up() error {
log.Println("kind.go:Up()")
args := []string{"create", "cluster", "--retain", "--wait=1m", flagLogLevel}
// Handle the config flag.
if d.configPath != "" {
args = append(args, "--config="+d.configPath)
}
// Handle the node image flag if we built a new node image.
if d.kindNodeImage != "" {
args = append(args, "--image="+d.kindNodeImage)
}
// Use a specific cluster name.
if d.kindClusterName != "" {
args = append(args, "--name="+d.kindClusterName)
}
// Use specific path for the kubeconfig
if d.kindKubeconfigPath != "" {
args = append(args, "--kubeconfig="+d.kindKubeconfigPath)
}
// Build the kind cluster.
cmd := exec.Command("kind", args...)
if err := d.control.FinishRunning(cmd); err != nil {
return err
}
log.Println("*************************************************************************************************")
log.Println("Cluster is UP")
log.Printf("Run: \"export KUBECONFIG=%s\" to access to it\n", d.kindKubeconfigPath)
log.Println("*************************************************************************************************")
return nil
}
// IsUp verifies if the cluster created by Up() is functional.
func (d *Deployer) IsUp() error {
log.Println("kind.go:IsUp()")
// Check if kubectl reports nodes.
cmd, err := d.KubectlCommand()
if err != nil {
return err
}
cmd.Args = append(cmd.Args, []string{"get", "nodes", "--no-headers"}...)
o, err := d.control.Output(cmd)
if err != nil {
return err
}
trimmed := strings.TrimSpace(string(o))
n := 0
if trimmed != "" {
n = len(strings.Split(trimmed, "\n"))
}
if n <= 0 {
return fmt.Errorf("cluster found, but %d nodes reported", n)
}
return nil
}
// DumpClusterLogs dumps the logs for this cluster in localPath.
func (d *Deployer) DumpClusterLogs(localPath, gcsPath string) error {
log.Println("kind.go:DumpClusterLogs()")
args := []string{"export", "logs", localPath, flagLogLevel}
// Use a specific cluster name.
if d.kindClusterName != "" {
args = append(args, "--name="+d.kindClusterName)
}
cmd := exec.Command("kind", args...)
if err := d.control.FinishRunning(cmd); err != nil {
log.Printf("kind.go:DumpClusterLogs(): ignoring error: %v", err)
}
return nil
}
// TestSetup is a NO-OP in this deployer.
func (d *Deployer) TestSetup() error {
log.Println("kind.go:TestSetup()")
// set conformance env so ginkgo.sh etc won't try to do provider setup
if err := os.Setenv("KUBERNETES_CONFORMANCE_TEST", "y"); err != nil {
return err
}
// Proceed only if a cluster exists.
exists, err := d.clusterExists()
if err != nil {
return err
}
if !exists {
log.Printf("kind.go:TestSetup(): no such cluster %q; skipping the setup of KUBECONFIG!", d.kindClusterName)
return nil
}
// set KUBECONFIG
if err = d.setKubeConfigEnv(); err != nil {
return err
}
return nil
}
// clusterExists checks if a kind cluster with 'name' exists
func (d *Deployer) clusterExists() (bool, error) {
log.Println("kind.go:clusterExists()")
cmd := exec.Command("kind")
cmd.Args = append(cmd.Args, []string{"get", "clusters"}...)
out, err := d.control.Output(cmd)
if err != nil {
return false, err
}
lines := strings.Split(string(out), "\n")
for _, line := range lines {
if line == d.kindClusterName {
log.Printf("kind.go:clusterExists(): found %q", d.kindClusterName)
return true, nil
}
}
return false, nil
}
// Down tears down the cluster.
func (d *Deployer) Down() error {
log.Println("kind.go:Down()")
// Proceed only if a cluster exists.
exists, err := d.clusterExists()
if err != nil {
return err
}
if !exists {
log.Printf("kind.go:Down(): no such cluster %q; skipping 'delete'!", d.kindClusterName)
return nil
}
log.Printf("kind.go:Down(): deleting cluster: %s", d.kindClusterName)
args := []string{"delete", "cluster", flagLogLevel}
// Use a specific cluster name.
if d.kindClusterName != "" {
args = append(args, "--name="+d.kindClusterName)
}
// Delete the cluster.
cmd := exec.Command("kind", args...)
if err := d.control.FinishRunning(cmd); err != nil {
return err
}
if d.kindClusterName != "" {
kindClusterDir := filepath.Join(d.kindBinaryDir, d.kindClusterName)
if _, err := os.Stat(kindClusterDir); !os.IsNotExist(err) {
if err := os.RemoveAll(kindClusterDir); err != nil {
return err
}
}
}
return nil
}
// GetClusterCreated is unimplemented.GetClusterCreated
func (d *Deployer) GetClusterCreated(gcpProject string) (time.Time, error) {
log.Println("kind.go:GetClusterCreated()")
return time.Time{}, errors.New("not implemented")
}
// KubectlCommand returns the exec.Cmd command for kubectl.
func (d *Deployer) KubectlCommand() (*exec.Cmd, error) {
log.Println("kind.go:KubectlCommand()")
if err := d.setKubeConfigEnv(); err != nil {
return nil, err
}
// Avoid using ./cluster/kubectl.sh
// TODO(bentheelder): cache this
return exec.Command("kubectl"), nil
}
// downloadFromURL downloads from a url to f
func downloadFromURL(url string, f *os.File) error {
log.Printf("kind.go:downloadFromURL(): %s", url)
// TODO(bentheelder): is this long enough?
timeout := time.Duration(60 * time.Second)
client := http.Client{
Timeout: timeout,
}
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
defer f.Sync()
_, err = io.Copy(f, resp.Body)
return err
}
// returns true if the binary at expected path exists and
// matches the expected hash of kindPlatformBinary
func haveStableBinary(expectedPath, kindPlatformBinary string) bool {
if _, err := os.Stat(expectedPath); os.IsNotExist(err) {
log.Printf("kind binary not present at %s", expectedPath)
return false
}
expectedHash, ok := kindBinaryStableHashes[kindPlatformBinary]
if !ok {
return false
}
hash, err := hashFile(expectedPath)
if err != nil {
return false
}
hashMatches := expectedHash == hash
if !hashMatches {
log.Printf("kind binary present with hash %q at %q, but expected hash %q", hash, expectedPath, expectedHash)
}
return hashMatches
}
// computes the sha256sum of the file at path
func hashFile(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
|
[
"\"HOME\"",
"\"PATH\""
] |
[] |
[
"HOME",
"PATH"
] |
[]
|
["HOME", "PATH"]
|
go
| 2 | 0 | |
pkg/jx/cmd/step/pr/step_pr_labels.go
|
package pr
import (
"fmt"
"github.com/jenkins-x/jx/pkg/jx/cmd/helper"
"os"
"regexp"
"strconv"
"strings"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/jenkins-x/jx/pkg/jx/cmd/opts"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/log"
)
// DefaultPrefix for all PR labels environment keys
const DefaultPrefix = "JX_PR_LABELS"
// StepPRLabelsOptions holds the options for the cmd
type StepPRLabelsOptions struct {
*opts.CommonOptions
Dir string
Prefix string
PullRequest string
}
var (
labelLong = templates.LongDesc(`
Creates environment variables from the labels in a pull request.
Environment variables are prefixed per default with ` + DefaultPrefix + `.
You can use the '--prefix' argument to set a different prefix.
`)
labelExample = templates.Examples(`
# List all labels of a given pull-request
jx step pr labels
# List all labels of a given pull-request using a custom prefix
jx step pr --prefix PRL
# List all labels of a given pull-request using a custom pull-request number
jx step pr --pr PR-34
jx step pr --pr 34
`)
)
// NewCmdStepPRLabels creates the new cmd
func NewCmdStepPRLabels(commonOpts *opts.CommonOptions) *cobra.Command {
options := &StepPRLabelsOptions{
CommonOptions: commonOpts,
}
cmd := &cobra.Command{
Use: "labels",
Short: "List all labels of a given pull-request",
Long: labelLong,
Example: labelExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
helper.CheckErr(err)
},
}
cmd.Flags().StringVarP(&options.PullRequest, "pr", "", "", "Git Pull Request number")
cmd.Flags().StringVarP(&options.Prefix, "prefix", "p", "", "Environment variable prefix")
return cmd
}
// Run implements the execution
func (o *StepPRLabelsOptions) Run() error {
gitInfo, provider, _, err := o.CreateGitProvider(o.Dir)
if err != nil {
return err
}
if provider == nil {
return fmt.Errorf("No Git provider could be found. Are you in a directory containing a `.git/config` file?")
}
if o.PullRequest == "" {
o.PullRequest = strings.TrimPrefix(os.Getenv("BRANCH_NAME"), "PR-")
}
if o.Prefix == "" {
o.Prefix = DefaultPrefix
}
prNum, err := strconv.Atoi(o.PullRequest)
if err != nil {
log.Warn("Unable to convert PR " + o.PullRequest + " to a number" + "\n")
}
pr, err := provider.GetPullRequest(gitInfo.Organisation, gitInfo, prNum)
if err != nil {
return errors.Wrapf(err, "failed to find PullRequest %d", prNum)
}
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
return errors.Wrapf(err, "failed to create regex %v", reg)
}
for _, v := range pr.Labels {
envKey := reg.ReplaceAllString(*v.Name, "_")
log.Infof("%v_%v='%v'\n", o.Prefix, strings.ToUpper(envKey), *v.Name)
}
return nil
}
|
[
"\"BRANCH_NAME\""
] |
[] |
[
"BRANCH_NAME"
] |
[]
|
["BRANCH_NAME"]
|
go
| 1 | 0 | |
wgengine/magicsock/magicsock.go
|
// Copyright (c) 2019 Tailscale Inc & 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 magicsock implements a socket that can change its communication path while
// in use, actively searching for the best way to communicate.
package magicsock
import (
"bufio"
"context"
crand "crypto/rand"
"encoding/binary"
"errors"
"expvar"
"fmt"
"hash/fnv"
"math"
"math/rand"
"net"
"os"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/tailscale/wireguard-go/conn"
"go4.org/mem"
"golang.org/x/crypto/nacl/box"
"golang.org/x/time/rate"
"inet.af/netaddr"
"tailscale.com/control/controlclient"
"tailscale.com/derp"
"tailscale.com/derp/derphttp"
"tailscale.com/disco"
"tailscale.com/health"
"tailscale.com/ipn/ipnstate"
"tailscale.com/logtail/backoff"
"tailscale.com/net/dnscache"
"tailscale.com/net/interfaces"
"tailscale.com/net/netcheck"
"tailscale.com/net/netns"
"tailscale.com/net/portmapper"
"tailscale.com/net/stun"
"tailscale.com/syncs"
"tailscale.com/tailcfg"
"tailscale.com/tstime"
"tailscale.com/types/key"
"tailscale.com/types/logger"
"tailscale.com/types/netmap"
"tailscale.com/types/nettype"
"tailscale.com/types/pad32"
"tailscale.com/types/wgkey"
"tailscale.com/version"
"tailscale.com/wgengine/monitor"
"tailscale.com/wgengine/wgcfg"
)
// Various debugging and experimental tweakables, set by environment
// variable.
var (
// logPacketDests prints the known addresses for a peer every time
// they change, in the legacy (non-discovery) endpoint code only.
logPacketDests, _ = strconv.ParseBool(os.Getenv("TS_DEBUG_LOG_PACKET_DESTS"))
// debugDisco prints verbose logs of active discovery events as
// they happen.
debugDisco, _ = strconv.ParseBool(os.Getenv("TS_DEBUG_DISCO"))
// debugOmitLocalAddresses removes all local interface addresses
// from magicsock's discovered local endpoints. Used in some tests.
debugOmitLocalAddresses, _ = strconv.ParseBool(os.Getenv("TS_DEBUG_OMIT_LOCAL_ADDRS"))
// debugUseDerpRoute temporarily (2020-03-22) controls whether DERP
// reverse routing is enabled (Issue 150). It will become always true
// later.
debugUseDerpRouteEnv = os.Getenv("TS_DEBUG_ENABLE_DERP_ROUTE")
debugUseDerpRoute, _ = strconv.ParseBool(debugUseDerpRouteEnv)
// logDerpVerbose logs all received DERP packets, including their
// full payload.
logDerpVerbose, _ = strconv.ParseBool(os.Getenv("TS_DEBUG_DERP"))
// debugReSTUNStopOnIdle unconditionally enables the "shut down
// STUN if magicsock is idle" behavior that normally only triggers
// on mobile devices, lowers the shutdown interval, and logs more
// verbosely about idle measurements.
debugReSTUNStopOnIdle, _ = strconv.ParseBool(os.Getenv("TS_DEBUG_RESTUN_STOP_ON_IDLE"))
)
// useDerpRoute reports whether magicsock should enable the DERP
// return path optimization (Issue 150).
func useDerpRoute() bool {
if debugUseDerpRouteEnv != "" {
return debugUseDerpRoute
}
ob := controlclient.DERPRouteFlag()
if v, ok := ob.Get(); ok {
return v
}
return false
}
// inTest reports whether the running program is a test that set the
// IN_TS_TEST environment variable.
//
// Unlike the other debug tweakables above, this one needs to be
// checked every time at runtime, because tests set this after program
// startup.
func inTest() bool {
inTest, _ := strconv.ParseBool(os.Getenv("IN_TS_TEST"))
return inTest
}
// A Conn routes UDP packets and actively manages a list of its endpoints.
// It implements wireguard/conn.Bind.
type Conn struct {
// This block mirrors the contents and field order of the Options
// struct. Initialized once at construction, then constant.
logf logger.Logf
port uint16 // the preferred port from opts.Port; 0 means auto
epFunc func(endpoints []string)
derpActiveFunc func()
idleFunc func() time.Duration // nil means unknown
packetListener nettype.PacketListener
noteRecvActivity func(tailcfg.DiscoKey) // or nil, see Options.NoteRecvActivity
simulatedNetwork bool
disableLegacy bool
// ================================================================
// No locking required to access these fields, either because
// they're static after construction, or are wholly owned by a
// single goroutine.
connCtx context.Context // closed on Conn.Close
connCtxCancel func() // closes connCtx
donec <-chan struct{} // connCtx.Done()'s to avoid context.cancelCtx.Done()'s mutex per call
// pconn4 and pconn6 are the underlying UDP sockets used to
// send/receive packets for wireguard and other magicsock
// protocols.
pconn4 *RebindingUDPConn
pconn6 *RebindingUDPConn
// netChecker is the prober that discovers local network
// conditions, including the closest DERP relay and NAT mappings.
netChecker *netcheck.Client
// portMapper is the NAT-PMP/PCP/UPnP prober/client, for requesting
// port mappings from NAT devices.
portMapper *portmapper.Client
// sendLogLimit is a rate limiter for errors logged in the (hot)
// packet sending codepath. It's so that, if magicsock gets into a
// bad state, we don't spam one error per wireguard packet being
// transmitted.
// TODO(danderson): now that we have global rate-limiting, is this still useful?
sendLogLimit *rate.Limiter
// stunReceiveFunc holds the current STUN packet processing func.
// Its Loaded value is always non-nil.
stunReceiveFunc atomic.Value // of func(p []byte, fromAddr *net.UDPAddr)
// derpRecvCh is used by ReceiveIPv4 to read DERP messages.
derpRecvCh chan derpReadResult
_ pad32.Four
// derpRecvCountAtomic is how many derpRecvCh sends are pending.
// It's incremented by runDerpReader whenever a DERP message
// arrives and decremented when they're read.
derpRecvCountAtomic int64
// ippEndpoint4 and ippEndpoint6 are owned by ReceiveIPv4 and
// ReceiveIPv6, respectively, to cache an IPPort->endpoint for
// hot flows.
ippEndpoint4, ippEndpoint6 ippEndpointCache
// ============================================================
mu sync.Mutex // guards all following fields; see userspaceEngine lock ordering rules
muCond *sync.Cond
started bool // Start was called
closed bool // Close was called
// derpCleanupTimer is the timer that fires to occasionally clean
// up idle DERP connections. It's only used when there is a non-home
// DERP connection in use.
derpCleanupTimer *time.Timer
// derpCleanupTimerArmed is whether derpCleanupTimer is
// scheduled to fire within derpCleanStaleInterval.
derpCleanupTimerArmed bool
// periodicReSTUNTimer, when non-nil, is an AfterFunc timer
// that will call Conn.doPeriodicSTUN.
periodicReSTUNTimer *time.Timer
// endpointsUpdateActive indicates that updateEndpoints is
// currently running. It's used to deduplicate concurrent endpoint
// update requests.
endpointsUpdateActive bool
// wantEndpointsUpdate, if non-empty, means that a new endpoints
// update should begin immediately after the currently-running one
// completes. It can only be non-empty if
// endpointsUpdateActive==true.
wantEndpointsUpdate string // true if non-empty; string is reason
// lastEndpoints records the endpoints found during the previous
// endpoint discovery. It's used to avoid duplicate endpoint
// change notifications.
lastEndpoints []string
// lastEndpointsTime is the last time the endpoints were updated,
// even if there was no change.
lastEndpointsTime time.Time
// onEndpointRefreshed are funcs to run (in their own goroutines)
// when endpoints are refreshed.
onEndpointRefreshed map[*discoEndpoint]func()
// peerSet is the set of peers that are currently configured in
// WireGuard. These are not used to filter inbound or outbound
// traffic at all, but only to track what state can be cleaned up
// in other maps below that are keyed by peer public key.
peerSet map[key.Public]struct{}
// discoPrivate is the private naclbox key used for active
// discovery traffic. It's created once near (but not during)
// construction.
discoPrivate key.Private
discoPublic tailcfg.DiscoKey // public of discoPrivate
discoShort string // ShortString of discoPublic (to save logging work later)
// nodeOfDisco tracks the networkmap Node entity for each peer
// discovery key.
//
// TODO(danderson): the only thing we ever use from this is the
// peer's WireGuard public key. This could be a map of DiscoKey to
// NodeKey.
nodeOfDisco map[tailcfg.DiscoKey]*tailcfg.Node
discoOfNode map[tailcfg.NodeKey]tailcfg.DiscoKey
discoOfAddr map[netaddr.IPPort]tailcfg.DiscoKey // validated non-DERP paths only
// endpointsOfDisco tracks the wireguard-go endpoints for peers
// with recent activity.
endpointOfDisco map[tailcfg.DiscoKey]*discoEndpoint // those with activity only
sharedDiscoKey map[tailcfg.DiscoKey]*[32]byte // nacl/box precomputed key
// addrsByUDP is a map of every remote ip:port to a priority
// list of endpoint addresses for a peer.
// The priority list is provided by wgengine configuration.
//
// Given a wgcfg describing:
// machineA: 10.0.0.1:1, 10.0.0.2:2
// machineB: 10.0.0.3:3
// the addrsByUDP map contains:
// 10.0.0.1:1 -> [10.0.0.1:1, 10.0.0.2:2]
// 10.0.0.2:2 -> [10.0.0.1:1, 10.0.0.2:2]
// 10.0.0.3:3 -> [10.0.0.3:3]
//
// Used only to communicate with legacy, pre-active-discovery
// clients.
addrsByUDP map[netaddr.IPPort]*addrSet
// addrsByKey maps from public keys (as seen by incoming DERP
// packets) to its addrSet (the same values as in addrsByUDP).
//
// Used only to communicate with legacy, pre-active-discovery
// clients.
addrsByKey map[key.Public]*addrSet
// netInfoFunc is a callback that provides a tailcfg.NetInfo when
// discovered network conditions change.
//
// TODO(danderson): why can't it be set at construction time?
// There seem to be a few natural places in ipn/local.go to
// swallow untimely invocations.
netInfoFunc func(*tailcfg.NetInfo) // nil until set
// netInfoLast is the NetInfo provided in the last call to
// netInfoFunc. It's used to deduplicate calls to netInfoFunc.
//
// TODO(danderson): should all the deduping happen in
// ipn/local.go? We seem to be doing dedupe at several layers, and
// magicsock could do with any complexity reduction it can get.
netInfoLast *tailcfg.NetInfo
derpMap *tailcfg.DERPMap // nil (or zero regions/nodes) means DERP is disabled
netMap *netmap.NetworkMap
privateKey key.Private // WireGuard private key for this node
everHadKey bool // whether we ever had a non-zero private key
myDerp int // nearest DERP region ID; 0 means none/unknown
derpStarted chan struct{} // closed on first connection to DERP; for tests & cleaner Close
activeDerp map[int]activeDerp // DERP regionID -> connection to a node in that region
prevDerp map[int]*syncs.WaitGroupChan
// derpRoute contains optional alternate routes to use as an
// optimization instead of contacting a peer via their home
// DERP connection. If they sent us a message on a different
// DERP connection (which should really only be on our DERP
// home connection, or what was once our home), then we
// remember that route here to optimistically use instead of
// creating a new DERP connection back to their home.
derpRoute map[key.Public]derpRoute
// peerLastDerp tracks which DERP node we last used to speak with a
// peer. It's only used to quiet logging, so we only log on change.
peerLastDerp map[key.Public]int
// noV4 and noV6 are whether IPv4 and IPv6 are known to be
// missing. They're only used to suppress log spam. The name
// is named negatively because in early start-up, we don't yet
// necessarily have a netcheck.Report and don't want to skip
// logging.
noV4, noV6 syncs.AtomicBool
// networkUp is whether the network is up (some interface is up
// with IPv4 or IPv6). It's used to suppress log spam and prevent
// new connection that'll fail.
networkUp syncs.AtomicBool
// havePrivateKey is whether privateKey is non-zero.
havePrivateKey syncs.AtomicBool
}
// derpRoute is a route entry for a public key, saying that a certain
// peer should be available at DERP node derpID, as long as the
// current connection for that derpID is dc. (but dc should not be
// used to write directly; it's owned by the read/write loops)
type derpRoute struct {
derpID int
dc *derphttp.Client // don't use directly; see comment above
}
// removeDerpPeerRoute removes a DERP route entry previously added by addDerpPeerRoute.
func (c *Conn) removeDerpPeerRoute(peer key.Public, derpID int, dc *derphttp.Client) {
c.mu.Lock()
defer c.mu.Unlock()
r2 := derpRoute{derpID, dc}
if r, ok := c.derpRoute[peer]; ok && r == r2 {
delete(c.derpRoute, peer)
}
}
// addDerpPeerRoute adds a DERP route entry, noting that peer was seen
// on DERP node derpID, at least on the connection identified by dc.
// See issue 150 for details.
func (c *Conn) addDerpPeerRoute(peer key.Public, derpID int, dc *derphttp.Client) {
c.mu.Lock()
defer c.mu.Unlock()
if c.derpRoute == nil {
c.derpRoute = make(map[key.Public]derpRoute)
}
r := derpRoute{derpID, dc}
c.derpRoute[peer] = r
}
// DerpMagicIP is a fake WireGuard endpoint IP address that means
// to use DERP. When used, the port number of the WireGuard endpoint
// is the DERP server number to use.
//
// Mnemonic: 3.3.40 are numbers above the keys D, E, R, P.
const DerpMagicIP = "127.3.3.40"
var derpMagicIPAddr = netaddr.MustParseIP(DerpMagicIP)
// activeDerp contains fields for an active DERP connection.
type activeDerp struct {
c *derphttp.Client
cancel context.CancelFunc
writeCh chan<- derpWriteRequest
// lastWrite is the time of the last request for its write
// channel (currently even if there was no write).
// It is always non-nil and initialized to a non-zero Time.
lastWrite *time.Time
createTime time.Time
}
// DefaultPort is the default port to listen on.
// The current default (zero) means to auto-select a random free port.
const DefaultPort = 0
// Options contains options for Listen.
type Options struct {
// Logf optionally provides a log function to use.
// Must not be nil.
Logf logger.Logf
// Port is the port to listen on.
// Zero means to pick one automatically.
Port uint16
// EndpointsFunc optionally provides a func to be called when
// endpoints change. The called func does not own the slice.
EndpointsFunc func(endpoint []string)
// DERPActiveFunc optionally provides a func to be called when
// a connection is made to a DERP server.
DERPActiveFunc func()
// IdleFunc optionally provides a func to return how long
// it's been since a TUN packet was sent or received.
IdleFunc func() time.Duration
// PacketListener optionally specifies how to create PacketConns.
// It's meant for testing.
PacketListener nettype.PacketListener
// NoteRecvActivity, if provided, is a func for magicsock to
// call whenever it receives a packet from a a
// discovery-capable peer if it's been more than ~10 seconds
// since the last one. (10 seconds is somewhat arbitrary; the
// sole user just doesn't need or want it called on every
// packet, just every minute or two for Wireguard timeouts,
// and 10 seconds seems like a good trade-off between often
// enough and not too often.) The provided func is called
// while holding userspaceEngine.wgLock and likely calls
// Conn.CreateEndpoint, which acquires Conn.mu. As such, you
// should not hold Conn.mu while calling it.
NoteRecvActivity func(tailcfg.DiscoKey)
// SimulatedNetwork can be set true in tests to signal that
// the network is simulated and thus it's okay to bind on the
// unspecified address (which we'd normally avoid to avoid
// triggering macOS and Windows firwall dialog boxes during
// "go test").
SimulatedNetwork bool
// DisableLegacyNetworking disables legacy peer handling. When
// enabled, only active discovery-aware nodes will be able to
// communicate with Conn.
DisableLegacyNetworking bool
// LinkMonitor is the link monitor to use.
// With one, the portmapper won't be used.
LinkMonitor *monitor.Mon
}
func (o *Options) logf() logger.Logf {
if o.Logf == nil {
panic("must provide magicsock.Options.logf")
}
return o.Logf
}
func (o *Options) endpointsFunc() func([]string) {
if o == nil || o.EndpointsFunc == nil {
return func([]string) {}
}
return o.EndpointsFunc
}
func (o *Options) derpActiveFunc() func() {
if o == nil || o.DERPActiveFunc == nil {
return func() {}
}
return o.DERPActiveFunc
}
// newConn is the error-free, network-listening-side-effect-free based
// of NewConn. Mostly for tests.
func newConn() *Conn {
c := &Conn{
disableLegacy: true,
sendLogLimit: rate.NewLimiter(rate.Every(1*time.Minute), 1),
addrsByUDP: make(map[netaddr.IPPort]*addrSet),
addrsByKey: make(map[key.Public]*addrSet),
derpRecvCh: make(chan derpReadResult),
derpStarted: make(chan struct{}),
peerLastDerp: make(map[key.Public]int),
endpointOfDisco: make(map[tailcfg.DiscoKey]*discoEndpoint),
sharedDiscoKey: make(map[tailcfg.DiscoKey]*[32]byte),
discoOfAddr: make(map[netaddr.IPPort]tailcfg.DiscoKey),
}
c.muCond = sync.NewCond(&c.mu)
c.networkUp.Set(true) // assume up until told otherwise
return c
}
// NewConn creates a magic Conn listening on opts.Port.
// As the set of possible endpoints for a Conn changes, the
// callback opts.EndpointsFunc is called.
//
// It doesn't start doing anything until Start is called.
func NewConn(opts Options) (*Conn, error) {
c := newConn()
c.port = opts.Port
c.logf = opts.logf()
c.epFunc = opts.endpointsFunc()
c.derpActiveFunc = opts.derpActiveFunc()
c.idleFunc = opts.IdleFunc
c.packetListener = opts.PacketListener
c.noteRecvActivity = opts.NoteRecvActivity
c.simulatedNetwork = opts.SimulatedNetwork
c.disableLegacy = opts.DisableLegacyNetworking
c.portMapper = portmapper.NewClient(logger.WithPrefix(c.logf, "portmapper: "))
if opts.LinkMonitor != nil {
c.portMapper.SetGatewayLookupFunc(opts.LinkMonitor.GatewayAndSelfIP)
}
if err := c.initialBind(); err != nil {
return nil, err
}
c.connCtx, c.connCtxCancel = context.WithCancel(context.Background())
c.donec = c.connCtx.Done()
c.netChecker = &netcheck.Client{
Logf: logger.WithPrefix(c.logf, "netcheck: "),
GetSTUNConn4: func() netcheck.STUNConn { return c.pconn4 },
SkipExternalNetwork: inTest(),
PortMapper: c.portMapper,
}
if c.pconn6 != nil {
c.netChecker.GetSTUNConn6 = func() netcheck.STUNConn { return c.pconn6 }
}
c.ignoreSTUNPackets()
return c, nil
}
func (c *Conn) Start() {
c.mu.Lock()
if c.started {
panic("duplicate Start call")
}
c.started = true
c.mu.Unlock()
c.ReSTUN("initial")
}
// ignoreSTUNPackets sets a STUN packet processing func that does nothing.
func (c *Conn) ignoreSTUNPackets() {
c.stunReceiveFunc.Store(func([]byte, netaddr.IPPort) {})
}
// doPeriodicSTUN is called (in a new goroutine) by
// periodicReSTUNTimer when periodic STUNs are active.
func (c *Conn) doPeriodicSTUN() { c.ReSTUN("periodic") }
func (c *Conn) stopPeriodicReSTUNTimerLocked() {
if t := c.periodicReSTUNTimer; t != nil {
t.Stop()
c.periodicReSTUNTimer = nil
}
}
// c.mu must NOT be held.
func (c *Conn) updateEndpoints(why string) {
defer func() {
c.mu.Lock()
defer c.mu.Unlock()
why := c.wantEndpointsUpdate
c.wantEndpointsUpdate = ""
if !c.closed {
if why != "" {
go c.updateEndpoints(why)
return
}
if c.shouldDoPeriodicReSTUNLocked() {
// Pick a random duration between 20
// and 26 seconds (just under 30s, a
// common UDP NAT timeout on Linux,
// etc)
d := tstime.RandomDurationBetween(20*time.Second, 26*time.Second)
if t := c.periodicReSTUNTimer; t != nil {
if debugReSTUNStopOnIdle {
c.logf("resetting existing periodicSTUN to run in %v", d)
}
t.Reset(d)
} else {
if debugReSTUNStopOnIdle {
c.logf("scheduling periodicSTUN to run in %v", d)
}
c.periodicReSTUNTimer = time.AfterFunc(d, c.doPeriodicSTUN)
}
} else {
if debugReSTUNStopOnIdle {
c.logf("periodic STUN idle")
}
c.stopPeriodicReSTUNTimerLocked()
}
}
c.endpointsUpdateActive = false
c.muCond.Broadcast()
}()
c.logf("[v1] magicsock: starting endpoint update (%s)", why)
endpoints, reasons, err := c.determineEndpoints(c.connCtx)
if err != nil {
c.logf("magicsock: endpoint update (%s) failed: %v", why, err)
// TODO(crawshaw): are there any conditions under which
// we should trigger a retry based on the error here?
return
}
if c.setEndpoints(endpoints, reasons) {
c.logEndpointChange(endpoints, reasons)
c.epFunc(endpoints)
}
}
// setEndpoints records the new endpoints, reporting whether they're changed.
// It takes ownership of the slice.
func (c *Conn) setEndpoints(endpoints []string, reasons map[string]string) (changed bool) {
anySTUN := false
for _, reason := range reasons {
if reason == "stun" {
anySTUN = true
}
}
c.mu.Lock()
defer c.mu.Unlock()
if !anySTUN && c.derpMap == nil && !inTest() {
// Don't bother storing or reporting this yet. We
// don't have a DERP map or any STUN entries, so we're
// just starting up. A DERP map should arrive shortly
// and then we'll have more interesting endpoints to
// report. This saves a map update.
// TODO(bradfitz): this optimization is currently
// skipped during the e2e tests because they depend
// too much on the exact sequence of updates. Fix the
// tests. But a protocol rewrite might happen first.
c.logf("[v1] magicsock: ignoring pre-DERP map, STUN-less endpoint update: %v", endpoints)
return false
}
c.lastEndpointsTime = time.Now()
for de, fn := range c.onEndpointRefreshed {
go fn()
delete(c.onEndpointRefreshed, de)
}
if stringsEqual(endpoints, c.lastEndpoints) {
return false
}
c.lastEndpoints = endpoints
return true
}
// setNetInfoHavePortMap updates NetInfo.HavePortMap to true.
func (c *Conn) setNetInfoHavePortMap() {
c.mu.Lock()
defer c.mu.Unlock()
if c.netInfoLast == nil {
// No NetInfo yet. Nothing to update.
return
}
if c.netInfoLast.HavePortMap {
// No change.
return
}
ni := c.netInfoLast.Clone()
ni.HavePortMap = true
c.callNetInfoCallbackLocked(ni)
}
func (c *Conn) updateNetInfo(ctx context.Context) (*netcheck.Report, error) {
c.mu.Lock()
dm := c.derpMap
c.mu.Unlock()
if dm == nil || c.networkDown() {
return new(netcheck.Report), nil
}
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
c.stunReceiveFunc.Store(c.netChecker.ReceiveSTUNPacket)
defer c.ignoreSTUNPackets()
report, err := c.netChecker.GetReport(ctx, dm)
if err != nil {
return nil, err
}
c.noV4.Set(!report.IPv4)
c.noV6.Set(!report.IPv6)
ni := &tailcfg.NetInfo{
DERPLatency: map[string]float64{},
MappingVariesByDestIP: report.MappingVariesByDestIP,
HairPinning: report.HairPinning,
UPnP: report.UPnP,
PMP: report.PMP,
PCP: report.PCP,
HavePortMap: c.portMapper.HaveMapping(),
}
for rid, d := range report.RegionV4Latency {
ni.DERPLatency[fmt.Sprintf("%d-v4", rid)] = d.Seconds()
}
for rid, d := range report.RegionV6Latency {
ni.DERPLatency[fmt.Sprintf("%d-v6", rid)] = d.Seconds()
}
ni.WorkingIPv6.Set(report.IPv6)
ni.WorkingUDP.Set(report.UDP)
ni.PreferredDERP = report.PreferredDERP
if ni.PreferredDERP == 0 {
// Perhaps UDP is blocked. Pick a deterministic but arbitrary
// one.
ni.PreferredDERP = c.pickDERPFallback()
}
if !c.setNearestDERP(ni.PreferredDERP) {
ni.PreferredDERP = 0
}
// TODO: set link type
c.callNetInfoCallback(ni)
return report, nil
}
var processStartUnixNano = time.Now().UnixNano()
// pickDERPFallback returns a non-zero but deterministic DERP node to
// connect to. This is only used if netcheck couldn't find the
// nearest one (for instance, if UDP is blocked and thus STUN latency
// checks aren't working).
//
// c.mu must NOT be held.
func (c *Conn) pickDERPFallback() int {
c.mu.Lock()
defer c.mu.Unlock()
if !c.wantDerpLocked() {
return 0
}
ids := c.derpMap.RegionIDs()
if len(ids) == 0 {
// No DERP regions in non-nil map.
return 0
}
// See where our peers are.
var (
peersOnDerp = map[int]int{}
best int
bestCount int
)
for _, as := range c.addrsByKey {
if id := as.derpID(); id != 0 {
peersOnDerp[id]++
if v := peersOnDerp[id]; v > bestCount {
bestCount = v
best = id
}
}
}
// If we already had selected something in the past and it has
// any peers, stay on it. If there are no peers, though, also
// stay where we are.
if c.myDerp != 0 && (best == 0 || peersOnDerp[c.myDerp] != 0) {
return c.myDerp
}
// Otherwise pick wherever the most peers are.
if best != 0 {
return best
}
// Otherwise just pick something randomly.
h := fnv.New64()
h.Write([]byte(fmt.Sprintf("%p/%d", c, processStartUnixNano))) // arbitrary
return ids[rand.New(rand.NewSource(int64(h.Sum64()))).Intn(len(ids))]
}
// callNetInfoCallback calls the NetInfo callback (if previously
// registered with SetNetInfoCallback) if ni has substantially changed
// since the last state.
//
// callNetInfoCallback takes ownership of ni.
//
// c.mu must NOT be held.
func (c *Conn) callNetInfoCallback(ni *tailcfg.NetInfo) {
c.mu.Lock()
defer c.mu.Unlock()
if ni.BasicallyEqual(c.netInfoLast) {
return
}
c.callNetInfoCallbackLocked(ni)
}
func (c *Conn) callNetInfoCallbackLocked(ni *tailcfg.NetInfo) {
c.netInfoLast = ni
if c.netInfoFunc != nil {
c.logf("[v1] magicsock: netInfo update: %+v", ni)
go c.netInfoFunc(ni)
}
}
// addValidDiscoPathForTest makes addr a validated disco address for
// discoKey. It's used in tests to enable receiving of packets from
// addr without having to spin up the entire active discovery
// machinery.
func (c *Conn) addValidDiscoPathForTest(discoKey tailcfg.DiscoKey, addr netaddr.IPPort) {
c.mu.Lock()
defer c.mu.Unlock()
c.discoOfAddr[addr] = discoKey
}
func (c *Conn) SetNetInfoCallback(fn func(*tailcfg.NetInfo)) {
if fn == nil {
panic("nil NetInfoCallback")
}
c.mu.Lock()
last := c.netInfoLast
c.netInfoFunc = fn
c.mu.Unlock()
if last != nil {
fn(last)
}
}
// peerForIP returns the Node in nm that's responsible for
// handling the given IP address.
func peerForIP(nm *netmap.NetworkMap, ip netaddr.IP) (n *tailcfg.Node, ok bool) {
if nm == nil {
return nil, false
}
// Check for exact matches before looking for subnet matches.
for _, p := range nm.Peers {
for _, a := range p.Addresses {
if a.IP == ip {
return p, true
}
}
}
// TODO(bradfitz): this is O(n peers). Add ART to netaddr?
var best netaddr.IPPrefix
for _, p := range nm.Peers {
for _, cidr := range p.AllowedIPs {
if cidr.Contains(ip) {
if best.IsZero() || cidr.Bits > best.Bits {
n = p
best = cidr
}
}
}
}
return n, n != nil
}
// PeerForIP returns the node that ip should route to.
func (c *Conn) PeerForIP(ip netaddr.IP) (n *tailcfg.Node, ok bool) {
c.mu.Lock()
defer c.mu.Unlock()
if c.netMap == nil {
return
}
return peerForIP(c.netMap, ip)
}
// LastRecvActivityOfDisco returns the time we last got traffic from
// this endpoint (updated every ~10 seconds).
func (c *Conn) LastRecvActivityOfDisco(dk tailcfg.DiscoKey) time.Time {
c.mu.Lock()
defer c.mu.Unlock()
de, ok := c.endpointOfDisco[dk]
if !ok {
return time.Time{}
}
unix := atomic.LoadInt64(&de.lastRecvUnixAtomic)
if unix == 0 {
return time.Time{}
}
return time.Unix(unix, 0)
}
// Ping handles a "tailscale ping" CLI query.
func (c *Conn) Ping(ip netaddr.IP, cb func(*ipnstate.PingResult)) {
c.mu.Lock()
defer c.mu.Unlock()
res := &ipnstate.PingResult{IP: ip.String()}
if c.privateKey.IsZero() {
res.Err = "local tailscaled stopped"
cb(res)
return
}
peer, ok := peerForIP(c.netMap, ip)
if !ok {
res.Err = "no matching peer"
cb(res)
return
}
if len(peer.Addresses) > 0 {
res.NodeIP = peer.Addresses[0].IP.String()
}
res.NodeName = peer.Name // prefer DNS name
if res.NodeName == "" {
res.NodeName = peer.Hostinfo.Hostname // else hostname
} else {
if i := strings.Index(res.NodeName, "."); i != -1 {
res.NodeName = res.NodeName[:i]
}
}
dk, ok := c.discoOfNode[peer.Key]
if !ok { // peer is using outdated Tailscale version (pre-0.100)
res.Err = "no discovery key for peer (pre Tailscale 0.100 version?). Try: ping 100.x.y.z"
cb(res)
return
}
de, ok := c.endpointOfDisco[dk]
if !ok {
c.mu.Unlock() // temporarily release
if c.noteRecvActivity != nil {
c.noteRecvActivity(dk)
}
c.mu.Lock() // re-acquire
// re-check at least basic invariant:
if c.privateKey.IsZero() {
res.Err = "local tailscaled stopped"
cb(res)
return
}
de, ok = c.endpointOfDisco[dk]
if !ok {
res.Err = "internal error: failed to create endpoint for discokey"
cb(res)
return
}
c.logf("[v1] magicsock: started peer %v for ping to %v", dk.ShortString(), peer.Key.ShortString())
}
de.cliPing(res, cb)
}
// c.mu must be held
func (c *Conn) populateCLIPingResponseLocked(res *ipnstate.PingResult, latency time.Duration, ep netaddr.IPPort) {
res.LatencySeconds = latency.Seconds()
if ep.IP != derpMagicIPAddr {
res.Endpoint = ep.String()
return
}
regionID := int(ep.Port)
res.DERPRegionID = regionID
if c.derpMap != nil {
if dr, ok := c.derpMap.Regions[regionID]; ok {
res.DERPRegionCode = dr.RegionCode
}
}
}
// DiscoPublicKey returns the discovery public key.
func (c *Conn) DiscoPublicKey() tailcfg.DiscoKey {
c.mu.Lock()
defer c.mu.Unlock()
if c.discoPrivate.IsZero() {
priv := key.NewPrivate()
c.discoPrivate = priv
c.discoPublic = tailcfg.DiscoKey(priv.Public())
c.discoShort = c.discoPublic.ShortString()
c.logf("magicsock: disco key = %v", c.discoShort)
}
return c.discoPublic
}
// PeerHasDiscoKey reports whether peer k supports discovery keys (client version 0.100.0+).
func (c *Conn) PeerHasDiscoKey(k tailcfg.NodeKey) bool {
c.mu.Lock()
defer c.mu.Unlock()
_, ok := c.discoOfNode[k]
return ok
}
// c.mu must NOT be held.
func (c *Conn) setNearestDERP(derpNum int) (wantDERP bool) {
c.mu.Lock()
defer c.mu.Unlock()
if !c.wantDerpLocked() {
c.myDerp = 0
health.SetMagicSockDERPHome(0)
return false
}
if derpNum == c.myDerp {
// No change.
return true
}
c.myDerp = derpNum
health.SetMagicSockDERPHome(derpNum)
if c.privateKey.IsZero() {
// No private key yet, so DERP connections won't come up anyway.
// Return early rather than ultimately log a couple lines of noise.
return true
}
// On change, notify all currently connected DERP servers and
// start connecting to our home DERP if we are not already.
dr := c.derpMap.Regions[derpNum]
if dr == nil {
c.logf("[unexpected] magicsock: derpMap.Regions[%v] is nil", derpNum)
} else {
c.logf("magicsock: home is now derp-%v (%v)", derpNum, c.derpMap.Regions[derpNum].RegionCode)
}
for i, ad := range c.activeDerp {
go ad.c.NotePreferred(i == c.myDerp)
}
c.goDerpConnect(derpNum)
return true
}
// startDerpHomeConnectLocked starts connecting to our DERP home, if any.
//
// c.mu must be held.
func (c *Conn) startDerpHomeConnectLocked() {
c.goDerpConnect(c.myDerp)
}
// goDerpConnect starts a goroutine to start connecting to the given
// DERP node.
//
// c.mu may be held, but does not need to be.
func (c *Conn) goDerpConnect(node int) {
if node == 0 {
return
}
go c.derpWriteChanOfAddr(netaddr.IPPort{IP: derpMagicIPAddr, Port: uint16(node)}, key.Public{})
}
// determineEndpoints returns the machine's endpoint addresses. It
// does a STUN lookup (via netcheck) to determine its public address.
//
// c.mu must NOT be held.
func (c *Conn) determineEndpoints(ctx context.Context) (ipPorts []string, reasons map[string]string, err error) {
nr, err := c.updateNetInfo(ctx)
if err != nil {
c.logf("magicsock.Conn.determineEndpoints: updateNetInfo: %v", err)
return nil, nil, err
}
already := make(map[string]string) // endpoint -> how it was found
var eps []string // unique endpoints
addAddr := func(s, reason string) {
if debugOmitLocalAddresses && (reason == "localAddresses" || reason == "socket") {
return
}
if _, ok := already[s]; !ok {
already[s] = reason
eps = append(eps, s)
}
}
if ext, err := c.portMapper.CreateOrGetMapping(ctx); err == nil {
addAddr(ext.String(), "portmap")
c.setNetInfoHavePortMap()
} else if !portmapper.IsNoMappingError(err) {
c.logf("portmapper: %v", err)
}
if nr.GlobalV4 != "" {
addAddr(nr.GlobalV4, "stun")
// If they're behind a hard NAT and are using a fixed
// port locally, assume they might've added a static
// port mapping on their router to the same explicit
// port that tailscaled is running with. Worst case
// it's an invalid candidate mapping.
if nr.MappingVariesByDestIP.EqualBool(true) && c.port != 0 {
if ip, _, err := net.SplitHostPort(nr.GlobalV4); err == nil {
addAddr(net.JoinHostPort(ip, strconv.Itoa(int(c.port))), "port_in")
}
}
}
if nr.GlobalV6 != "" {
addAddr(nr.GlobalV6, "stun")
}
c.ignoreSTUNPackets()
if localAddr := c.pconn4.LocalAddr(); localAddr.IP.IsUnspecified() {
ips, loopback, err := interfaces.LocalAddresses()
if err != nil {
return nil, nil, err
}
reason := "localAddresses"
if len(ips) == 0 && len(eps) == 0 {
// Only include loopback addresses if we have no
// interfaces at all to use as endpoints and don't
// have a public IPv4 or IPv6 address. This allows
// for localhost testing when you're on a plane and
// offline, for example.
ips = loopback
reason = "loopback"
}
for _, ip := range ips {
addAddr(netaddr.IPPort{IP: ip, Port: uint16(localAddr.Port)}.String(), reason)
}
} else {
// Our local endpoint is bound to a particular address.
// Do not offer addresses on other local interfaces.
addAddr(localAddr.String(), "socket")
}
// Note: the endpoints are intentionally returned in priority order,
// from "farthest but most reliable" to "closest but least
// reliable." Addresses returned from STUN should be globally
// addressable, but might go farther on the network than necessary.
// Local interface addresses might have lower latency, but not be
// globally addressable.
//
// The STUN address(es) are always first so that legacy wireguard
// can use eps[0] as its only known endpoint address (although that's
// obviously non-ideal).
return eps, already, nil
}
func stringsEqual(x, y []string) bool {
if len(x) != len(y) {
return false
}
for i := range x {
if x[i] != y[i] {
return false
}
}
return true
}
// LocalPort returns the current IPv4 listener's port number.
func (c *Conn) LocalPort() uint16 {
laddr := c.pconn4.LocalAddr()
return uint16(laddr.Port)
}
var errNetworkDown = errors.New("magicsock: network down")
func (c *Conn) networkDown() bool { return !c.networkUp.Get() }
func (c *Conn) Send(b []byte, ep conn.Endpoint) error {
if c.networkDown() {
return errNetworkDown
}
switch v := ep.(type) {
default:
panic(fmt.Sprintf("[unexpected] Endpoint type %T", v))
case *discoEndpoint:
return v.send(b)
case *addrSet:
return c.sendAddrSet(b, v)
}
}
var errConnClosed = errors.New("Conn closed")
var errDropDerpPacket = errors.New("too many DERP packets queued; dropping")
var udpAddrPool = &sync.Pool{
New: func() interface{} { return new(net.UDPAddr) },
}
// sendUDP sends UDP packet b to ipp.
// See sendAddr's docs on the return value meanings.
func (c *Conn) sendUDP(ipp netaddr.IPPort, b []byte) (sent bool, err error) {
ua := udpAddrPool.Get().(*net.UDPAddr)
defer udpAddrPool.Put(ua)
return c.sendUDPStd(ipp.UDPAddrAt(ua), b)
}
// sendUDP sends UDP packet b to addr.
// See sendAddr's docs on the return value meanings.
func (c *Conn) sendUDPStd(addr *net.UDPAddr, b []byte) (sent bool, err error) {
switch {
case addr.IP.To4() != nil:
_, err = c.pconn4.WriteTo(b, addr)
if err != nil && c.noV4.Get() {
return false, nil
}
case len(addr.IP) == net.IPv6len:
if c.pconn6 == nil {
// ignore IPv6 dest if we don't have an IPv6 address.
return false, nil
}
_, err = c.pconn6.WriteTo(b, addr)
if err != nil && c.noV6.Get() {
return false, nil
}
default:
panic("bogus sendUDPStd addr type")
}
return err == nil, err
}
// sendAddr sends packet b to addr, which is either a real UDP address
// or a fake UDP address representing a DERP server (see derpmap.go).
// The provided public key identifies the recipient.
//
// The returned err is whether there was an error writing when it
// should've worked.
// The returned sent is whether a packet went out at all.
// An example of when they might be different: sending to an
// IPv6 address when the local machine doesn't have IPv6 support
// returns (false, nil); it's not an error, but nothing was sent.
func (c *Conn) sendAddr(addr netaddr.IPPort, pubKey key.Public, b []byte) (sent bool, err error) {
if addr.IP != derpMagicIPAddr {
return c.sendUDP(addr, b)
}
ch := c.derpWriteChanOfAddr(addr, pubKey)
if ch == nil {
return false, nil
}
// TODO(bradfitz): this makes garbage for now; we could use a
// buffer pool later. Previously we passed ownership of this
// to derpWriteRequest and waited for derphttp.Client.Send to
// complete, but that's too slow while holding wireguard-go
// internal locks.
pkt := make([]byte, len(b))
copy(pkt, b)
select {
case <-c.donec:
return false, errConnClosed
case ch <- derpWriteRequest{addr, pubKey, pkt}:
return true, nil
default:
// Too many writes queued. Drop packet.
return false, errDropDerpPacket
}
}
// bufferedDerpWritesBeforeDrop is how many packets writes can be
// queued up the DERP client to write on the wire before we start
// dropping.
//
// TODO: this is currently arbitrary. Figure out something better?
const bufferedDerpWritesBeforeDrop = 32
// derpWriteChanOfAddr returns a DERP client for fake UDP addresses that
// represent DERP servers, creating them as necessary. For real UDP
// addresses, it returns nil.
//
// If peer is non-zero, it can be used to find an active reverse
// path, without using addr.
func (c *Conn) derpWriteChanOfAddr(addr netaddr.IPPort, peer key.Public) chan<- derpWriteRequest {
if addr.IP != derpMagicIPAddr {
return nil
}
regionID := int(addr.Port)
if c.networkDown() {
return nil
}
c.mu.Lock()
defer c.mu.Unlock()
if !c.wantDerpLocked() || c.closed {
return nil
}
if c.privateKey.IsZero() {
c.logf("magicsock: DERP lookup of %v with no private key; ignoring", addr)
return nil
}
// See if we have a connection open to that DERP node ID
// first. If so, might as well use it. (It's a little
// arbitrary whether we use this one vs. the reverse route
// below when we have both.)
ad, ok := c.activeDerp[regionID]
if ok {
*ad.lastWrite = time.Now()
c.setPeerLastDerpLocked(peer, regionID, regionID)
return ad.writeCh
}
// If we don't have an open connection to the peer's home DERP
// node, see if we have an open connection to a DERP node
// where we'd heard from that peer already. For instance,
// perhaps peer's home is Frankfurt, but they dialed our home DERP
// node in SF to reach us, so we can reply to them using our
// SF connection rather than dialing Frankfurt. (Issue 150)
if !peer.IsZero() && useDerpRoute() {
if r, ok := c.derpRoute[peer]; ok {
if ad, ok := c.activeDerp[r.derpID]; ok && ad.c == r.dc {
c.setPeerLastDerpLocked(peer, r.derpID, regionID)
*ad.lastWrite = time.Now()
return ad.writeCh
}
}
}
why := "home-keep-alive"
if !peer.IsZero() {
why = peerShort(peer)
}
c.logf("magicsock: adding connection to derp-%v for %v", regionID, why)
firstDerp := false
if c.activeDerp == nil {
firstDerp = true
c.activeDerp = make(map[int]activeDerp)
c.prevDerp = make(map[int]*syncs.WaitGroupChan)
}
if c.derpMap == nil || c.derpMap.Regions[regionID] == nil {
return nil
}
// Note that derphttp.NewRegionClient does not dial the server
// so it is safe to do under the mu lock.
dc := derphttp.NewRegionClient(c.privateKey, c.logf, func() *tailcfg.DERPRegion {
if c.connCtx.Err() != nil {
// If we're closing, don't try to acquire the lock.
// We might already be in Conn.Close and the Lock would deadlock.
return nil
}
c.mu.Lock()
defer c.mu.Unlock()
if c.derpMap == nil {
return nil
}
return c.derpMap.Regions[regionID]
})
dc.SetCanAckPings(true)
dc.NotePreferred(c.myDerp == regionID)
dc.DNSCache = dnscache.Get()
ctx, cancel := context.WithCancel(c.connCtx)
ch := make(chan derpWriteRequest, bufferedDerpWritesBeforeDrop)
ad.c = dc
ad.writeCh = ch
ad.cancel = cancel
ad.lastWrite = new(time.Time)
*ad.lastWrite = time.Now()
ad.createTime = time.Now()
c.activeDerp[regionID] = ad
c.logActiveDerpLocked()
c.setPeerLastDerpLocked(peer, regionID, regionID)
c.scheduleCleanStaleDerpLocked()
// Build a startGate for the derp reader+writer
// goroutines, so they don't start running until any
// previous generation is closed.
startGate := syncs.ClosedChan()
if prev := c.prevDerp[regionID]; prev != nil {
startGate = prev.DoneChan()
}
// And register a WaitGroup(Chan) for this generation.
wg := syncs.NewWaitGroupChan()
wg.Add(2)
c.prevDerp[regionID] = wg
if firstDerp {
startGate = c.derpStarted
go func() {
dc.Connect(ctx)
close(c.derpStarted)
c.muCond.Broadcast()
}()
}
go c.runDerpReader(ctx, addr, dc, wg, startGate)
go c.runDerpWriter(ctx, dc, ch, wg, startGate)
go c.derpActiveFunc()
return ad.writeCh
}
// setPeerLastDerpLocked notes that peer is now being written to via
// the provided DERP regionID, and that the peer advertises a DERP
// home region ID of homeID.
//
// If there's any change, it logs.
//
// c.mu must be held.
func (c *Conn) setPeerLastDerpLocked(peer key.Public, regionID, homeID int) {
if peer.IsZero() {
return
}
old := c.peerLastDerp[peer]
if old == regionID {
return
}
c.peerLastDerp[peer] = regionID
var newDesc string
switch {
case regionID == homeID && regionID == c.myDerp:
newDesc = "shared home"
case regionID == homeID:
newDesc = "their home"
case regionID == c.myDerp:
newDesc = "our home"
case regionID != homeID:
newDesc = "alt"
}
if old == 0 {
c.logf("[v1] magicsock: derp route for %s set to derp-%d (%s)", peerShort(peer), regionID, newDesc)
} else {
c.logf("[v1] magicsock: derp route for %s changed from derp-%d => derp-%d (%s)", peerShort(peer), old, regionID, newDesc)
}
}
// derpReadResult is the type sent by runDerpClient to ReceiveIPv4
// when a DERP packet is available.
//
// Notably, it doesn't include the derp.ReceivedPacket because we
// don't want to give the receiver access to the aliased []byte. To
// get at the packet contents they need to call copyBuf to copy it
// out, which also releases the buffer.
type derpReadResult struct {
regionID int
n int // length of data received
src key.Public // may be zero until server deployment if v2+
// copyBuf is called to copy the data to dst. It returns how
// much data was copied, which will be n if dst is large
// enough. copyBuf can only be called once.
// If copyBuf is nil, that's a signal from the sender to ignore
// this message.
copyBuf func(dst []byte) int
}
// runDerpReader runs in a goroutine for the life of a DERP
// connection, handling received packets.
func (c *Conn) runDerpReader(ctx context.Context, derpFakeAddr netaddr.IPPort, dc *derphttp.Client, wg *syncs.WaitGroupChan, startGate <-chan struct{}) {
defer wg.Decr()
defer dc.Close()
select {
case <-startGate:
case <-ctx.Done():
return
}
didCopy := make(chan struct{}, 1)
regionID := int(derpFakeAddr.Port)
res := derpReadResult{regionID: regionID}
var pkt derp.ReceivedPacket
res.copyBuf = func(dst []byte) int {
n := copy(dst, pkt.Data)
didCopy <- struct{}{}
return n
}
defer health.SetDERPRegionConnectedState(regionID, false)
// peerPresent is the set of senders we know are present on this
// connection, based on messages we've received from the server.
peerPresent := map[key.Public]bool{}
bo := backoff.NewBackoff(fmt.Sprintf("derp-%d", regionID), c.logf, 5*time.Second)
var lastPacketTime time.Time
for {
msg, connGen, err := dc.RecvDetail()
if err != nil {
health.SetDERPRegionConnectedState(regionID, false)
// Forget that all these peers have routes.
for peer := range peerPresent {
delete(peerPresent, peer)
c.removeDerpPeerRoute(peer, regionID, dc)
}
if err == derphttp.ErrClientClosed {
return
}
if c.networkDown() {
c.logf("[v1] magicsock: derp.Recv(derp-%d): network down, closing", regionID)
return
}
select {
case <-ctx.Done():
return
default:
}
c.logf("magicsock: [%p] derp.Recv(derp-%d): %v", dc, regionID, err)
// If our DERP connection broke, it might be because our network
// conditions changed. Start that check.
c.ReSTUN("derp-recv-error")
// Back off a bit before reconnecting.
bo.BackOff(ctx, err)
select {
case <-ctx.Done():
return
default:
}
continue
}
bo.BackOff(ctx, nil) // reset
now := time.Now()
if lastPacketTime.IsZero() || now.Sub(lastPacketTime) > 5*time.Second {
health.NoteDERPRegionReceivedFrame(regionID)
lastPacketTime = now
}
switch m := msg.(type) {
case derp.ServerInfoMessage:
health.SetDERPRegionConnectedState(regionID, true)
c.logf("magicsock: derp-%d connected; connGen=%v", regionID, connGen)
continue
case derp.ReceivedPacket:
pkt = m
res.n = len(m.Data)
res.src = m.Source
if logDerpVerbose {
c.logf("magicsock: got derp-%v packet: %q", regionID, m.Data)
}
// If this is a new sender we hadn't seen before, remember it and
// register a route for this peer.
if _, ok := peerPresent[m.Source]; !ok {
peerPresent[m.Source] = true
c.addDerpPeerRoute(m.Source, regionID, dc)
}
case derp.PingMessage:
// Best effort reply to the ping.
pingData := [8]byte(m)
go func() {
if err := dc.SendPong(pingData); err != nil {
c.logf("magicsock: derp-%d SendPong error: %v", regionID, err)
}
}()
continue
default:
// Ignore.
continue
}
if !c.sendDerpReadResult(ctx, res) {
return
}
select {
case <-ctx.Done():
return
case <-didCopy:
continue
}
}
}
var (
testCounterZeroDerpReadResultSend expvar.Int
testCounterZeroDerpReadResultRecv expvar.Int
)
// sendDerpReadResult sends res to c.derpRecvCh and reports whether it
// was sent. (It reports false if ctx was done first.)
//
// This includes doing the whole wake-up dance to interrupt
// ReceiveIPv4's blocking UDP read.
func (c *Conn) sendDerpReadResult(ctx context.Context, res derpReadResult) (sent bool) {
// Before we wake up ReceiveIPv4 with SetReadDeadline,
// note that a DERP packet has arrived. ReceiveIPv4
// will read this field to note that its UDP read
// error is due to us.
atomic.AddInt64(&c.derpRecvCountAtomic, 1)
// Cancel the pconn read goroutine.
c.pconn4.SetReadDeadline(aLongTimeAgo)
select {
case <-ctx.Done():
select {
case <-c.donec:
// The whole Conn shut down. The reader of
// c.derpRecvCh also selects on c.donec, so it's
// safe to abort now.
case c.derpRecvCh <- (derpReadResult{}):
// Just this DERP reader is closing (perhaps
// the user is logging out, or the DERP
// connection is too idle for sends). Since we
// already incremented c.derpRecvCountAtomic,
// we need to send on the channel (unless the
// conn is going down).
// The receiver treats a derpReadResult zero value
// message as a skip.
testCounterZeroDerpReadResultSend.Add(1)
}
return false
case c.derpRecvCh <- res:
return true
}
}
type derpWriteRequest struct {
addr netaddr.IPPort
pubKey key.Public
b []byte // copied; ownership passed to receiver
}
// runDerpWriter runs in a goroutine for the life of a DERP
// connection, handling received packets.
func (c *Conn) runDerpWriter(ctx context.Context, dc *derphttp.Client, ch <-chan derpWriteRequest, wg *syncs.WaitGroupChan, startGate <-chan struct{}) {
defer wg.Decr()
select {
case <-startGate:
case <-ctx.Done():
return
}
for {
select {
case <-ctx.Done():
return
case wr := <-ch:
err := dc.Send(wr.pubKey, wr.b)
if err != nil {
c.logf("magicsock: derp.Send(%v): %v", wr.addr, err)
}
}
}
}
// findEndpoint maps from a UDP address to a WireGuard endpoint, for
// ReceiveIPv4/ReceiveIPv6.
//
// TODO(bradfitz): add a fast path that returns nil here for normal
// wireguard-go transport packets; wireguard-go only uses this
// Endpoint for the relatively rare non-data packets; but we need the
// Endpoint to find the UDPAddr to return to wireguard anyway, so no
// benefit unless we can, say, always return the same fake UDPAddr for
// all packets.
func (c *Conn) findEndpoint(ipp netaddr.IPPort, packet []byte) conn.Endpoint {
c.mu.Lock()
defer c.mu.Unlock()
// See if they have a discoEndpoint, for a set of peers
// both supporting active discovery.
if dk, ok := c.discoOfAddr[ipp]; ok {
if ep, ok := c.endpointOfDisco[dk]; ok {
return ep
}
}
return c.findLegacyEndpointLocked(ipp, packet)
}
// aLongTimeAgo is a non-zero time, far in the past, used for
// immediate cancellation of network operations.
var aLongTimeAgo = time.Unix(233431200, 0)
// noteRecvActivityFromEndpoint calls the c.noteRecvActivity hook if
// e is a discovery-capable peer and this is the first receive activity
// it's got in awhile (in last 10 seconds).
//
// This should be called whenever a packet arrives from e.
func (c *Conn) noteRecvActivityFromEndpoint(e conn.Endpoint) {
de, ok := e.(*discoEndpoint)
if ok && c.noteRecvActivity != nil && de.isFirstRecvActivityInAwhile() {
c.noteRecvActivity(de.discoKey)
}
}
func (c *Conn) ReceiveIPv6(b []byte) (int, conn.Endpoint, error) {
if c.pconn6 == nil {
return 0, nil, syscall.EAFNOSUPPORT
}
for {
n, ipp, err := c.pconn6.ReadFromNetaddr(b)
if err != nil {
return 0, nil, err
}
if ep, ok := c.receiveIP(b[:n], ipp, &c.ippEndpoint6); ok {
return n, ep, nil
}
}
}
func (c *Conn) derpPacketArrived() bool {
return atomic.LoadInt64(&c.derpRecvCountAtomic) > 0
}
// ReceiveIPv4 is called by wireguard-go to receive an IPv4 packet.
// In Tailscale's case, that packet might also arrive via DERP. A DERP packet arrival
// aborts the pconn4 read deadline to make it fail.
func (c *Conn) ReceiveIPv4(b []byte) (n int, ep conn.Endpoint, err error) {
var ipp netaddr.IPPort
for {
// Drain DERP queues before reading new UDP packets.
if c.derpPacketArrived() {
goto ReadDERP
}
n, ipp, err = c.pconn4.ReadFromNetaddr(b)
if err != nil {
// If the pconn4 read failed, the likely reason is a DERP reader received
// a packet and interrupted us.
// It's possible for ReadFrom to return a non deadline exceeded error
// and for there to have also had a DERP packet arrive, but that's fine:
// we'll get the same error from ReadFrom later.
if c.derpPacketArrived() {
goto ReadDERP
}
return 0, nil, err
}
if ep, ok := c.receiveIP(b[:n], ipp, &c.ippEndpoint4); ok {
return n, ep, nil
} else {
continue
}
ReadDERP:
n, ep, err = c.receiveIPv4DERP(b)
if err == errLoopAgain {
continue
}
return n, ep, err
}
}
// receiveIP is the shared bits of ReceiveIPv4 and ReceiveIPv6.
//
// ok is whether this read should be reported up to wireguard-go (our
// caller).
func (c *Conn) receiveIP(b []byte, ipp netaddr.IPPort, cache *ippEndpointCache) (ep conn.Endpoint, ok bool) {
if stun.Is(b) {
c.stunReceiveFunc.Load().(func([]byte, netaddr.IPPort))(b, ipp)
return nil, false
}
if c.handleDiscoMessage(b, ipp) {
return nil, false
}
if !c.havePrivateKey.Get() {
// If we have no private key, we're logged out or
// stopped. Don't try to pass these wireguard packets
// up to wireguard-go; it'll just complain (Issue
// 1167).
return nil, false
}
if cache.ipp == ipp && cache.de != nil && cache.gen == cache.de.numStopAndReset() {
ep = cache.de
} else {
ep = c.findEndpoint(ipp, b)
if ep == nil {
return nil, false
}
if de, ok := ep.(*discoEndpoint); ok {
cache.ipp = ipp
cache.de = de
cache.gen = de.numStopAndReset()
}
}
c.noteRecvActivityFromEndpoint(ep)
return ep, true
}
var errLoopAgain = errors.New("received packet was not a wireguard-go packet or no endpoint found")
// receiveIPv4DERP reads a packet from c.derpRecvCh into b and returns the associated endpoint.
//
// If the packet was a disco message or the peer endpoint wasn't
// found, the returned error is errLoopAgain.
func (c *Conn) receiveIPv4DERP(b []byte) (n int, ep conn.Endpoint, err error) {
var dm derpReadResult
select {
case <-c.donec:
// Socket has been shut down. All the producers of packets
// respond to the context cancellation and go away, so we have
// to also unblock and return an error, to inform wireguard-go
// that this socket has gone away.
//
// Specifically, wireguard-go depends on its bind.Conn having
// the standard socket behavior, which is that a Close()
// unblocks any concurrent Read()s. wireguard-go itself calls
// Close() on magicsock, and expects ReceiveIPv4 to unblock
// with an error so it can clean up.
return 0, nil, errors.New("socket closed")
case dm = <-c.derpRecvCh:
// Below.
}
if atomic.AddInt64(&c.derpRecvCountAtomic, -1) == 0 {
c.pconn4.SetReadDeadline(time.Time{})
}
if dm.copyBuf == nil {
testCounterZeroDerpReadResultRecv.Add(1)
return 0, nil, errLoopAgain
}
var regionID int
n, regionID = dm.n, dm.regionID
ncopy := dm.copyBuf(b)
if ncopy != n {
err = fmt.Errorf("received DERP packet of length %d that's too big for WireGuard ReceiveIPv4 buf size %d", n, ncopy)
c.logf("magicsock: %v", err)
return 0, nil, err
}
ipp := netaddr.IPPort{IP: derpMagicIPAddr, Port: uint16(regionID)}
if c.handleDiscoMessage(b[:n], ipp) {
return 0, nil, errLoopAgain
}
var (
didNoteRecvActivity bool
discoEp *discoEndpoint
asEp *addrSet
)
c.mu.Lock()
if dk, ok := c.discoOfNode[tailcfg.NodeKey(dm.src)]; ok {
discoEp = c.endpointOfDisco[dk]
// If we know about the node (it's in discoOfNode) but don't know about the
// endpoint, that's because it's an idle peer that doesn't yet exist in the
// wireguard config. So run the receive hook, if defined, which should
// create the wireguard peer.
if discoEp == nil && c.noteRecvActivity != nil {
didNoteRecvActivity = true
c.mu.Unlock() // release lock before calling noteRecvActivity
c.noteRecvActivity(dk) // (calls back into CreateEndpoint)
// Now require the lock. No invariants need to be rechecked; just
// 1-2 map lookups follow that are harmless if, say, the peer has
// been deleted during this time.
c.mu.Lock()
discoEp = c.endpointOfDisco[dk]
c.logf("magicsock: DERP packet received from idle peer %v; created=%v", dm.src.ShortString(), discoEp != nil)
}
}
if !c.disableLegacy {
asEp = c.addrsByKey[dm.src]
}
c.mu.Unlock()
if discoEp != nil {
ep = discoEp
} else if asEp != nil {
ep = asEp
} else {
key := wgkey.Key(dm.src)
c.logf("magicsock: DERP packet from unknown key: %s", key.ShortString())
ep = c.findEndpoint(ipp, b[:n])
if ep == nil {
return 0, nil, errLoopAgain
}
}
if !didNoteRecvActivity {
c.noteRecvActivityFromEndpoint(ep)
}
return n, ep, nil
}
// discoLogLevel controls the verbosity of discovery log messages.
type discoLogLevel int
const (
// discoLog means that a message should be logged.
discoLog discoLogLevel = iota
// discoVerboseLog means that a message should only be logged
// in TS_DEBUG_DISCO mode.
discoVerboseLog
)
func (c *Conn) sendDiscoMessage(dst netaddr.IPPort, dstKey tailcfg.NodeKey, dstDisco tailcfg.DiscoKey, m disco.Message, logLevel discoLogLevel) (sent bool, err error) {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return false, errConnClosed
}
var nonce [disco.NonceLen]byte
if _, err := crand.Read(nonce[:]); err != nil {
panic(err) // worth dying for
}
pkt := make([]byte, 0, 512) // TODO: size it correctly? pool? if it matters.
pkt = append(pkt, disco.Magic...)
pkt = append(pkt, c.discoPublic[:]...)
pkt = append(pkt, nonce[:]...)
sharedKey := c.sharedDiscoKeyLocked(dstDisco)
c.mu.Unlock()
pkt = box.SealAfterPrecomputation(pkt, m.AppendMarshal(nil), &nonce, sharedKey)
sent, err = c.sendAddr(dst, key.Public(dstKey), pkt)
if sent {
if logLevel == discoLog || (logLevel == discoVerboseLog && debugDisco) {
c.logf("[v1] magicsock: disco: %v->%v (%v, %v) sent %v", c.discoShort, dstDisco.ShortString(), dstKey.ShortString(), derpStr(dst.String()), disco.MessageSummary(m))
}
} else if err == nil {
// Can't send. (e.g. no IPv6 locally)
} else {
if !c.networkDown() {
c.logf("magicsock: disco: failed to send %T to %v: %v", m, dst, err)
}
}
return sent, err
}
// handleDiscoMessage handles a discovery message and reports whether
// msg was a Tailscale inter-node discovery message.
//
// A discovery message has the form:
//
// * magic [6]byte
// * senderDiscoPubKey [32]byte
// * nonce [24]byte
// * naclbox of payload (see tailscale.com/disco package for inner payload format)
//
// For messages received over DERP, the addr will be derpMagicIP (with
// port being the region)
func (c *Conn) handleDiscoMessage(msg []byte, src netaddr.IPPort) (isDiscoMsg bool) {
const headerLen = len(disco.Magic) + len(tailcfg.DiscoKey{}) + disco.NonceLen
if len(msg) < headerLen || string(msg[:len(disco.Magic)]) != disco.Magic {
return false
}
// If the first four parts are the prefix of disco.Magic
// (0x5453f09f) then it's definitely not a valid Wireguard
// packet (which starts with little-endian uint32 1, 2, 3, 4).
// Use naked returns for all following paths.
isDiscoMsg = true
var sender tailcfg.DiscoKey
copy(sender[:], msg[len(disco.Magic):])
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return
}
if debugDisco {
c.logf("magicsock: disco: got disco-looking frame from %v", sender.ShortString())
}
if c.privateKey.IsZero() {
// Ignore disco messages when we're stopped.
// Still return true, to not pass it down to wireguard.
return
}
if c.discoPrivate.IsZero() {
if debugDisco {
c.logf("magicsock: disco: ignoring disco-looking frame, no local key")
}
return
}
peerNode, ok := c.nodeOfDisco[sender]
if !ok {
if debugDisco {
c.logf("magicsock: disco: ignoring disco-looking frame, don't know node for %v", sender.ShortString())
}
return
}
needsRecvActivityCall := false
de, endpointFound0 := c.endpointOfDisco[sender]
if !endpointFound0 {
// We don't have an active endpoint for this sender but we knew about the node, so
// it's an idle endpoint that doesn't yet exist in the wireguard config. We now have
// to notify the userspace engine (via noteRecvActivity) so wireguard-go can create
// an Endpoint (ultimately calling our CreateEndpoint).
c.logf("magicsock: got disco message from idle peer, starting lazy conf for %v, %v", peerNode.Key.ShortString(), sender.ShortString())
if c.noteRecvActivity == nil {
c.logf("magicsock: [unexpected] have node without endpoint, without c.noteRecvActivity hook")
return
}
needsRecvActivityCall = true
} else {
needsRecvActivityCall = de.isFirstRecvActivityInAwhile()
}
if needsRecvActivityCall && c.noteRecvActivity != nil {
// We can't hold Conn.mu while calling noteRecvActivity.
// noteRecvActivity acquires userspaceEngine.wgLock (and per our
// lock ordering rules: wgLock must come first), and also calls
// back into our Conn.CreateEndpoint, which would double-acquire
// Conn.mu.
c.mu.Unlock()
c.noteRecvActivity(sender)
c.mu.Lock() // re-acquire
// Now, recheck invariants that might've changed while we'd
// released the lock, which isn't much:
if c.closed || c.privateKey.IsZero() {
return
}
de, ok = c.endpointOfDisco[sender]
if !ok {
if _, ok := c.nodeOfDisco[sender]; !ok {
// They just disappeared while we'd released the lock.
return false
}
c.logf("magicsock: [unexpected] lazy endpoint not created for %v, %v", peerNode.Key.ShortString(), sender.ShortString())
return
}
if !endpointFound0 {
c.logf("magicsock: lazy endpoint created via disco message for %v, %v", peerNode.Key.ShortString(), sender.ShortString())
}
}
// First, do we even know (and thus care) about this sender? If not,
// don't bother decrypting it.
var nonce [disco.NonceLen]byte
copy(nonce[:], msg[len(disco.Magic)+len(key.Public{}):])
sealedBox := msg[headerLen:]
payload, ok := box.OpenAfterPrecomputation(nil, sealedBox, &nonce, c.sharedDiscoKeyLocked(sender))
if !ok {
// This might be have been intended for a previous
// disco key. When we restart we get a new disco key
// and old packets might've still been in flight (or
// scheduled). This is particularly the case for LANs
// or non-NATed endpoints.
// Don't log in normal case. Pass on to wireguard, in case
// it's actually a a wireguard packet (super unlikely,
// but).
if debugDisco {
c.logf("magicsock: disco: failed to open naclbox from %v (wrong rcpt?)", sender)
}
// TODO(bradfitz): add some counter for this that logs rarely
return
}
dm, err := disco.Parse(payload)
if debugDisco {
c.logf("magicsock: disco: disco.Parse = %T, %v", dm, err)
}
if err != nil {
// Couldn't parse it, but it was inside a correctly
// signed box, so just ignore it, assuming it's from a
// newer version of Tailscale that we don't
// understand. Not even worth logging about, lest it
// be too spammy for old clients.
// TODO(bradfitz): add some counter for this that logs rarely
return
}
switch dm := dm.(type) {
case *disco.Ping:
c.handlePingLocked(dm, de, src, sender, peerNode)
case *disco.Pong:
if de == nil {
return
}
de.handlePongConnLocked(dm, src)
case *disco.CallMeMaybe:
if src.IP != derpMagicIPAddr {
// CallMeMaybe messages should only come via DERP.
c.logf("[unexpected] CallMeMaybe packets should only come via DERP")
return
}
if de != nil {
c.logf("magicsock: disco: %v<-%v (%v, %v) got call-me-maybe, %d endpoints",
c.discoShort, de.discoShort,
de.publicKey.ShortString(), derpStr(src.String()),
len(dm.MyNumber))
go de.handleCallMeMaybe(dm)
}
}
return
}
func (c *Conn) handlePingLocked(dm *disco.Ping, de *discoEndpoint, src netaddr.IPPort, sender tailcfg.DiscoKey, peerNode *tailcfg.Node) {
if peerNode == nil {
c.logf("magicsock: disco: [unexpected] ignoring ping from unknown peer Node")
return
}
likelyHeartBeat := src == de.lastPingFrom && time.Since(de.lastPingTime) < 5*time.Second
de.lastPingFrom = src
de.lastPingTime = time.Now()
if !likelyHeartBeat || debugDisco {
c.logf("[v1] magicsock: disco: %v<-%v (%v, %v) got ping tx=%x", c.discoShort, de.discoShort, peerNode.Key.ShortString(), src, dm.TxID[:6])
}
// Remember this route if not present.
c.setAddrToDiscoLocked(src, sender, nil)
de.addCandidateEndpoint(src)
ipDst := src
discoDest := sender
go c.sendDiscoMessage(ipDst, peerNode.Key, discoDest, &disco.Pong{
TxID: dm.TxID,
Src: src,
}, discoVerboseLog)
}
// enqueueCallMeMaybe schedules a send of disco.CallMeMaybe to de via derpAddr
// once we know that our STUN endpoint is fresh.
//
// derpAddr is de.derpAddr at the time of send. It's assumed the peer won't be
// flipping primary DERPs in the 0-30ms it takes to confirm our STUN endpoint.
// If they do, traffic will just go over DERP for a bit longer until the next
// discovery round.
func (c *Conn) enqueueCallMeMaybe(derpAddr netaddr.IPPort, de *discoEndpoint) {
c.mu.Lock()
defer c.mu.Unlock()
if !c.lastEndpointsTime.After(time.Now().Add(-endpointsFreshEnoughDuration)) {
c.logf("magicsock: want call-me-maybe but endpoints stale; restunning")
if c.onEndpointRefreshed == nil {
c.onEndpointRefreshed = map[*discoEndpoint]func(){}
}
c.onEndpointRefreshed[de] = func() {
c.logf("magicsock: STUN done; sending call-me-maybe to %v %v", de.discoShort, de.publicKey.ShortString())
c.enqueueCallMeMaybe(derpAddr, de)
}
// TODO(bradfitz): make a new 'reSTUNQuickly' method
// that passes down a do-a-lite-netcheck flag down to
// netcheck that does 1 (or 2 max) STUN queries
// (UDP-only, not HTTPs) to find our port mapping to
// our home DERP and maybe one other. For now we do a
// "full" ReSTUN which may or may not be a full one
// (depending on age) and may do HTTPS timing queries
// (if UDP is blocked). Good enough for now.
go c.ReSTUN("refresh-for-peering")
return
}
eps := make([]netaddr.IPPort, 0, len(c.lastEndpoints))
for _, ep := range c.lastEndpoints {
if ipp, err := netaddr.ParseIPPort(ep); err == nil {
eps = append(eps, ipp)
}
}
go de.sendDiscoMessage(derpAddr, &disco.CallMeMaybe{MyNumber: eps}, discoLog)
}
// setAddrToDiscoLocked records that newk is at src.
//
// c.mu must be held.
//
// If the caller already has a discoEndpoint mutex held as well, it
// can be passed in as alreadyLocked so it won't be re-acquired during
// any lazy cleanup of the mapping.
func (c *Conn) setAddrToDiscoLocked(src netaddr.IPPort, newk tailcfg.DiscoKey, alreadyLocked *discoEndpoint) {
oldk, ok := c.discoOfAddr[src]
if ok && oldk == newk {
return
}
if ok {
c.logf("[v1] magicsock: disco: changing mapping of %v from %x=>%x", src, oldk.ShortString(), newk.ShortString())
} else {
c.logf("[v1] magicsock: disco: adding mapping of %v to %v", src, newk.ShortString())
}
c.discoOfAddr[src] = newk
if !ok {
c.cleanDiscoOfAddrLocked(alreadyLocked)
}
}
// cleanDiscoOfAddrLocked lazily checks a few entries in c.discoOfAddr
// and deletes them if they're stale. It has no pointers in it so we
// don't go through the effort of keeping it aggressively
// pruned. Instead, we lazily clean it whenever it grows.
//
// c.mu must be held.
//
// If the caller already has a discoEndpoint mutex held as well, it
// can be passed in as alreadyLocked so it won't be re-acquired.
func (c *Conn) cleanDiscoOfAddrLocked(alreadyLocked *discoEndpoint) {
// If it's small enough, don't worry about it.
if len(c.discoOfAddr) < 16 {
return
}
const checkEntries = 5 // per one unit of growth
// Take advantage of Go's random map iteration to check & clean
// a few entries.
n := 0
for ipp, dk := range c.discoOfAddr {
n++
if n > checkEntries {
return
}
de, ok := c.endpointOfDisco[dk]
if !ok {
// This discokey isn't even known anymore. Clean.
delete(c.discoOfAddr, ipp)
continue
}
if de != alreadyLocked {
de.mu.Lock()
}
if _, ok := de.endpointState[ipp]; !ok {
// The discoEndpoint no longer knows about that endpoint.
// It must've changed. Clean.
delete(c.discoOfAddr, ipp)
}
if de != alreadyLocked {
de.mu.Unlock()
}
}
}
func (c *Conn) sharedDiscoKeyLocked(k tailcfg.DiscoKey) *[32]byte {
if v, ok := c.sharedDiscoKey[k]; ok {
return v
}
shared := new([32]byte)
box.Precompute(shared, key.Public(k).B32(), c.discoPrivate.B32())
c.sharedDiscoKey[k] = shared
return shared
}
func (c *Conn) SetNetworkUp(up bool) {
c.mu.Lock()
defer c.mu.Unlock()
if c.networkUp.Get() == up {
return
}
c.logf("magicsock: SetNetworkUp(%v)", up)
c.networkUp.Set(up)
if up {
c.startDerpHomeConnectLocked()
} else {
c.portMapper.NoteNetworkDown()
c.closeAllDerpLocked("network-down")
}
}
// SetPrivateKey sets the connection's private key.
//
// This is only used to be able prove our identity when connecting to
// DERP servers.
//
// If the private key changes, any DERP connections are torn down &
// recreated when needed.
func (c *Conn) SetPrivateKey(privateKey wgkey.Private) error {
c.mu.Lock()
defer c.mu.Unlock()
oldKey, newKey := c.privateKey, key.Private(privateKey)
if newKey == oldKey {
return nil
}
c.privateKey = newKey
c.havePrivateKey.Set(!newKey.IsZero())
if oldKey.IsZero() {
c.everHadKey = true
c.logf("magicsock: SetPrivateKey called (init)")
if c.started {
go c.ReSTUN("set-private-key")
}
} else if newKey.IsZero() {
c.logf("magicsock: SetPrivateKey called (zeroed)")
c.closeAllDerpLocked("zero-private-key")
c.stopPeriodicReSTUNTimerLocked()
c.onEndpointRefreshed = nil
} else {
c.logf("magicsock: SetPrivateKey called (changed)")
c.closeAllDerpLocked("new-private-key")
}
// Key changed. Close existing DERP connections and reconnect to home.
if c.myDerp != 0 && !newKey.IsZero() {
c.logf("magicsock: private key changed, reconnecting to home derp-%d", c.myDerp)
c.startDerpHomeConnectLocked()
}
if newKey.IsZero() {
for _, de := range c.endpointOfDisco {
de.stopAndReset()
}
}
return nil
}
// UpdatePeers is called when the set of WireGuard peers changes. It
// then removes any state for old peers.
//
// The caller passes ownership of newPeers map to UpdatePeers.
func (c *Conn) UpdatePeers(newPeers map[key.Public]struct{}) {
c.mu.Lock()
defer c.mu.Unlock()
oldPeers := c.peerSet
c.peerSet = newPeers
// Clean up any key.Public-keyed maps for peers that no longer
// exist.
for peer := range oldPeers {
if _, ok := newPeers[peer]; !ok {
delete(c.addrsByKey, peer)
delete(c.derpRoute, peer)
delete(c.peerLastDerp, peer)
}
}
if len(oldPeers) == 0 && len(newPeers) > 0 {
go c.ReSTUN("non-zero-peers")
}
}
// SetDERPMap controls which (if any) DERP servers are used.
// A nil value means to disable DERP; it's disabled by default.
func (c *Conn) SetDERPMap(dm *tailcfg.DERPMap) {
c.mu.Lock()
defer c.mu.Unlock()
if reflect.DeepEqual(dm, c.derpMap) {
return
}
c.derpMap = dm
if dm == nil {
c.closeAllDerpLocked("derp-disabled")
return
}
if c.started {
go c.ReSTUN("derp-map-update")
}
}
func nodesEqual(x, y []*tailcfg.Node) bool {
if len(x) != len(y) {
return false
}
for i := range x {
if !x[i].Equal(y[i]) {
return false
}
}
return true
}
// SetNetworkMap is called when the control client gets a new network
// map from the control server. It must always be non-nil.
//
// It should not use the DERPMap field of NetworkMap; that's
// conditionally sent to SetDERPMap instead.
func (c *Conn) SetNetworkMap(nm *netmap.NetworkMap) {
c.mu.Lock()
defer c.mu.Unlock()
if c.netMap != nil && nodesEqual(c.netMap.Peers, nm.Peers) {
return
}
numDisco := 0
for _, n := range nm.Peers {
if n.DiscoKey.IsZero() {
continue
}
numDisco++
if ep, ok := c.endpointOfDisco[n.DiscoKey]; ok && ep.publicKey == n.Key {
ep.updateFromNode(n)
} else if ok {
c.logf("magicsock: disco key %v changed from node key %v to %v", n.DiscoKey, ep.publicKey.ShortString(), n.Key.ShortString())
ep.stopAndReset()
delete(c.endpointOfDisco, n.DiscoKey)
}
}
c.logf("[v1] magicsock: got updated network map; %d peers (%d with discokey)", len(nm.Peers), numDisco)
c.netMap = nm
// Build and/or update node<->disco maps, only reallocating if
// the set of discokeys changed.
for pass := 1; pass <= 2; pass++ {
if c.nodeOfDisco == nil || pass == 2 {
c.nodeOfDisco = map[tailcfg.DiscoKey]*tailcfg.Node{}
c.discoOfNode = map[tailcfg.NodeKey]tailcfg.DiscoKey{}
}
for _, n := range nm.Peers {
if !n.DiscoKey.IsZero() {
c.nodeOfDisco[n.DiscoKey] = n
if old, ok := c.discoOfNode[n.Key]; ok && old != n.DiscoKey {
c.logf("magicsock: node %s changed discovery key from %x to %x", n.Key.ShortString(), old[:8], n.DiscoKey[:8])
}
c.discoOfNode[n.Key] = n.DiscoKey
}
}
if len(c.nodeOfDisco) == numDisco && len(c.discoOfNode) == numDisco {
break
}
}
// Clean c.endpointOfDisco for discovery keys that are no longer present.
for dk, de := range c.endpointOfDisco {
if _, ok := c.nodeOfDisco[dk]; !ok {
de.stopAndReset()
delete(c.endpointOfDisco, dk)
delete(c.sharedDiscoKey, dk)
}
}
}
func (c *Conn) wantDerpLocked() bool { return c.derpMap != nil }
// c.mu must be held.
func (c *Conn) closeAllDerpLocked(why string) {
if len(c.activeDerp) == 0 {
return // without the useless log statement
}
for i := range c.activeDerp {
c.closeDerpLocked(i, why)
}
c.logActiveDerpLocked()
}
// c.mu must be held.
// It is the responsibility of the caller to call logActiveDerpLocked after any set of closes.
func (c *Conn) closeDerpLocked(node int, why string) {
if ad, ok := c.activeDerp[node]; ok {
c.logf("magicsock: closing connection to derp-%v (%v), age %v", node, why, time.Since(ad.createTime).Round(time.Second))
go ad.c.Close()
ad.cancel()
delete(c.activeDerp, node)
}
}
// c.mu must be held.
func (c *Conn) logActiveDerpLocked() {
now := time.Now()
c.logf("magicsock: %v active derp conns%s", len(c.activeDerp), logger.ArgWriter(func(buf *bufio.Writer) {
if len(c.activeDerp) == 0 {
return
}
buf.WriteString(":")
c.foreachActiveDerpSortedLocked(func(node int, ad activeDerp) {
fmt.Fprintf(buf, " derp-%d=cr%v,wr%v", node, simpleDur(now.Sub(ad.createTime)), simpleDur(now.Sub(*ad.lastWrite)))
})
}))
}
func (c *Conn) logEndpointChange(endpoints []string, reasons map[string]string) {
c.logf("magicsock: endpoints changed: %s", logger.ArgWriter(func(buf *bufio.Writer) {
for i, ep := range endpoints {
if i > 0 {
buf.WriteString(", ")
}
fmt.Fprintf(buf, "%s (%s)", ep, reasons[ep])
}
}))
}
// c.mu must be held.
func (c *Conn) foreachActiveDerpSortedLocked(fn func(regionID int, ad activeDerp)) {
if len(c.activeDerp) < 2 {
for id, ad := range c.activeDerp {
fn(id, ad)
}
return
}
ids := make([]int, 0, len(c.activeDerp))
for id := range c.activeDerp {
ids = append(ids, id)
}
sort.Ints(ids)
for _, id := range ids {
fn(id, c.activeDerp[id])
}
}
func (c *Conn) cleanStaleDerp() {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return
}
c.derpCleanupTimerArmed = false
tooOld := time.Now().Add(-derpInactiveCleanupTime)
dirty := false
someNonHomeOpen := false
for i, ad := range c.activeDerp {
if i == c.myDerp {
continue
}
if ad.lastWrite.Before(tooOld) {
c.closeDerpLocked(i, "idle")
dirty = true
} else {
someNonHomeOpen = true
}
}
if dirty {
c.logActiveDerpLocked()
}
if someNonHomeOpen {
c.scheduleCleanStaleDerpLocked()
}
}
func (c *Conn) scheduleCleanStaleDerpLocked() {
if c.derpCleanupTimerArmed {
// Already going to fire soon. Let the existing one
// fire lest it get infinitely delayed by repeated
// calls to scheduleCleanStaleDerpLocked.
return
}
c.derpCleanupTimerArmed = true
if c.derpCleanupTimer != nil {
c.derpCleanupTimer.Reset(derpCleanStaleInterval)
} else {
c.derpCleanupTimer = time.AfterFunc(derpCleanStaleInterval, c.cleanStaleDerp)
}
}
// DERPs reports the number of active DERP connections.
func (c *Conn) DERPs() int {
c.mu.Lock()
defer c.mu.Unlock()
return len(c.activeDerp)
}
func (c *Conn) SetMark(value uint32) error { return nil }
func (c *Conn) LastMark() uint32 { return 0 }
// Close closes the connection.
//
// Only the first close does anything. Any later closes return nil.
func (c *Conn) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return nil
}
if c.derpCleanupTimerArmed {
c.derpCleanupTimer.Stop()
}
c.stopPeriodicReSTUNTimerLocked()
c.portMapper.Close()
for _, ep := range c.endpointOfDisco {
ep.stopAndReset()
}
c.closed = true
c.connCtxCancel()
c.closeAllDerpLocked("conn-close")
if c.pconn6 != nil {
c.pconn6.Close()
}
err := c.pconn4.Close()
// Wait on goroutines updating right at the end, once everything is
// already closed. We want everything else in the Conn to be
// consistently in the closed state before we release mu to wait
// on the endpoint updater & derphttp.Connect.
for c.goroutinesRunningLocked() {
c.muCond.Wait()
}
return err
}
func (c *Conn) goroutinesRunningLocked() bool {
if c.endpointsUpdateActive {
return true
}
// The goroutine running dc.Connect in derpWriteChanOfAddr may linger
// and appear to leak, as observed in https://github.com/tailscale/tailscale/issues/554.
// This is despite the underlying context being cancelled by connCtxCancel above.
// To avoid this condition, we must wait on derpStarted here
// to ensure that this goroutine has exited by the time Close returns.
// We only do this if derpWriteChanOfAddr has executed at least once:
// on the first run, it sets firstDerp := true and spawns the aforementioned goroutine.
// To detect this, we check activeDerp, which is initialized to non-nil on the first run.
if c.activeDerp != nil {
select {
case <-c.derpStarted:
break
default:
return true
}
}
return false
}
func maxIdleBeforeSTUNShutdown() time.Duration {
if debugReSTUNStopOnIdle {
return 45 * time.Second
}
return sessionActiveTimeout
}
func (c *Conn) shouldDoPeriodicReSTUNLocked() bool {
if c.networkDown() {
return false
}
if len(c.peerSet) == 0 || c.privateKey.IsZero() {
// If no peers, not worth doing.
// Also don't if there's no key (not running).
return false
}
if f := c.idleFunc; f != nil {
idleFor := f()
if debugReSTUNStopOnIdle {
c.logf("magicsock: periodicReSTUN: idle for %v", idleFor.Round(time.Second))
}
if idleFor > maxIdleBeforeSTUNShutdown() {
if c.netMap != nil && c.netMap.Debug != nil && c.netMap.Debug.ForceBackgroundSTUN {
// Overridden by control.
return true
}
return false
}
}
return true
}
// ReSTUN triggers an address discovery.
// The provided why string is for debug logging only.
func (c *Conn) ReSTUN(why string) {
c.mu.Lock()
defer c.mu.Unlock()
if !c.started {
panic("call to ReSTUN before Start")
}
if c.closed {
// raced with a shutdown.
return
}
// If the user stopped the app, stop doing work. (When the
// user stops Tailscale via the GUI apps, ipn/local.go
// reconfigures the engine with a zero private key.)
//
// This used to just check c.privateKey.IsZero, but that broke
// some end-to-end tests tests that didn't ever set a private
// key somehow. So for now, only stop doing work if we ever
// had a key, which helps real users, but appeases tests for
// now. TODO: rewrite those tests to be less brittle or more
// realistic.
if c.privateKey.IsZero() && c.everHadKey {
c.logf("magicsock: ReSTUN(%q) ignored; stopped, no private key", why)
return
}
if c.endpointsUpdateActive {
if c.wantEndpointsUpdate != why {
c.logf("[v1] magicsock: ReSTUN: endpoint update active, need another later (%q)", why)
c.wantEndpointsUpdate = why
}
} else {
c.endpointsUpdateActive = true
go c.updateEndpoints(why)
}
}
func (c *Conn) initialBind() error {
if err := c.bind1(&c.pconn4, "udp4"); err != nil {
return err
}
c.portMapper.SetLocalPort(c.LocalPort())
if err := c.bind1(&c.pconn6, "udp6"); err != nil {
c.logf("magicsock: ignoring IPv6 bind failure: %v", err)
}
return nil
}
func (c *Conn) listenPacket(ctx context.Context, network, addr string) (net.PacketConn, error) {
if c.packetListener != nil {
return c.packetListener.ListenPacket(ctx, network, addr)
}
return netns.Listener().ListenPacket(ctx, network, addr)
}
func (c *Conn) bind1(ruc **RebindingUDPConn, which string) error {
host := ""
if inTest() && !c.simulatedNetwork {
host = "127.0.0.1"
if which == "udp6" {
host = "::1"
}
}
var pc net.PacketConn
var err error
listenCtx := context.Background() // unused without DNS name to resolve
if c.port == 0 && DefaultPort != 0 {
pc, err = c.listenPacket(listenCtx, which, net.JoinHostPort(host, fmt.Sprint(DefaultPort)))
if err != nil {
c.logf("magicsock: bind: default port %s/%v unavailable; picking random", which, DefaultPort)
}
}
if pc == nil {
pc, err = c.listenPacket(listenCtx, which, net.JoinHostPort(host, fmt.Sprint(c.port)))
}
if err != nil {
c.logf("magicsock: bind(%s/%v): %v", which, c.port, err)
return fmt.Errorf("magicsock: bind: %s/%d: %v", which, c.port, err)
}
if *ruc == nil {
*ruc = new(RebindingUDPConn)
}
(*ruc).Reset(pc)
return nil
}
// Rebind closes and re-binds the UDP sockets.
// It should be followed by a call to ReSTUN.
func (c *Conn) Rebind() {
host := ""
if inTest() && !c.simulatedNetwork {
host = "127.0.0.1"
}
listenCtx := context.Background() // unused without DNS name to resolve
if c.port != 0 {
c.pconn4.mu.Lock()
oldPort := c.pconn4.localAddrLocked().Port
if err := c.pconn4.pconn.Close(); err != nil {
c.logf("magicsock: link change close failed: %v", err)
}
packetConn, err := c.listenPacket(listenCtx, "udp4", net.JoinHostPort(host, fmt.Sprint(c.port)))
if err != nil {
c.logf("magicsock: link change unable to bind fixed port %d: %v, falling back to random port", c.port, err)
packetConn, err = c.listenPacket(listenCtx, "udp4", net.JoinHostPort(host, "0"))
if err != nil {
c.logf("magicsock: link change failed to bind random port: %v", err)
c.pconn4.mu.Unlock()
return
}
newPort := c.pconn4.localAddrLocked().Port
c.logf("magicsock: link change rebound port: from %v to %v (failed to get %v)", oldPort, newPort, c.port)
} else {
c.logf("magicsock: link change rebound port: %d", c.port)
}
c.pconn4.pconn = packetConn.(*net.UDPConn)
c.pconn4.mu.Unlock()
} else {
c.logf("magicsock: link change, binding new port")
packetConn, err := c.listenPacket(listenCtx, "udp4", host+":0")
if err != nil {
c.logf("magicsock: link change failed to bind new port: %v", err)
return
}
c.pconn4.Reset(packetConn.(*net.UDPConn))
}
c.portMapper.SetLocalPort(c.LocalPort())
c.mu.Lock()
c.closeAllDerpLocked("rebind")
if !c.privateKey.IsZero() {
c.startDerpHomeConnectLocked()
}
c.mu.Unlock()
c.resetEndpointStates()
}
// resetEndpointStates resets the preferred address for all peers and
// re-enables spraying.
// This is called when connectivity changes enough that we no longer
// trust the old routes.
func (c *Conn) resetEndpointStates() {
c.mu.Lock()
defer c.mu.Unlock()
for _, de := range c.endpointOfDisco {
de.noteConnectivityChange()
}
c.resetAddrSetStatesLocked()
}
// packIPPort packs an IPPort into the form wanted by WireGuard.
func packIPPort(ua netaddr.IPPort) []byte {
ip := ua.IP.Unmap()
a := ip.As16()
ipb := a[:]
if ip.Is4() {
ipb = ipb[12:]
}
b := make([]byte, 0, len(ipb)+2)
b = append(b, ipb...)
b = append(b, byte(ua.Port))
b = append(b, byte(ua.Port>>8))
return b
}
// CreateBind is called by WireGuard to create a UDP binding.
func (c *Conn) CreateBind(uint16) (conn.Bind, uint16, error) {
return c, c.LocalPort(), nil
}
// CreateEndpoint is called by WireGuard to connect to an endpoint.
//
// The key is the public key of the peer and addrs is either:
//
// 1) a comma-separated list of UDP ip:ports (the peer doesn't have a discovery key)
// 2) "<hex-discovery-key>.disco.tailscale:12345", a magic value that means the peer
// is running code that supports active discovery, so CreateEndpoint returns
// a discoEndpoint.
//
func (c *Conn) CreateEndpoint(pubKey [32]byte, addrs string) (conn.Endpoint, error) {
c.mu.Lock()
defer c.mu.Unlock()
pk := key.Public(pubKey)
c.logf("magicsock: CreateEndpoint: key=%s: %s", pk.ShortString(), derpStr(addrs))
if !strings.HasSuffix(addrs, wgcfg.EndpointDiscoSuffix) {
return c.createLegacyEndpointLocked(pk, addrs)
}
discoHex := strings.TrimSuffix(addrs, wgcfg.EndpointDiscoSuffix)
discoKey, err := key.NewPublicFromHexMem(mem.S(discoHex))
if err != nil {
return nil, fmt.Errorf("magicsock: invalid discokey endpoint %q for %v: %w", addrs, pk.ShortString(), err)
}
de := &discoEndpoint{
c: c,
publicKey: tailcfg.NodeKey(pk), // peer public key (for WireGuard + DERP)
discoKey: tailcfg.DiscoKey(discoKey), // for discovery mesages
discoShort: tailcfg.DiscoKey(discoKey).ShortString(),
wgEndpointHostPort: addrs,
sentPing: map[stun.TxID]sentPing{},
endpointState: map[netaddr.IPPort]*endpointState{},
}
de.initFakeUDPAddr()
de.updateFromNode(c.nodeOfDisco[de.discoKey])
c.endpointOfDisco[de.discoKey] = de
return de, nil
}
// RebindingUDPConn is a UDP socket that can be re-bound.
// Unix has no notion of re-binding a socket, so we swap it out for a new one.
type RebindingUDPConn struct {
mu sync.Mutex
pconn net.PacketConn
}
func (c *RebindingUDPConn) Reset(pconn net.PacketConn) {
c.mu.Lock()
old := c.pconn
c.pconn = pconn
c.mu.Unlock()
if old != nil {
old.Close()
}
}
// ReadFromNetaddr reads a packet from c into b.
// It returns the number of bytes copied and the source address.
func (c *RebindingUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {
for {
c.mu.Lock()
pconn := c.pconn
c.mu.Unlock()
n, addr, err := pconn.ReadFrom(b)
if err != nil {
c.mu.Lock()
pconn2 := c.pconn
c.mu.Unlock()
if pconn != pconn2 {
continue
}
}
return n, addr, err
}
}
// ReadFromNetaddr reads a packet from c into b.
// It returns the number of bytes copied and the return address.
// It is identical to c.ReadFrom, except that it returns a netaddr.IPPort instead of a net.Addr.
// ReadFromNetaddr is designed to work with specific underlying connection types.
// If c's underlying connection returns a non-*net.UPDAddr return address, ReadFromNetaddr will return an error.
// ReadFromNetaddr exists because it removes an allocation per read,
// when c's underlying connection is a net.UDPConn.
func (c *RebindingUDPConn) ReadFromNetaddr(b []byte) (n int, ipp netaddr.IPPort, err error) {
for {
c.mu.Lock()
pconn := c.pconn
c.mu.Unlock()
// Optimization: Treat *net.UDPConn specially.
// ReadFromUDP gets partially inlined, avoiding allocating a *net.UDPAddr,
// as long as pAddr itself doesn't escape.
// The non-*net.UDPConn case works, but it allocates.
var pAddr *net.UDPAddr
if udpConn, ok := pconn.(*net.UDPConn); ok {
n, pAddr, err = udpConn.ReadFromUDP(b)
} else {
var addr net.Addr
n, addr, err = pconn.ReadFrom(b)
if addr != nil {
pAddr, ok = addr.(*net.UDPAddr)
if !ok {
return 0, netaddr.IPPort{}, fmt.Errorf("RebindingUDPConn.ReadFromNetaddr: underlying connection returned address of type %T, want *netaddr.UDPAddr", addr)
}
}
}
if err != nil {
c.mu.Lock()
pconn2 := c.pconn
c.mu.Unlock()
if pconn != pconn2 {
continue
}
} else {
// Convert pAddr to a netaddr.IPPort.
// This prevents pAddr from escaping.
var ok bool
ipp, ok = netaddr.FromStdAddr(pAddr.IP, pAddr.Port, pAddr.Zone)
if !ok {
return 0, netaddr.IPPort{}, errors.New("netaddr.FromStdAddr failed")
}
}
return n, ipp, err
}
}
func (c *RebindingUDPConn) LocalAddr() *net.UDPAddr {
c.mu.Lock()
defer c.mu.Unlock()
return c.localAddrLocked()
}
func (c *RebindingUDPConn) localAddrLocked() *net.UDPAddr {
return c.pconn.LocalAddr().(*net.UDPAddr)
}
func (c *RebindingUDPConn) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
return c.pconn.Close()
}
func (c *RebindingUDPConn) SetReadDeadline(t time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
c.pconn.SetReadDeadline(t)
}
func (c *RebindingUDPConn) WriteToUDP(b []byte, addr *net.UDPAddr) (int, error) {
for {
c.mu.Lock()
pconn := c.pconn
c.mu.Unlock()
n, err := pconn.WriteTo(b, addr)
if err != nil {
c.mu.Lock()
pconn2 := c.pconn
c.mu.Unlock()
if pconn != pconn2 {
continue
}
}
return n, err
}
}
func (c *RebindingUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
for {
c.mu.Lock()
pconn := c.pconn
c.mu.Unlock()
n, err := pconn.WriteTo(b, addr)
if err != nil {
c.mu.Lock()
pconn2 := c.pconn
c.mu.Unlock()
if pconn != pconn2 {
continue
}
}
return n, err
}
}
// simpleDur rounds d such that it stringifies to something short.
func simpleDur(d time.Duration) time.Duration {
if d < time.Second {
return d.Round(time.Millisecond)
}
if d < time.Minute {
return d.Round(time.Second)
}
return d.Round(time.Minute)
}
func peerShort(k key.Public) string {
k2 := wgkey.Key(k)
return k2.ShortString()
}
func sbPrintAddr(sb *strings.Builder, a netaddr.IPPort) {
is6 := a.IP.Is6()
if is6 {
sb.WriteByte('[')
}
fmt.Fprintf(sb, "%s", a.IP)
if is6 {
sb.WriteByte(']')
}
fmt.Fprintf(sb, ":%d", a.Port)
}
func (c *Conn) derpRegionCodeOfAddrLocked(ipPort string) string {
_, portStr, err := net.SplitHostPort(ipPort)
if err != nil {
return ""
}
regionID, err := strconv.Atoi(portStr)
if err != nil {
return ""
}
return c.derpRegionCodeOfIDLocked(regionID)
}
func (c *Conn) derpRegionCodeOfIDLocked(regionID int) string {
if c.derpMap == nil {
return ""
}
if r, ok := c.derpMap.Regions[regionID]; ok {
return r.RegionCode
}
return ""
}
func (c *Conn) UpdateStatus(sb *ipnstate.StatusBuilder) {
c.mu.Lock()
defer c.mu.Unlock()
ss := &ipnstate.PeerStatus{
PublicKey: c.privateKey.Public(),
Addrs: c.lastEndpoints,
OS: version.OS(),
}
if c.netMap != nil {
ss.HostName = c.netMap.Hostinfo.Hostname
ss.DNSName = c.netMap.Name
ss.UserID = c.netMap.User
} else {
ss.HostName, _ = os.Hostname()
}
if c.derpMap != nil {
derpRegion, ok := c.derpMap.Regions[c.myDerp]
if ok {
ss.Relay = derpRegion.RegionCode
}
}
if c.netMap != nil {
for _, addr := range c.netMap.Addresses {
if !addr.IsSingleIP() {
continue
}
sb.AddTailscaleIP(addr.IP)
// TailAddr only allows for a single Tailscale IP. For
// readability of `tailscale status`, make it the IPv4
// address.
if addr.IP.Is4() {
ss.TailAddr = addr.IP.String()
}
}
}
sb.SetSelfStatus(ss)
for dk, n := range c.nodeOfDisco {
ps := &ipnstate.PeerStatus{InMagicSock: true}
ps.Addrs = append(ps.Addrs, n.Endpoints...)
ps.Relay = c.derpRegionCodeOfAddrLocked(n.DERP)
if de, ok := c.endpointOfDisco[dk]; ok {
de.populatePeerStatus(ps)
}
sb.AddPeer(key.Public(n.Key), ps)
}
// Old-style (pre-disco) peers:
for k, as := range c.addrsByKey {
ps := &ipnstate.PeerStatus{
InMagicSock: true,
Relay: c.derpRegionCodeOfIDLocked(as.derpID()),
}
as.populatePeerStatus(ps)
sb.AddPeer(k, ps)
}
c.foreachActiveDerpSortedLocked(func(node int, ad activeDerp) {
// TODO(bradfitz): add to ipnstate.StatusBuilder
//f("<li><b>derp-%v</b>: cr%v,wr%v</li>", node, simpleDur(now.Sub(ad.createTime)), simpleDur(now.Sub(*ad.lastWrite)))
})
}
func ippDebugString(ua netaddr.IPPort) string {
if ua.IP == derpMagicIPAddr {
return fmt.Sprintf("derp-%d", ua.Port)
}
return ua.String()
}
// discoEndpoint is a wireguard/conn.Endpoint for new-style peers that
// advertise a DiscoKey and participate in active discovery.
type discoEndpoint struct {
// atomically accessed; declared first for alignment reasons
lastRecvUnixAtomic int64
numStopAndResetAtomic int64
// These fields are initialized once and never modified.
c *Conn
publicKey tailcfg.NodeKey // peer public key (for WireGuard + DERP)
discoKey tailcfg.DiscoKey // for discovery mesages
discoShort string // ShortString of discoKey
fakeWGAddr netaddr.IPPort // the UDP address we tell wireguard-go we're using
wgEndpointHostPort string // string from CreateEndpoint: "<hex-discovery-key>.disco.tailscale:12345"
// Owned by Conn.mu:
lastPingFrom netaddr.IPPort
lastPingTime time.Time
// mu protects all following fields.
mu sync.Mutex // Lock ordering: Conn.mu, then discoEndpoint.mu
heartBeatTimer *time.Timer // nil when idle
lastSend time.Time // last time there was outgoing packets sent to this peer (from wireguard-go)
lastFullPing time.Time // last time we pinged all endpoints
derpAddr netaddr.IPPort // fallback/bootstrap path, if non-zero (non-zero for well-behaved clients)
bestAddr netaddr.IPPort // best non-DERP path; zero if none
bestAddrLatency time.Duration
bestAddrAt time.Time // time best address re-confirmed
trustBestAddrUntil time.Time // time when bestAddr expires
sentPing map[stun.TxID]sentPing
endpointState map[netaddr.IPPort]*endpointState
isCallMeMaybeEP map[netaddr.IPPort]bool
pendingCLIPings []pendingCLIPing // any outstanding "tailscale ping" commands running
}
type pendingCLIPing struct {
res *ipnstate.PingResult
cb func(*ipnstate.PingResult)
}
const (
// sessionActiveTimeout is how long since the last activity we
// try to keep an established discoEndpoint peering alive.
// It's also the idle time at which we stop doing STUN queries to
// keep NAT mappings alive.
sessionActiveTimeout = 2 * time.Minute
// upgradeInterval is how often we try to upgrade to a better path
// even if we have some non-DERP route that works.
upgradeInterval = 1 * time.Minute
// heartbeatInterval is how often pings to the best UDP address
// are sent.
heartbeatInterval = 2 * time.Second
// discoPingInterval is the minimum time between pings
// to an endpoint. (Except in the case of CallMeMaybe frames
// resetting the counter, as the first pings likely didn't through
// the firewall)
discoPingInterval = 5 * time.Second
// pingTimeoutDuration is how long we wait for a pong reply before
// assuming it's never coming.
pingTimeoutDuration = 5 * time.Second
// trustUDPAddrDuration is how long we trust a UDP address as the exclusive
// path (without using DERP) without having heard a Pong reply.
trustUDPAddrDuration = 5 * time.Second
// goodEnoughLatency is the latency at or under which we don't
// try to upgrade to a better path.
goodEnoughLatency = 5 * time.Millisecond
// derpInactiveCleanupTime is how long a non-home DERP connection
// needs to be idle (last written to) before we close it.
derpInactiveCleanupTime = 60 * time.Second
// derpCleanStaleInterval is how often cleanStaleDerp runs when there
// are potentially-stale DERP connections to close.
derpCleanStaleInterval = 15 * time.Second
// endpointsFreshEnoughDuration is how long we consider a
// STUN-derived endpoint valid for. UDP NAT mappings typically
// expire at 30 seconds, so this is a few seconds shy of that.
endpointsFreshEnoughDuration = 27 * time.Second
)
// endpointState is some state and history for a specific endpoint of
// a discoEndpoint. (The subject is the discoEndpoint.endpointState
// map key)
type endpointState struct {
// all fields guarded by discoEndpoint.mu
// lastPing is the last (outgoing) ping time.
lastPing time.Time
// lastGotPing, if non-zero, means that this was an endpoint
// that we learned about at runtime (from an incoming ping)
// and that is not in the network map. If so, we keep the time
// updated and use it to discard old candidates.
lastGotPing time.Time
// callMeMaybeTime, if non-zero, is the time this endpoint
// was advertised last via a call-me-maybe disco message.
callMeMaybeTime time.Time
recentPongs []pongReply // ring buffer up to pongHistoryCount entries
recentPong uint16 // index into recentPongs of most recent; older before, wrapped
index int16 // index in nodecfg.Node.Endpoints; meaningless if lastGotPing non-zero
}
// indexSentinelDeleted is the temporary value that endpointState.index takes while
// a discoEndpoint's endpoints are being updated from a new network map.
const indexSentinelDeleted = -1
// shouldDeleteLocked reports whether we should delete this endpoint.
func (st *endpointState) shouldDeleteLocked() bool {
switch {
case !st.callMeMaybeTime.IsZero():
return false
case st.lastGotPing.IsZero():
// This was an endpoint from the network map. Is it still in the network map?
return st.index == indexSentinelDeleted
default:
// This was an endpoint discovered at runtime.
return time.Since(st.lastGotPing) > sessionActiveTimeout
}
}
func (de *discoEndpoint) deleteEndpointLocked(ep netaddr.IPPort) {
delete(de.endpointState, ep)
if de.bestAddr == ep {
de.bestAddr = netaddr.IPPort{}
}
}
// pongHistoryCount is how many pongReply values we keep per endpointState
const pongHistoryCount = 64
type pongReply struct {
latency time.Duration
pongAt time.Time // when we received the pong
from netaddr.IPPort // the pong's src (usually same as endpoint map key)
pongSrc netaddr.IPPort // what they reported they heard
}
type sentPing struct {
to netaddr.IPPort
at time.Time
timer *time.Timer // timeout timer
purpose discoPingPurpose
}
// initFakeUDPAddr populates fakeWGAddr with a globally unique fake UDPAddr.
// The current implementation just uses the pointer value of de jammed into an IPv6
// address, but it could also be, say, a counter.
func (de *discoEndpoint) initFakeUDPAddr() {
var addr [16]byte
addr[0] = 0xfd
addr[1] = 0x00
binary.BigEndian.PutUint64(addr[2:], uint64(reflect.ValueOf(de).Pointer()))
de.fakeWGAddr = netaddr.IPPort{
IP: netaddr.IPFrom16(addr),
Port: 12345,
}
}
// isFirstRecvActivityInAwhile notes that receive activity has occured for this
// endpoint and reports whether it's been at least 10 seconds since the last
// receive activity (including having never received from this peer before).
func (de *discoEndpoint) isFirstRecvActivityInAwhile() bool {
now := time.Now().Unix()
old := atomic.LoadInt64(&de.lastRecvUnixAtomic)
if old <= now-10 {
atomic.StoreInt64(&de.lastRecvUnixAtomic, now)
return true
}
return false
}
// String exists purely so wireguard-go internals can log.Printf("%v")
// its internal conn.Endpoints and we don't end up with data races
// from fmt (via log) reading mutex fields and such.
func (de *discoEndpoint) String() string {
return fmt.Sprintf("magicsock.discoEndpoint{%v, %v}", de.publicKey.ShortString(), de.discoShort)
}
func (de *discoEndpoint) ClearSrc() {}
func (de *discoEndpoint) SrcToString() string { panic("unused") } // unused by wireguard-go
func (de *discoEndpoint) SrcIP() net.IP { panic("unused") } // unused by wireguard-go
func (de *discoEndpoint) DstToString() string { return de.wgEndpointHostPort }
func (de *discoEndpoint) DstIP() net.IP { panic("unused") }
func (de *discoEndpoint) DstToBytes() []byte { return packIPPort(de.fakeWGAddr) }
// addrForSendLocked returns the address(es) that should be used for
// sending the next packet. Zero, one, or both of UDP address and DERP
// addr may be non-zero.
//
// de.mu must be held.
func (de *discoEndpoint) addrForSendLocked(now time.Time) (udpAddr, derpAddr netaddr.IPPort) {
udpAddr = de.bestAddr
if udpAddr.IsZero() || now.After(de.trustBestAddrUntil) {
// We had a bestAddr but it expired so send both to it
// and DERP.
derpAddr = de.derpAddr
}
return
}
// heartbeat is called every heartbeatInterval to keep the best UDP path alive,
// or kick off discovery of other paths.
func (de *discoEndpoint) heartbeat() {
de.mu.Lock()
defer de.mu.Unlock()
de.heartBeatTimer = nil
if de.lastSend.IsZero() {
// Shouldn't happen.
return
}
if time.Since(de.lastSend) > sessionActiveTimeout {
// Session's idle. Stop heartbeating.
de.c.logf("[v1] magicsock: disco: ending heartbeats for idle session to %v (%v)", de.publicKey.ShortString(), de.discoShort)
return
}
now := time.Now()
udpAddr, _ := de.addrForSendLocked(now)
if !udpAddr.IsZero() {
// We have a preferred path. Ping that every 2 seconds.
de.startPingLocked(udpAddr, now, pingHeartbeat)
}
if de.wantFullPingLocked(now) {
de.sendPingsLocked(now, true)
}
de.heartBeatTimer = time.AfterFunc(heartbeatInterval, de.heartbeat)
}
// wantFullPingLocked reports whether we should ping to all our peers looking for
// a better path.
//
// de.mu must be held.
func (de *discoEndpoint) wantFullPingLocked(now time.Time) bool {
if de.bestAddr.IsZero() || de.lastFullPing.IsZero() {
return true
}
if now.After(de.trustBestAddrUntil) {
return true
}
if de.bestAddrLatency <= goodEnoughLatency {
return false
}
if now.Sub(de.lastFullPing) >= upgradeInterval {
return true
}
return false
}
func (de *discoEndpoint) noteActiveLocked() {
de.lastSend = time.Now()
if de.heartBeatTimer == nil {
de.heartBeatTimer = time.AfterFunc(heartbeatInterval, de.heartbeat)
}
}
// cliPing starts a ping for the "tailscale ping" command. res is value to call cb with,
// already partially filled.
func (de *discoEndpoint) cliPing(res *ipnstate.PingResult, cb func(*ipnstate.PingResult)) {
de.mu.Lock()
defer de.mu.Unlock()
de.pendingCLIPings = append(de.pendingCLIPings, pendingCLIPing{res, cb})
now := time.Now()
udpAddr, derpAddr := de.addrForSendLocked(now)
if !derpAddr.IsZero() {
de.startPingLocked(derpAddr, now, pingCLI)
}
if !udpAddr.IsZero() && now.Before(de.trustBestAddrUntil) {
// Already have an active session, so just ping the address we're using.
// Otherwise "tailscale ping" results to a node on the local network
// can look like they're bouncing between, say 10.0.0.0/9 and the peer's
// IPv6 address, both 1ms away, and it's random who replies first.
de.startPingLocked(udpAddr, now, pingCLI)
} else {
for ep := range de.endpointState {
de.startPingLocked(ep, now, pingCLI)
}
}
de.noteActiveLocked()
}
func (de *discoEndpoint) send(b []byte) error {
now := time.Now()
de.mu.Lock()
udpAddr, derpAddr := de.addrForSendLocked(now)
if udpAddr.IsZero() || now.After(de.trustBestAddrUntil) {
de.sendPingsLocked(now, true)
}
de.noteActiveLocked()
de.mu.Unlock()
if udpAddr.IsZero() && derpAddr.IsZero() {
return errors.New("no UDP or DERP addr")
}
var err error
if !udpAddr.IsZero() {
_, err = de.c.sendAddr(udpAddr, key.Public(de.publicKey), b)
}
if !derpAddr.IsZero() {
if ok, _ := de.c.sendAddr(derpAddr, key.Public(de.publicKey), b); ok && err != nil {
// UDP failed but DERP worked, so good enough:
return nil
}
}
return err
}
func (de *discoEndpoint) pingTimeout(txid stun.TxID) {
de.mu.Lock()
defer de.mu.Unlock()
sp, ok := de.sentPing[txid]
if !ok {
return
}
if debugDisco || de.bestAddr.IsZero() || time.Now().After(de.trustBestAddrUntil) {
de.c.logf("[v1] magicsock: disco: timeout waiting for pong %x from %v (%v, %v)", txid[:6], sp.to, de.publicKey.ShortString(), de.discoShort)
}
de.removeSentPingLocked(txid, sp)
}
// forgetPing is called by a timer when a ping either fails to send or
// has taken too long to get a pong reply.
func (de *discoEndpoint) forgetPing(txid stun.TxID) {
de.mu.Lock()
defer de.mu.Unlock()
if sp, ok := de.sentPing[txid]; ok {
de.removeSentPingLocked(txid, sp)
}
}
func (de *discoEndpoint) removeSentPingLocked(txid stun.TxID, sp sentPing) {
// Stop the timer for the case where sendPing failed to write to UDP.
// In the case of a timer already having fired, this is a no-op:
sp.timer.Stop()
delete(de.sentPing, txid)
}
// sendDiscoPing sends a ping with the provided txid to ep.
//
// The caller (startPingLocked) should've already been recorded the ping in
// sentPing and set up the timer.
func (de *discoEndpoint) sendDiscoPing(ep netaddr.IPPort, txid stun.TxID, logLevel discoLogLevel) {
sent, _ := de.sendDiscoMessage(ep, &disco.Ping{TxID: [12]byte(txid)}, logLevel)
if !sent {
de.forgetPing(txid)
}
}
// discoPingPurpose is the reason why a discovery ping message was sent.
type discoPingPurpose int
//go:generate stringer -type=discoPingPurpose -trimprefix=ping
const (
// pingDiscovery means that purpose of a ping was to see if a
// path was valid.
pingDiscovery discoPingPurpose = iota
// pingHeartbeat means that purpose of a ping was whether a
// peer was still there.
pingHeartbeat
// pingCLI means that the user is running "tailscale ping"
// from the CLI. These types of pings can go over DERP.
pingCLI
)
func (de *discoEndpoint) startPingLocked(ep netaddr.IPPort, now time.Time, purpose discoPingPurpose) {
if purpose != pingCLI {
st, ok := de.endpointState[ep]
if !ok {
// Shouldn't happen. But don't ping an endpoint that's
// not active for us.
de.c.logf("magicsock: disco: [unexpected] attempt to ping no longer live endpoint %v", ep)
return
}
st.lastPing = now
}
txid := stun.NewTxID()
de.sentPing[txid] = sentPing{
to: ep,
at: now,
timer: time.AfterFunc(pingTimeoutDuration, func() { de.pingTimeout(txid) }),
purpose: purpose,
}
logLevel := discoLog
if purpose == pingHeartbeat {
logLevel = discoVerboseLog
}
go de.sendDiscoPing(ep, txid, logLevel)
}
func (de *discoEndpoint) sendPingsLocked(now time.Time, sendCallMeMaybe bool) {
de.lastFullPing = now
var sentAny bool
for ep, st := range de.endpointState {
if st.shouldDeleteLocked() {
de.deleteEndpointLocked(ep)
continue
}
if !st.lastPing.IsZero() && now.Sub(st.lastPing) < discoPingInterval {
continue
}
firstPing := !sentAny
sentAny = true
if firstPing && sendCallMeMaybe {
de.c.logf("[v1] magicsock: disco: send, starting discovery for %v (%v)", de.publicKey.ShortString(), de.discoShort)
}
de.startPingLocked(ep, now, pingDiscovery)
}
derpAddr := de.derpAddr
if sentAny && sendCallMeMaybe && !derpAddr.IsZero() {
// Have our magicsock.Conn figure out its STUN endpoint (if
// it doesn't know already) and then send a CallMeMaybe
// message to our peer via DERP informing them that we've
// sent so our firewall ports are probably open and now
// would be a good time for them to connect.
go de.c.enqueueCallMeMaybe(derpAddr, de)
}
}
func (de *discoEndpoint) sendDiscoMessage(dst netaddr.IPPort, dm disco.Message, logLevel discoLogLevel) (sent bool, err error) {
return de.c.sendDiscoMessage(dst, de.publicKey, de.discoKey, dm, logLevel)
}
func (de *discoEndpoint) updateFromNode(n *tailcfg.Node) {
if n == nil {
// TODO: log, error, count? if this even happens.
return
}
de.mu.Lock()
defer de.mu.Unlock()
if n.DERP == "" {
de.derpAddr = netaddr.IPPort{}
} else {
de.derpAddr, _ = netaddr.ParseIPPort(n.DERP)
}
for _, st := range de.endpointState {
st.index = indexSentinelDeleted // assume deleted until updated in next loop
}
for i, epStr := range n.Endpoints {
if i > math.MaxInt16 {
// Seems unlikely.
continue
}
ipp, err := netaddr.ParseIPPort(epStr)
if err != nil {
de.c.logf("magicsock: bogus netmap endpoint %q", epStr)
continue
}
if st, ok := de.endpointState[ipp]; ok {
st.index = int16(i)
} else {
de.endpointState[ipp] = &endpointState{index: int16(i)}
}
}
// Now delete anything unless it's still in the network map or
// was a recently discovered endpoint.
for ep, st := range de.endpointState {
if st.shouldDeleteLocked() {
de.deleteEndpointLocked(ep)
}
}
}
// addCandidateEndpoint adds ep as an endpoint to which we should send
// future pings.
//
// This is called once we've already verified that we got a valid
// discovery message from de via ep.
func (de *discoEndpoint) addCandidateEndpoint(ep netaddr.IPPort) {
de.mu.Lock()
defer de.mu.Unlock()
if st, ok := de.endpointState[ep]; ok {
if st.lastGotPing.IsZero() {
// Already-known endpoint from the network map.
return
}
st.lastGotPing = time.Now()
return
}
// Newly discovered endpoint. Exciting!
de.c.logf("magicsock: disco: adding %v as candidate endpoint for %v (%s)", ep, de.discoShort, de.publicKey.ShortString())
de.endpointState[ep] = &endpointState{
lastGotPing: time.Now(),
}
// If for some reason this gets very large, do some cleanup.
if size := len(de.endpointState); size > 100 {
for ep, st := range de.endpointState {
if st.shouldDeleteLocked() {
de.deleteEndpointLocked(ep)
}
}
size2 := len(de.endpointState)
de.c.logf("magicsock: disco: addCandidateEndpoint pruned %v candidate set from %v to %v entries", size, size2)
}
}
// noteConnectivityChange is called when connectivity changes enough
// that we should question our earlier assumptions about which paths
// work.
func (de *discoEndpoint) noteConnectivityChange() {
de.mu.Lock()
defer de.mu.Unlock()
de.trustBestAddrUntil = time.Time{}
}
// handlePongConnLocked handles a Pong message (a reply to an earlier ping).
// It should be called with the Conn.mu held.
func (de *discoEndpoint) handlePongConnLocked(m *disco.Pong, src netaddr.IPPort) {
de.mu.Lock()
defer de.mu.Unlock()
isDerp := src.IP == derpMagicIPAddr
sp, ok := de.sentPing[m.TxID]
if !ok {
// This is not a pong for a ping we sent. Ignore.
return
}
de.removeSentPingLocked(m.TxID, sp)
now := time.Now()
latency := now.Sub(sp.at)
if !isDerp {
st, ok := de.endpointState[sp.to]
if !ok {
// This is no longer an endpoint we care about.
return
}
de.c.setAddrToDiscoLocked(src, de.discoKey, de)
st.addPongReplyLocked(pongReply{
latency: latency,
pongAt: now,
from: src,
pongSrc: m.Src,
})
}
if sp.purpose != pingHeartbeat {
de.c.logf("[v1] magicsock: disco: %v<-%v (%v, %v) got pong tx=%x latency=%v pong.src=%v%v", de.c.discoShort, de.discoShort, de.publicKey.ShortString(), src, m.TxID[:6], latency.Round(time.Millisecond), m.Src, logger.ArgWriter(func(bw *bufio.Writer) {
if sp.to != src {
fmt.Fprintf(bw, " ping.to=%v", sp.to)
}
}))
}
for _, pp := range de.pendingCLIPings {
de.c.populateCLIPingResponseLocked(pp.res, latency, sp.to)
go pp.cb(pp.res)
}
de.pendingCLIPings = nil
// Promote this pong response to our current best address if it's lower latency.
// TODO(bradfitz): decide how latency vs. preference order affects decision
if !isDerp {
if de.bestAddr.IsZero() || latency < de.bestAddrLatency {
if de.bestAddr != sp.to {
de.c.logf("magicsock: disco: node %v %v now using %v", de.publicKey.ShortString(), de.discoShort, sp.to)
de.bestAddr = sp.to
}
}
if de.bestAddr == sp.to {
de.bestAddrLatency = latency
de.bestAddrAt = now
de.trustBestAddrUntil = now.Add(trustUDPAddrDuration)
}
}
}
// discoEndpoint.mu must be held.
func (st *endpointState) addPongReplyLocked(r pongReply) {
if n := len(st.recentPongs); n < pongHistoryCount {
st.recentPong = uint16(n)
st.recentPongs = append(st.recentPongs, r)
return
}
i := st.recentPong + 1
if i == pongHistoryCount {
i = 0
}
st.recentPongs[i] = r
st.recentPong = i
}
// handleCallMeMaybe handles a CallMeMaybe discovery message via
// DERP. The contract for use of this message is that the peer has
// already sent to us via UDP, so their stateful firewall should be
// open. Now we can Ping back and make it through.
func (de *discoEndpoint) handleCallMeMaybe(m *disco.CallMeMaybe) {
de.mu.Lock()
defer de.mu.Unlock()
now := time.Now()
for ep := range de.isCallMeMaybeEP {
de.isCallMeMaybeEP[ep] = false // mark for deletion
}
if de.isCallMeMaybeEP == nil {
de.isCallMeMaybeEP = map[netaddr.IPPort]bool{}
}
var newEPs []netaddr.IPPort
for _, ep := range m.MyNumber {
if ep.IP.Is6() && ep.IP.IsLinkLocalUnicast() {
// We send these out, but ignore them for now.
// TODO: teach the ping code to ping on all interfaces
// for these.
continue
}
de.isCallMeMaybeEP[ep] = true
if es, ok := de.endpointState[ep]; ok {
es.callMeMaybeTime = now
} else {
de.endpointState[ep] = &endpointState{callMeMaybeTime: now}
newEPs = append(newEPs, ep)
}
}
if len(newEPs) > 0 {
de.c.logf("magicsock: disco: call-me-maybe from %v %v added new endpoints: %v",
de.publicKey.ShortString(), de.discoShort,
logger.ArgWriter(func(w *bufio.Writer) {
for i, ep := range newEPs {
if i > 0 {
w.WriteString(", ")
}
w.WriteString(ep.String())
}
}))
}
// Delete any prior CalllMeMaybe endpoints that weren't included
// in this message.
for ep, want := range de.isCallMeMaybeEP {
if !want {
delete(de.isCallMeMaybeEP, ep)
de.deleteEndpointLocked(ep)
}
}
// Zero out all the lastPing times to force sendPingsLocked to send new ones,
// even if it's been less than 5 seconds ago.
for _, st := range de.endpointState {
st.lastPing = time.Time{}
}
de.sendPingsLocked(time.Now(), false)
}
func (de *discoEndpoint) populatePeerStatus(ps *ipnstate.PeerStatus) {
de.mu.Lock()
defer de.mu.Unlock()
if de.lastSend.IsZero() {
return
}
ps.LastWrite = de.lastSend
now := time.Now()
if udpAddr, derpAddr := de.addrForSendLocked(now); !udpAddr.IsZero() && derpAddr.IsZero() {
ps.CurAddr = udpAddr.String()
}
}
// stopAndReset stops timers associated with de and resets its state back to zero.
// It's called when a discovery endpoint is no longer present in the NetworkMap,
// or when magicsock is transition from running to stopped state (via SetPrivateKey(zero))
func (de *discoEndpoint) stopAndReset() {
atomic.AddInt64(&de.numStopAndResetAtomic, 1)
de.mu.Lock()
defer de.mu.Unlock()
de.c.logf("[v1] magicsock: doing cleanup for discovery key %x", de.discoKey[:])
// Zero these fields so if the user re-starts the network, the discovery
// state isn't a mix of before & after two sessions.
de.lastSend = time.Time{}
de.lastFullPing = time.Time{}
de.bestAddr = netaddr.IPPort{}
de.bestAddrLatency = 0
de.bestAddrAt = time.Time{}
de.trustBestAddrUntil = time.Time{}
for _, es := range de.endpointState {
es.lastPing = time.Time{}
}
for txid, sp := range de.sentPing {
de.removeSentPingLocked(txid, sp)
}
if de.heartBeatTimer != nil {
de.heartBeatTimer.Stop()
de.heartBeatTimer = nil
}
de.pendingCLIPings = nil
}
func (de *discoEndpoint) numStopAndReset() int64 {
return atomic.LoadInt64(&de.numStopAndResetAtomic)
}
// derpStr replaces DERP IPs in s with "derp-".
func derpStr(s string) string { return strings.ReplaceAll(s, "127.3.3.40:", "derp-") }
// ippEndpointCache is a mutex-free single-element cache, mapping from
// a single netaddr.IPPort to a single endpoint.
type ippEndpointCache struct {
ipp netaddr.IPPort
gen int64
de *discoEndpoint
}
|
[
"\"TS_DEBUG_LOG_PACKET_DESTS\"",
"\"TS_DEBUG_DISCO\"",
"\"TS_DEBUG_OMIT_LOCAL_ADDRS\"",
"\"TS_DEBUG_ENABLE_DERP_ROUTE\"",
"\"TS_DEBUG_DERP\"",
"\"TS_DEBUG_RESTUN_STOP_ON_IDLE\"",
"\"IN_TS_TEST\""
] |
[] |
[
"IN_TS_TEST",
"TS_DEBUG_RESTUN_STOP_ON_IDLE",
"TS_DEBUG_ENABLE_DERP_ROUTE",
"TS_DEBUG_LOG_PACKET_DESTS",
"TS_DEBUG_OMIT_LOCAL_ADDRS",
"TS_DEBUG_DERP",
"TS_DEBUG_DISCO"
] |
[]
|
["IN_TS_TEST", "TS_DEBUG_RESTUN_STOP_ON_IDLE", "TS_DEBUG_ENABLE_DERP_ROUTE", "TS_DEBUG_LOG_PACKET_DESTS", "TS_DEBUG_OMIT_LOCAL_ADDRS", "TS_DEBUG_DERP", "TS_DEBUG_DISCO"]
|
go
| 7 | 0 | |
matterbridge.go
|
package main
import (
"flag"
"fmt"
"os"
"runtime"
"strings"
"github.com/42wim/matterbridge/bridge/config"
"github.com/42wim/matterbridge/gateway"
"github.com/42wim/matterbridge/gateway/bridgemap"
"github.com/google/gops/agent"
prefixed "github.com/matterbridge/logrus-prefixed-formatter"
"github.com/sirupsen/logrus"
)
var (
version = "1.20.1-dev"
githash string
flagConfig = flag.String("conf", "matterbridge.toml", "config file")
flagDebug = flag.Bool("debug", false, "enable debug")
flagVersion = flag.Bool("version", false, "show version")
flagGops = flag.Bool("gops", false, "enable gops agent")
)
func main() {
flag.Parse()
if *flagVersion {
fmt.Printf("version: %s %s\n", version, githash)
return
}
rootLogger := setupLogger()
logger := rootLogger.WithFields(logrus.Fields{"prefix": "main"})
if *flagGops {
if err := agent.Listen(agent.Options{}); err != nil {
logger.Errorf("Failed to start gops agent: %#v", err)
} else {
defer agent.Close()
}
}
logger.Printf("Running version %s %s", version, githash)
if strings.Contains(version, "-dev") {
logger.Println("WARNING: THIS IS A DEVELOPMENT VERSION. Things may break.")
}
cfg := config.NewConfig(rootLogger, *flagConfig)
cfg.BridgeValues().General.Debug = *flagDebug
// if logging to a file, ensure it is closed when the program terminates
// nolint:errcheck
defer func() {
if f, ok := rootLogger.Out.(*os.File); ok {
f.Sync()
f.Close()
}
}()
r, err := gateway.NewRouter(rootLogger, cfg, bridgemap.FullMap)
if err != nil {
logger.Fatalf("Starting gateway failed: %s", err)
}
if err = r.Start(); err != nil {
logger.Fatalf("Starting gateway failed: %s", err)
}
logger.Printf("Gateway(s) started succesfully. Now relaying messages")
select {}
}
func setupLogger() *logrus.Logger {
logger := &logrus.Logger{
Out: os.Stdout,
Formatter: &prefixed.TextFormatter{
PrefixPadding: 13,
DisableColors: true,
},
Level: logrus.InfoLevel,
}
if *flagDebug || os.Getenv("DEBUG") == "1" {
logger.SetReportCaller(true)
logger.Formatter = &prefixed.TextFormatter{
PrefixPadding: 13,
DisableColors: true,
FullTimestamp: false,
CallerFormatter: func(function, file string) string {
return fmt.Sprintf(" [%s:%s]", function, file)
},
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
sp := strings.SplitAfter(f.File, "/matterbridge/")
filename := f.File
if len(sp) > 1 {
filename = sp[1]
}
s := strings.Split(f.Function, ".")
funcName := s[len(s)-1]
return funcName, fmt.Sprintf("%s:%d", filename, f.Line)
},
}
logger.Level = logrus.DebugLevel
logger.WithFields(logrus.Fields{"prefix": "main"}).Info("Enabling debug logging.")
}
return logger
}
|
[
"\"DEBUG\""
] |
[] |
[
"DEBUG"
] |
[]
|
["DEBUG"]
|
go
| 1 | 0 | |
e2e_tests/data_serving.py
|
import os
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
def runTests():
# Get the url of the service.
service_url = os.environ.get('SERVICE_URL').strip('"')
print('SERVICE_URL={}'.format(service_url))
# Get service account credentials to make request to private URL
creds = service_account.IDTokenCredentials.from_service_account_file(
os.environ.get('PATH_TO_SA_CREDS'), target_audience=service_url)
authed_session = AuthorizedSession(creds)
resp = authed_session.get(service_url)
if not resp.ok:
print('Request failed with code {}'.format(resp.status_code))
exit(1)
if b'Running data server.' not in resp.content:
print('Unexpected response. Expected: "Running data server."'
'Received: {}'.format(resp.content))
exit(1)
print('Test completed with no errors')
if __name__ == '__main__':
runTests()
|
[] |
[] |
[
"PATH_TO_SA_CREDS",
"SERVICE_URL"
] |
[]
|
["PATH_TO_SA_CREDS", "SERVICE_URL"]
|
python
| 2 | 0 | |
tests/system_tests_link_routes.py
|
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import os
from time import sleep, time
from threading import Event
from subprocess import PIPE, STDOUT
from system_test import TestCase, Qdrouterd, main_module, TIMEOUT, Process, TestTimeout, \
AsyncTestSender, AsyncTestReceiver, MgmtMsgProxy, unittest, QdManager
from test_broker import FakeBroker
from test_broker import FakeService
from proton import Delivery
from proton import Message
from proton.handlers import MessagingHandler
from proton.reactor import AtMostOnce, Container, DynamicNodeProperties, LinkOption, AtLeastOnce
from proton.reactor import ApplicationEvent
from proton.reactor import EventInjector
from proton.utils import BlockingConnection
from system_tests_drain_support import DrainMessagesHandler, DrainOneMessageHandler, DrainNoMessagesHandler, DrainNoMoreMessagesHandler
from qpid_dispatch.management.client import Node
from qpid_dispatch.management.error import NotFoundStatus, BadRequestStatus
class LinkRouteTest(TestCase):
"""
Tests the linkRoute property of the dispatch router.
Sets up 4 routers (two of which are acting as brokers (QDR.A, QDR.D)). The other two routers have linkRoutes
configured such that matching traffic will be directed to/from the 'fake' brokers.
(please see configs in the setUpClass method to get a sense of how the routers and their connections are configured)
The tests in this class send and receive messages across this network of routers to link routable addresses.
Uses the Python Blocking API to send/receive messages. The blocking api plays neatly into the synchronous nature
of system tests.
QDR.A acting broker #1
+---------+ +---------+ +---------+ +-----------------+
| | <------ | | <----- | |<----| blocking_sender |
| QDR.A | | QDR.B | | QDR.C | +-----------------+
| | ------> | | ------> | | +-------------------+
+---------+ +---------+ +---------+---->| blocking_receiver |
^ | +-------------------+
| |
| V
+---------+
| |
| QDR.D |
| |
+---------+
QDR.D acting broker #2
"""
@classmethod
def get_router(cls, index):
return cls.routers[index]
@classmethod
def setUpClass(cls):
"""Start three routers"""
super(LinkRouteTest, cls).setUpClass()
def router(name, connection):
config = [
('router', {'mode': 'interior', 'id': 'QDR.%s'%name}),
] + connection
config = Qdrouterd.Config(config)
cls.routers.append(cls.tester.qdrouterd(name, config, wait=False))
cls.routers = []
a_listener_port = cls.tester.get_port()
b_listener_port = cls.tester.get_port()
c_listener_port = cls.tester.get_port()
d_listener_port = cls.tester.get_port()
test_tag_listener_port = cls.tester.get_port()
router('A',
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
])
router('B',
[
# Listener for clients, note that the tests assume this listener is first in this list:
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': b_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
('listener', {'name': 'test-tag', 'role': 'route-container', 'host': '0.0.0.0', 'port': test_tag_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
# This is an route-container connection made from QDR.B's ephemeral port to a_listener_port
('connector', {'name': 'broker', 'role': 'route-container', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
# Only inter router communication must happen on 'inter-router' connectors. This connector makes
# a connection from the router B's ephemeral port to c_listener_port
('connector', {'name': 'routerC', 'role': 'inter-router', 'host': '0.0.0.0', 'port': c_listener_port}),
# This is an on-demand connection made from QDR.B's ephemeral port to d_listener_port
('connector', {'name': 'routerD', 'role': 'route-container', 'host': '0.0.0.0', 'port': d_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
#('linkRoute', {'prefix': 'org.apache', 'connection': 'broker', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'QDR.A', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'QDR.A', 'direction': 'out'}),
('linkRoute', {'prefix': 'pulp.task', 'connection': 'test-tag', 'direction': 'in'}),
('linkRoute', {'prefix': 'pulp.task', 'connection': 'test-tag', 'direction': 'out'}),
# addresses matching pattern 'a.*.toA.#' route to QDR.A
('linkRoute', {'pattern': 'a.*.toA.#', 'containerId': 'QDR.A', 'direction': 'in'}),
('linkRoute', {'pattern': 'a.*.toA.#', 'containerId': 'QDR.A', 'direction': 'out'}),
# addresses matching pattern 'a.*.toD.#' route to QDR.D
# Dont change dir to direction here so we can make sure that the dir attribute is still working.
('linkRoute', {'pattern': 'a.*.toD.#', 'containerId': 'QDR.D', 'dir': 'in'}),
('linkRoute', {'pattern': 'a.*.toD.#', 'containerId': 'QDR.D', 'dir': 'out'})
]
)
router('C',
[
# The client will exclusively use the following listener to
# connect to QDR.C, the tests assume this is the first entry
# in the list
('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.tester.get_port(), 'saslMechanisms': 'ANONYMOUS'}),
('listener', {'host': '0.0.0.0', 'role': 'inter-router', 'port': c_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
# The dot(.) at the end is ignored by the address hashing scheme.
('linkRoute', {'prefix': 'org.apache.', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache.', 'direction': 'out'}),
('linkRoute', {'prefix': 'pulp.task', 'direction': 'in'}),
('linkRoute', {'prefix': 'pulp.task', 'direction': 'out'}),
('linkRoute', {'pattern': 'a.*.toA.#', 'direction': 'in'}),
('linkRoute', {'pattern': 'a.*.toA.#', 'direction': 'out'}),
('linkRoute', {'pattern': 'a.*.toD.#', 'direction': 'in'}),
('linkRoute', {'pattern': 'a.*.toD.#', 'direction': 'out'})
]
)
router('D', # sink for QDR.D routes
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': d_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
])
# Wait for the routers to locate each other, and for route propagation
# to settle
cls.routers[1].wait_router_connected('QDR.C')
cls.routers[2].wait_router_connected('QDR.B')
cls.routers[2].wait_address("org.apache", remotes=1, delay=0.5)
# This is not a classic router network in the sense that QDR.A and D are acting as brokers. We allow a little
# bit more time for the routers to stabilize.
sleep(2)
def run_qdstat_linkRoute(self, address, args=None):
cmd = ['qdstat', '--bus', str(address), '--timeout', str(TIMEOUT) ] + ['--linkroute']
if args:
cmd = cmd + args
p = self.popen(
cmd,
name='qdstat-'+self.id(), stdout=PIPE, expect=None,
universal_newlines=True)
out = p.communicate()[0]
assert p.returncode == 0, "qdstat exit status %s, output:\n%s" % (p.returncode, out)
return out
def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK, address=None):
p = self.popen(
['qdmanage'] + cmd.split(' ') + ['--bus', address or self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
universal_newlines=True)
out = p.communicate(input)[0]
try:
p.teardown()
except Exception as e:
raise Exception("%s\n%s" % (e, out))
return out
def test_aaa_qdmanage_query_link_route(self):
"""
qdmanage converts short type to long type and this test specifically tests if qdmanage is actually doing
the type conversion correctly by querying with short type and long type.
"""
cmd = 'QUERY --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
# Make sure there is a dir of in and out.
self.assertTrue('"direction": "in"' in out)
self.assertTrue('"direction": "out"' in out)
self.assertTrue('"containerId": "QDR.A"' in out)
# Use the long type and make sure that qdmanage does not mess up the long type
cmd = 'QUERY --type=org.apache.qpid.dispatch.router.config.linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
# Make sure there is a dir of in and out.
self.assertTrue('"direction": "in"' in out)
self.assertTrue('"direction": "out"' in out)
self.assertTrue('"containerId": "QDR.A"' in out)
identity = out[out.find("identity") + 12: out.find("identity") + 13]
cmd = 'READ --type=linkRoute --identity=' + identity
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
self.assertTrue(identity in out)
exception_occurred = False
try:
# This identity should not be found
cmd = 'READ --type=linkRoute --identity=9999'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
except Exception as e:
exception_occurred = True
self.assertTrue("NotFoundStatus: Not Found" in str(e))
self.assertTrue(exception_occurred)
exception_occurred = False
try:
# There is no identity specified, this is a bad request
cmd = 'READ --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
except Exception as e:
exception_occurred = True
self.assertTrue("BadRequestStatus: No name or identity provided" in str(e))
self.assertTrue(exception_occurred)
cmd = 'CREATE --type=autoLink address=127.0.0.1 direction=in connection=routerC'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
identity = out[out.find("identity") + 12: out.find("identity") + 14]
cmd = 'READ --type=autoLink --identity=' + identity
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
self.assertTrue(identity in out)
def test_bbb_qdstat_link_routes_routerB(self):
"""
Runs qdstat on router B to make sure that router B has 4 link routes,
each having one 'in' and one 'out' entry
"""
out = self.run_qdstat_linkRoute(self.routers[1].addresses[0])
for route in ['a.*.toA.#', 'a.*.toD.#', 'org.apache', 'pulp.task']:
self.assertTrue(route in out)
out_list = out.split()
self.assertEqual(out_list.count('in'), 4)
self.assertEqual(out_list.count('out'), 4)
parts = out.split("\n")
self.assertEqual(len(parts), 15)
out = self.run_qdstat_linkRoute(self.routers[1].addresses[0], args=['--limit=1'])
parts = out.split("\n")
self.assertEqual(len(parts), 8)
def test_ccc_qdstat_link_routes_routerC(self):
"""
Runs qdstat on router C to make sure that router C has 4 link routes,
each having one 'in' and one 'out' entry
"""
out = self.run_qdstat_linkRoute(self.routers[2].addresses[0])
out_list = out.split()
self.assertEqual(out_list.count('in'), 4)
self.assertEqual(out_list.count('out'), 4)
def test_ddd_partial_link_route_match(self):
"""
The linkRoute on Routers C and B is set to org.apache.
Creates a receiver listening on the address 'org.apache.dev' and a sender that sends to address 'org.apache.dev'.
Sends a message to org.apache.dev via router QDR.C and makes sure that the message was successfully
routed (using partial address matching) and received using pre-created links that were created as a
result of specifying addresses in the linkRoute attribute('org.apache.').
"""
hello_world_1 = "Hello World_1!"
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache.dev
blocking_receiver = blocking_connection.create_receiver(address="org.apache.dev")
apply_options = AtMostOnce()
# Sender to org.apache.dev
blocking_sender = blocking_connection.create_sender(address="org.apache.dev", options=apply_options)
msg = Message(body=hello_world_1)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_1, received_message.body)
# Connect to the router acting like the broker (QDR.A) and check the deliveriesIngress and deliveriesEgress
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
self.assertEqual(u'QDR.A', local_node.query(type='org.apache.qpid.dispatch.router',
attribute_names=[u'id']).results[0][0])
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev').deliveriesIngress)
# There should be 4 links -
# 1. outbound receiver link on org.apache.dev
# 2. inbound sender link on blocking_sender
# 3. inbound link to the $management
# 4. outbound link to $management
# self.assertEqual(4, len()
self.assertEqual(4, len(local_node.query(type='org.apache.qpid.dispatch.router.link').results))
blocking_connection.close()
def test_partial_link_route_match_1(self):
"""
This test is pretty much the same as the previous test (test_partial_link_route_match) but the connection is
made to router QDR.B instead of QDR.C and we expect to see the same behavior.
"""
hello_world_2 = "Hello World_2!"
addr = self.routers[1].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache.dev
blocking_receiver = blocking_connection.create_receiver(address="org.apache.dev.1")
apply_options = AtMostOnce()
# Sender to to org.apache.dev
blocking_sender = blocking_connection.create_sender(address="org.apache.dev.1", options=apply_options)
msg = Message(body=hello_world_2)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_2, received_message.body)
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
# Make sure that the router node acting as the broker (QDR.A) had one message routed through it. This confirms
# that the message was link routed
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev.1').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev.1').deliveriesIngress)
blocking_connection.close()
def test_full_link_route_match(self):
"""
The linkRoute on Routers C and B is set to org.apache.
Creates a receiver listening on the address 'org.apache' and a sender that sends to address 'org.apache'.
Sends a message to org.apache via router QDR.C and makes sure that the message was successfully
routed (using full address matching) and received using pre-created links that were created as a
result of specifying addresses in the linkRoute attribute('org.apache.').
"""
hello_world_3 = "Hello World_3!"
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache
blocking_receiver = blocking_connection.create_receiver(address="org.apache")
apply_options = AtMostOnce()
# Sender to to org.apache
blocking_sender = blocking_connection.create_sender(address="org.apache", options=apply_options)
msg = Message(body=hello_world_3)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_3, received_message.body)
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
# Make sure that the router node acting as the broker (QDR.A) had one message routed through it. This confirms
# that the message was link routed
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache').deliveriesIngress)
blocking_connection.close()
def _link_route_pattern_match(self, connect_node, include_host,
exclude_host, test_address,
expected_pattern):
"""
This helper function ensures that messages sent to 'test_address' pass
through 'include_host', and are *not* routed to 'exclude_host'
"""
hello_pattern = "Hello Pattern!"
route = 'M0' + test_address
# Connect to the two 'waypoints', ensure the route is not present on
# either
node_A = Node.connect(include_host, timeout=TIMEOUT)
node_B = Node.connect(exclude_host, timeout=TIMEOUT)
for node in [node_A, node_B]:
self.assertRaises(NotFoundStatus,
node.read,
type='org.apache.qpid.dispatch.router.address',
name=route)
# wait until the host we're connecting to gets its next hop for the
# pattern we're connecting to
connect_node.wait_address(expected_pattern, remotes=1, delay=0.1)
# Connect to 'connect_node' and send message to 'address'
blocking_connection = BlockingConnection(connect_node.addresses[0])
blocking_receiver = blocking_connection.create_receiver(address=test_address)
blocking_sender = blocking_connection.create_sender(address=test_address,
options=AtMostOnce())
msg = Message(body=hello_pattern)
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_pattern, received_message.body)
# verify test_address is only present on include_host and not on exclude_host
self.assertRaises(NotFoundStatus,
node_B.read,
type='org.apache.qpid.dispatch.router.address',
name=route)
self.assertEqual(1, node_A.read(type='org.apache.qpid.dispatch.router.address',
name=route).deliveriesIngress)
self.assertEqual(1, node_A.read(type='org.apache.qpid.dispatch.router.address',
name=route).deliveriesIngress)
# drop the connection and verify that test_address is no longer on include_host
blocking_connection.close()
timeout = time() + TIMEOUT
while True:
try:
node_A.read(type='org.apache.qpid.dispatch.router.address',
name=route)
if time() > timeout:
raise Exception("Expected route '%s' to expire!" % route)
sleep(0.1)
except NotFoundStatus:
break;
node_A.close()
node_B.close()
def test_link_route_pattern_match(self):
"""
Verify the addresses match the proper patterns and are routed to the
proper 'waypoint' only
"""
qdr_A = self.routers[0].addresses[0]
qdr_D = self.routers[3].addresses[0]
qdr_C = self.routers[2] # note: the node, not the address!
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_A,
exclude_host=qdr_D,
test_address='a.notD.toA',
expected_pattern='a.*.toA.#')
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_D,
exclude_host=qdr_A,
test_address='a.notA.toD',
expected_pattern='a.*.toD.#')
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_A,
exclude_host=qdr_D,
test_address='a.toD.toA.xyz',
expected_pattern='a.*.toA.#')
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_D,
exclude_host=qdr_A,
test_address='a.toA.toD.abc',
expected_pattern='a.*.toD.#')
def test_custom_annotations_match(self):
"""
The linkRoute on Routers C and B is set to org.apache.
Creates a receiver listening on the address 'org.apache' and a sender that sends to address 'org.apache'.
Sends a message with custom annotations to org.apache via router QDR.C and makes sure that the message was successfully
routed (using full address matching) and received using pre-created links that were created as a
result of specifying addresses in the linkRoute attribute('org.apache.'). Make sure custom annotations arrived as well.
"""
hello_world_3 = "Hello World_3!"
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache
blocking_receiver = blocking_connection.create_receiver(address="org.apache.2")
apply_options = AtMostOnce()
# Sender to to org.apache
blocking_sender = blocking_connection.create_sender(address="org.apache.2", options=apply_options)
msg = Message(body=hello_world_3)
annotations = {'custom-annotation': '1/Custom_Annotation'}
msg.annotations = annotations
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_3, received_message.body)
self.assertEqual(received_message.annotations, annotations)
blocking_connection.close()
def test_full_link_route_match_1(self):
"""
This test is pretty much the same as the previous test (test_full_link_route_match) but the connection is
made to router QDR.B instead of QDR.C and we expect the message to be link routed successfully.
"""
hello_world_4 = "Hello World_4!"
addr = self.routers[1].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache
blocking_receiver = blocking_connection.create_receiver(address="org.apache.1")
apply_options = AtMostOnce()
# Sender to to org.apache
blocking_sender = blocking_connection.create_sender(address="org.apache.1", options=apply_options)
msg = Message(body=hello_world_4)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_4, received_message.body)
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
# Make sure that the router node acting as the broker (QDR.A) had one message routed through it. This confirms
# that the message was link routed
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.1').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.1').deliveriesIngress)
blocking_connection.close()
def test_zzz_qdmanage_delete_link_route(self):
"""
We are deleting the link route using qdmanage short name. This should be the last test to run
"""
local_node = Node.connect(self.routers[1].addresses[0], timeout=TIMEOUT)
res = local_node.query(type='org.apache.qpid.dispatch.router')
results = res.results[0]
attribute_list = res.attribute_names
result_list = local_node.query(type='org.apache.qpid.dispatch.router.config.linkRoute').results
self.assertEqual(results[attribute_list.index('linkRouteCount')], len(result_list))
# First delete linkRoutes on QDR.B
for rid in range(8):
cmd = 'DELETE --type=linkRoute --identity=' + result_list[rid][1]
self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
cmd = 'QUERY --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
self.assertEqual(out.rstrip(), '[]')
# linkRoutes now gone on QDR.B but remember that it still exist on QDR.C
# We will now try to create a receiver on address org.apache.dev on QDR.C.
# Since the linkRoute on QDR.B is gone, QDR.C
# will not allow a receiver to be created since there is no route to destination.
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
# Now delete linkRoutes on QDR.C to eradicate linkRoutes completely
local_node = Node.connect(addr, timeout=TIMEOUT)
result_list = local_node.query(type='org.apache.qpid.dispatch.router.config.linkRoute').results
# QDR.C has 8 link routes configured, nuke 'em:
self.assertEqual(8, len(result_list))
for rid in range(8):
cmd = 'DELETE --type=linkRoute --identity=' + result_list[rid][1]
self.run_qdmanage(cmd=cmd, address=addr)
cmd = 'QUERY --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=addr)
self.assertEqual(out.rstrip(), '[]')
res = local_node.query(type='org.apache.qpid.dispatch.router')
results = res.results[0]
attribute_list = res.attribute_names
self.assertEqual(results[attribute_list.index('linkRouteCount')], 0)
blocking_connection = BlockingConnection(addr, timeout=3)
# Receive on org.apache.dev (this address used to be linkRouted but not anymore since we deleted linkRoutes
# on both QDR.C and QDR.B)
blocking_receiver = blocking_connection.create_receiver(address="org.apache.dev")
apply_options = AtMostOnce()
hello_world_1 = "Hello World_1!"
# Sender to org.apache.dev
blocking_sender = blocking_connection.create_sender(address="org.apache.dev", options=apply_options)
msg = Message(body=hello_world_1)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive(timeout=5)
self.assertEqual(hello_world_1, received_message.body)
def test_yyy_delivery_tag(self):
"""
Tests that the router carries over the delivery tag on a link routed delivery
"""
listening_address = self.routers[1].addresses[1]
sender_address = self.routers[2].addresses[0]
qdstat_address = self.routers[2].addresses[0]
test = DeliveryTagsTest(sender_address, listening_address, qdstat_address)
test.run()
self.assertEqual(None, test.error)
def test_yyy_invalid_delivery_tag(self):
test = InvalidTagTest(self.routers[2].addresses[0])
test.run()
self.assertEqual(None, test.error)
def test_close_with_unsettled(self):
test = CloseWithUnsettledTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_www_drain_support_all_messages(self):
drain_support = DrainMessagesHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_www_drain_support_one_message(self):
drain_support = DrainOneMessageHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_www_drain_support_no_messages(self):
drain_support = DrainNoMessagesHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_www_drain_support_no_more_messages(self):
drain_support = DrainNoMoreMessagesHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_link_route_terminus_address(self):
# The receiver is attaching to router B to a listener that has link route for address 'pulp.task' setup.
listening_address = self.routers[1].addresses[1]
# Run the query on a normal port
query_address_listening = self.routers[1].addresses[0]
# Sender is attaching to router C
sender_address = self.routers[2].addresses[0]
query_address_sending = self.routers[2].addresses[0]
test = TerminusAddrTest(sender_address, listening_address, query_address_sending, query_address_listening)
test.run()
self.assertTrue(test.in_receiver_found)
self.assertTrue(test.out_receiver_found)
self.assertTrue(test.in_sender_found)
self.assertTrue(test.out_sender_found)
def test_dynamic_source(self):
test = DynamicSourceTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_dynamic_target(self):
test = DynamicTargetTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_detach_without_close(self):
test = DetachNoCloseTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_detach_mixed_close(self):
test = DetachMixedCloseTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def _multi_link_send_receive(self, send_host, receive_host, name):
senders = ["%s/%s" % (send_host, address) for address in ["org.apache.foo", "org.apache.bar"]]
receivers = ["%s/%s" % (receive_host, address) for address in ["org.apache.foo", "org.apache.bar"]]
test = MultiLinkSendReceive(senders, receivers, name)
test.run()
self.assertEqual(None, test.error)
def test_same_name_route_receivers_through_B(self):
self._multi_link_send_receive(self.routers[0].addresses[0], self.routers[1].addresses[0], "recv_through_B")
def test_same_name_route_senders_through_B(self):
self._multi_link_send_receive(self.routers[1].addresses[0], self.routers[0].addresses[0], "send_through_B")
def test_same_name_route_receivers_through_C(self):
self._multi_link_send_receive(self.routers[0].addresses[0], self.routers[2].addresses[0], "recv_through_C")
def test_same_name_route_senders_through_C(self):
self._multi_link_send_receive(self.routers[2].addresses[0], self.routers[0].addresses[0], "send_through_C")
def test_echo_detach_received(self):
"""
Create two receivers to link routed address org.apache.dev
Create a sender to the same address that the receiver is listening on and send 100 messages.
After the receivers receive 10 messages each, the receivers will detach and expect to receive ten
detaches in response.
"""
test = EchoDetachReceived(self.routers[2].addresses[0], self.routers[2].addresses[0])
test.run()
self.assertEqual(None, test.error)
def test_bad_link_route_config(self):
"""
What happens when the link route create request is malformed?
"""
mgmt = self.routers[1].management
# zero length prefix
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-1",
attributes={'prefix': '',
'containerId': 'FakeBroker',
'direction': 'in'})
# pattern wrong type
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-2",
attributes={'pattern': 666,
'containerId': 'FakeBroker',
'direction': 'in'})
# invalid pattern (no tokens)
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-3",
attributes={'pattern': '///',
'containerId': 'FakeBroker',
'direction': 'in'})
# empty attributes
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-4",
attributes={})
# both pattern and prefix
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-5",
attributes={'prefix': 'a1',
'pattern': 'b2',
'containerId': 'FakeBroker',
'direction': 'in'})
# bad direction
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-6",
attributes={'pattern': 'b2',
'containerId': 'FakeBroker',
'direction': 'nowhere'})
# bad distribution
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-7",
attributes={'pattern': 'b2',
'containerId': 'FakeBroker',
'direction': 'in',
"distribution": "dilly dilly"})
# no direction
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-8",
attributes={'prefix': 'b2',
'containerId': 'FakeBroker'})
# neither pattern nor prefix
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-9",
attributes={'direction': 'out',
'containerId': 'FakeBroker'})
class DeliveryTagsTest(MessagingHandler):
def __init__(self, sender_address, listening_address, qdstat_address):
super(DeliveryTagsTest, self).__init__()
self.sender_address = sender_address
self.listening_address = listening_address
self.sender = None
self.receiver_connection = None
self.sender_connection = None
self.qdstat_address = qdstat_address
self.id = '1235'
self.times = 1
self.sent = 0
self.rcvd = 0
self.delivery_tag_verified = False
# The delivery tag we are going to send in the transfer frame
# We will later make sure that the same delivery tag shows up on the receiving end in the link routed case.
# KAG: force the literal to type 'str' due to SWIG weirdness: on 2.X a
# delivery tag cannot be unicode (must be binary), but on 3.X it must
# be unicode! See https://issues.apache.org/jira/browse/PROTON-1843
self.delivery_tag = str('92319')
self.error = None
def timeout(self):
self.error = "Timeout expired: sent=%d rcvd=%d" % (self.sent, self.rcvd)
if self.receiver_connection:
self.receiver_connection.close()
if self.sender_connection:
self.sender_connection.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.receiver_connection = event.container.connect(self.listening_address)
def on_connection_remote_open(self, event):
if event.connection == self.receiver_connection:
continue_loop = True
# Dont open the sender connection unless we can make sure that there is a remote receiver ready to
# accept the message.
# If there is no remote receiver, the router will throw a 'No route to destination' error when
# creating sender connection.
# The following loops introduces a wait before creating the sender connection. It gives time to the
# router so that the address Dpulp.task can show up on the remoteCount
i = 0
while continue_loop:
if i > 100: # If we have run the read command for more than hundred times and we still do not have
# the remoteCount set to 1, there is a problem, just exit out of the function instead
# of looping to infinity.
self.receiver_connection.close()
return
local_node = Node.connect(self.qdstat_address, timeout=TIMEOUT)
out = local_node.read(type='org.apache.qpid.dispatch.router.address', name='Dpulp.task').remoteCount
if out == 1:
continue_loop = False
else:
i += 1
sleep(0.25)
self.sender_connection = event.container.connect(self.sender_address)
self.sender = event.container.create_sender(self.sender_connection, "pulp.task", options=AtMostOnce())
def on_sendable(self, event):
if self.times == 1:
msg = Message(body="Hello World")
self.sender.send(msg, tag=self.delivery_tag)
self.times += 1
self.sent += 1
def on_message(self, event):
if "Hello World" == event.message.body:
self.rcvd += 1
# If the tag on the delivery is the same as the tag we sent with the initial transfer, it means
# that the router has propagated the delivery tag successfully because of link routing.
if self.delivery_tag != event.delivery.tag:
self.error = "Delivery-tag: expected:%r got:%r" % (self.delivery_tag, event.delivery.tag)
self.receiver_connection.close()
self.sender_connection.close()
self.timer.cancel()
def run(self):
Container(self).run()
class CloseWithUnsettledTest(MessagingHandler):
##
## This test sends a message across an attach-routed link. While the message
## is unsettled, the client link is closed. The test is ensuring that the
## router does not crash during the closing of the links.
##
def __init__(self, normal_addr, route_addr):
super(CloseWithUnsettledTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.CWUtest"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.sender = event.container.create_sender(self.conn_normal, self.dest)
def on_connection_closed(self, event):
self.conn_route.close()
self.timer.cancel()
def on_link_opened(self, event):
if event.receiver:
self.receiver = event.receiver
self.receiver.flow(1)
def on_sendable(self, event):
msg = Message(body="CloseWithUnsettled")
event.sender.send(msg)
def on_message(self, event):
self.conn_normal.close()
def run(self):
Container(self).run()
class DynamicSourceTest(MessagingHandler):
##
## This test verifies that a dynamic source can be propagated via link-route to
## a route-container.
##
def __init__(self, normal_addr, route_addr):
super(DynamicSourceTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DynamicSource"
self.address = "DynamicSourceAddress"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.receiver = event.container.create_receiver(self.conn_normal, None, dynamic=True,options=DynamicNodeProperties({"x-opt-qd.address":u"pulp.task.abc"}))
def on_link_opened(self, event):
if event.receiver == self.receiver:
if self.receiver.remote_source.address != self.address:
self.error = "Expected %s, got %s" % (self.address, self.receiver.remote_source.address)
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_link_opening(self, event):
if event.sender:
self.sender = event.sender
if not self.sender.remote_source.dynamic:
self.error = "Expected sender with dynamic source"
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
self.sender.source.address = self.address
self.sender.open()
def run(self):
Container(self).run()
class DynamicTarget(LinkOption):
def apply(self, link):
link.target.dynamic = True
link.target.address = None
class DynamicTargetTest(MessagingHandler):
##
## This test verifies that a dynamic source can be propagated via link-route to
## a route-container.
##
def __init__(self, normal_addr, route_addr):
super(DynamicTargetTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DynamicTarget"
self.address = "DynamicTargetAddress"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.sender = event.container.create_sender(self.conn_normal, None, options=\
[DynamicTarget(), DynamicNodeProperties({"x-opt-qd.address":u"pulp.task.abc"})])
def on_link_opened(self, event):
if event.sender == self.sender:
if self.sender.remote_target.address != self.address:
self.error = "Expected %s, got %s" % (self.address, self.receiver.remote_source.address)
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_link_opening(self, event):
if event.receiver:
self.receiver = event.receiver
if not self.receiver.remote_target.dynamic:
self.error = "Expected receiver with dynamic source"
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
self.receiver.target.address = self.address
self.receiver.open()
def run(self):
Container(self).run()
class DetachNoCloseTest(MessagingHandler):
##
## This test verifies that link-detach (not close) is propagated properly
##
def __init__(self, normal_addr, route_addr):
super(DetachNoCloseTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DetachNoClose"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def stop(self):
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.receiver = event.container.create_receiver(self.conn_normal, self.dest)
def on_link_opened(self, event):
if event.receiver == self.receiver:
self.receiver.detach()
def on_link_remote_detach(self, event):
if event.sender == self.sender:
self.sender.detach()
if event.receiver == self.receiver:
##
## Test passed, we expected a detach on the propagated sender and back
##
self.stop()
def on_link_closing(self, event):
if event.sender == self.sender:
self.error = 'Propagated link was closed. Expected it to be detached'
self.stop()
if event.receiver == self.receiver:
self.error = 'Client link was closed. Expected it to be detached'
self.stop()
def on_link_opening(self, event):
if event.sender:
self.sender = event.sender
self.sender.source.address = self.sender.remote_source.address
self.sender.open()
def run(self):
Container(self).run()
class DetachMixedCloseTest(MessagingHandler):
##
## This test verifies that link-detach (not close) is propagated properly
##
def __init__(self, normal_addr, route_addr):
super(DetachMixedCloseTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DetachMixedClose"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def stop(self):
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.receiver = event.container.create_receiver(self.conn_normal, self.dest)
def on_link_opened(self, event):
if event.receiver == self.receiver:
self.receiver.detach()
def on_link_remote_detach(self, event):
if event.sender == self.sender:
self.sender.close()
if event.receiver == self.receiver:
self.error = 'Client link was detached. Expected it to be closed'
self.stop()
def on_link_closing(self, event):
if event.sender == self.sender:
self.error = 'Propagated link was closed. Expected it to be detached'
self.stop()
if event.receiver == self.receiver:
##
## Test Passed
##
self.stop()
def on_link_opening(self, event):
if event.sender:
self.sender = event.sender
self.sender.source.address = self.sender.remote_source.address
self.sender.open()
def run(self):
Container(self).run()
# Test to validate fix for DISPATCH-927
class EchoDetachReceived(MessagingHandler):
def __init__(self, sender_address, recv_address):
super(EchoDetachReceived, self).__init__()
self.sender_address = sender_address
self.recv_address = recv_address
self.dest = "org.apache.dev"
self.num_msgs = 100
self.num_receivers = 10
self.msgs_sent = 0
self.receiver_conn = None
self.sender_conn = None
self.sender = None
self.receiver_dict = {}
self.error = None
self.receiver_attaches = 0
self.timer = None
self.sender_attached = False
self.received_msgs_dict = {}
self.receiver_detach_dict = {}
self.num_detaches_echoed = 0
@property
def msgs_received(self):
return sum(self.received_msgs_dict.values())
def timeout(self):
self.bail("Timeout Expired: msgs_sent=%d msgs_received=%d, number of detaches received=%d"
% (self.msgs_sent, self.msgs_received, self.num_detaches_echoed))
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
# Create two separate connections for sender and receivers
self.receiver_conn = event.container.connect(self.recv_address)
self.sender_conn = event.container.connect(self.sender_address)
for i in range(self.num_receivers):
name = "R%d" % i
self.receiver_dict[name] = event.container.create_receiver(self.receiver_conn, self.dest, name=name)
self.received_msgs_dict[name] = 0
def bail(self, text=None):
self.error = text
self.sender_conn.close()
self.receiver_conn.close()
self.timer.cancel()
def on_link_opened(self, event):
if event.receiver:
if event.receiver.name in list(self.receiver_dict):
self.receiver_attaches+=1
# The response receiver attaches have been received. The receiver sent attaches which was link routed
# all the way to the 'broker' router and the response attaches have come back.
# It is now time to create the sender.
if self.receiver_attaches == self.num_receivers:
self.sender = event.container.create_sender(self.sender_conn, self.dest)
elif event.sender:
if not self.sender_attached:
if event.sender == self.sender:
# The sender attaches were link routed as well and the response attach has been received.
self.sender_attached = True
def on_sendable(self, event):
# The sender will send 100 messages
if self.receiver_attaches == self.num_receivers and self.sender_attached:
if self.msgs_sent < self.num_msgs:
msg = Message(body="Hello World")
self.sender.send(msg)
self.msgs_sent += 1
def on_message(self, event):
if event.receiver and event.receiver.name in list(self.receiver_dict):
self.received_msgs_dict[event.receiver.name] += 1
if sum(self.received_msgs_dict.values()) == self.num_msgs:
# The receivers have received a total of 100 messages. Close the receivers. The detach sent by these
# receivers will travel all the way over the link route and the 'broker' router will respond with a
# detach
for receiver in list(self.receiver_dict):
self.receiver_dict[receiver].close()
def on_link_closed(self, event):
if event.receiver.name in list(self.receiver_dict) and event.receiver.name not in list(self.receiver_detach_dict):
self.receiver_detach_dict[event.receiver.name] = event.receiver
self.num_detaches_echoed += 1
# Terminate the test only if both detach frames have been received.
if all(receiver in list(self.receiver_detach_dict) for receiver in list(self.receiver_dict)):
self.bail()
def run(self):
Container(self).run()
class TerminusAddrTest(MessagingHandler):
"""
This tests makes sure that the link route address is visible in the output of qdstat -l command.
Sets up a sender on address pulp.task.terminusTestSender and a receiver on pulp.task.terminusTestReceiver.
Connects to the router to which the sender is attached and makes sure that the pulp.task.terminusTestSender address
shows up with an 'in' and 'out'
Similarly connects to the router to which the receiver is attached and makes sure that the
pulp.task.terminusTestReceiver address shows up with an 'in' and 'out'
"""
def __init__(self, sender_address, listening_address, query_address_sending, query_address_listening):
super(TerminusAddrTest, self).__init__()
self.sender_address = sender_address
self.listening_address = listening_address
self.sender = None
self.receiver = None
self.message_received = False
self.receiver_connection = None
self.sender_connection = None
# We will run a query on the same router where the sender is attached
self.query_address_sending = query_address_sending
# We will run a query on the same router where the receiver is attached
self.query_address_listening = query_address_listening
self.count = 0
self.in_receiver_found = False
self.out_receiver_found = False
self.in_sender_found = False
self.out_sender_found = False
self.receiver_link_opened = False
self.sender_link_opened = False
def on_start(self, event):
self.receiver_connection = event.container.connect(self.listening_address)
def on_connection_remote_open(self, event):
if event.connection == self.receiver_connection:
continue_loop = True
# The following loops introduces a wait. It gives time to the
# router so that the address Dpulp.task can show up on the remoteCount
i = 0
while continue_loop:
if i > 100: # If we have run the read command for more than hundred times and we still do not have
# the remoteCount set to 1, there is a problem, just exit out of the function instead
# of looping to infinity.
self.receiver_connection.close()
return
local_node = Node.connect(self.query_address_sending, timeout=TIMEOUT)
out = local_node.read(type='org.apache.qpid.dispatch.router.address', name='Dpulp.task').remoteCount
if out == 1:
continue_loop = False
i += 1
sleep(0.25)
self.sender_connection = event.container.connect(self.sender_address)
# Notice here that the receiver and sender are listening on different addresses. Receiver on
# pulp.task.terminusTestReceiver and the sender on pulp.task.terminusTestSender
self.receiver = event.container.create_receiver(self.receiver_connection, "pulp.task.terminusTestReceiver")
self.sender = event.container.create_sender(self.sender_connection, "pulp.task.terminusTestSender", options=AtMostOnce())
def on_link_opened(self, event):
if event.receiver == self.receiver:
self.receiver_link_opened = True
local_node = Node.connect(self.query_address_listening, timeout=TIMEOUT)
out = local_node.query(type='org.apache.qpid.dispatch.router.link')
link_dir_index = out.attribute_names.index("linkDir")
owning_addr_index = out.attribute_names.index("owningAddr")
# Make sure that the owningAddr M0pulp.task.terminusTestReceiver shows up on both in and out.
# The 'out' link is on address M0pulp.task.terminusTestReceiver outgoing from the router B to the receiver
# The 'in' link is on address M0pulp.task.terminusTestReceiver incoming from router C to router B
for result in out.results:
if result[link_dir_index] == 'in' and result[owning_addr_index] == 'M0pulp.task.terminusTestReceiver':
self.in_receiver_found = True
if result[link_dir_index] == 'out' and result[owning_addr_index] == 'M0pulp.task.terminusTestReceiver':
self.out_receiver_found = True
if event.sender == self.sender:
self.sender_link_opened = True
local_node = Node.connect(self.query_address_sending, timeout=TIMEOUT)
out = local_node.query(type='org.apache.qpid.dispatch.router.link')
link_dir_index = out.attribute_names.index("linkDir")
owning_addr_index = out.attribute_names.index("owningAddr")
# Make sure that the owningAddr M0pulp.task.terminusTestSender shows up on both in and out.
# The 'in' link is on address M0pulp.task.terminusTestSender incoming from sender to router
# The 'out' link is on address M0pulp.task.terminusTestSender outgoing from router C to router B
for result in out.results:
if result[link_dir_index] == 'in' and result[owning_addr_index] == 'M0pulp.task.terminusTestSender':
self.in_sender_found = True
if result[link_dir_index] == 'out' and result[owning_addr_index] == 'M0pulp.task.terminusTestSender':
self.out_sender_found = True
# Shutdown the connections only if the on_link_opened has been called for sender and receiver links.
if self.sender_link_opened and self.receiver_link_opened:
self.sender.close()
self.receiver.close()
self.sender_connection.close()
self.receiver_connection.close()
def run(self):
Container(self).run()
class MultiLinkSendReceive(MessagingHandler):
class SendState(object):
def __init__(self, link):
self.link = link
self.sent = False
self.accepted = False
self.done = False
self.closed = False
def send(self, subject, body):
if not self.sent:
self.link.send(Message(subject=subject,body=body,address=self.link.target.address))
self.sent = True
def on_accepted(self):
self.accepted = True
self.done = True
def close(self):
if not self.closed:
self.closed = True
self.link.close()
self.link.connection.close()
class RecvState(object):
def __init__(self, link):
self.link = link
self.received = False
self.done = False
self.closed = False
def on_message(self):
self.received = True
self.done = True
def close(self):
if not self.closed:
self.closed = True
self.link.close()
self.link.connection.close()
def __init__(self, send_urls, recv_urls, name, message=None):
super(MultiLinkSendReceive, self).__init__()
self.send_urls = send_urls
self.recv_urls = recv_urls
self.senders = {}
self.receivers = {}
self.message = message or "SendReceiveTest"
self.sent = False
self.error = None
self.name = name
def close(self):
for sender in self.senders.values():
sender.close()
for receiver in self.receivers.values():
receiver.close()
def all_done(self):
for sender in self.senders.values():
if not sender.done:
return False
for receiver in self.receivers.values():
if not receiver.done:
return False
return True
def timeout(self):
self.error = "Timeout Expired"
self.close()
def stop_if_all_done(self):
if self.all_done():
self.stop()
def stop(self):
self.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
event.container.container_id = None
for u in self.send_urls:
s = self.SendState(event.container.create_sender(u, name=self.name))
self.senders[s.link.connection.container] = s
for u in self.recv_urls:
r = self.RecvState(event.container.create_receiver(u, name=self.name))
self.receivers[r.link.connection.container] = r
def on_sendable(self, event):
self.senders[event.connection.container].send(self.name, self.message)
def on_message(self, event):
if self.message != event.message.body:
error = "Incorrect message. Got %s, expected %s" % (event.message.body, self.message.body)
self.receivers[event.connection.container].on_message()
self.stop_if_all_done()
def on_accepted(self, event):
self.senders[event.connection.container].on_accepted()
self.stop_if_all_done()
def run(self):
Container(self).run()
class LinkRouteProtocolTest(TestCase):
"""
Test link route implementation against "misbehaving" containers
Uses a custom fake broker (not a router) that can do weird things at the
protocol level.
+-------------+ +---------+ +-----------------+
| | <------ | | <----- | blocking_sender |
| fake broker | | QDR.A | +-----------------+
| | ------> | | ------> +-------------------+
+-------------+ +---------+ | blocking_receiver |
+-------------------+
"""
@classmethod
def setUpClass(cls):
"""Configure and start QDR.A"""
super(LinkRouteProtocolTest, cls).setUpClass()
config = [
('router', {'mode': 'standalone', 'id': 'QDR.A'}),
# for client connections:
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the fake broker
('connector', {'name': 'broker',
'role': 'route-container',
'host': '127.0.0.1',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# forward 'org.apache' messages to + from fake broker:
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'out'})
]
config = Qdrouterd.Config(config)
cls.router = cls.tester.qdrouterd('A', config, wait=False)
def _fake_broker(self, cls):
"""Spawn a fake broker listening on the broker's connector
"""
fake_broker = cls(self.router.connector_addresses[0])
# wait until the connection to the fake broker activates
self.router.wait_connectors()
return fake_broker
def test_DISPATCH_1092(self):
# This fake broker will force the session closed after the link
# detaches. Verify that the session comes back up correctly when the
# next client attaches
killer = self._fake_broker(SessionKiller)
for i in range(2):
bconn = BlockingConnection(self.router.addresses[0])
bsender = bconn.create_sender(address="org.apache",
options=AtLeastOnce())
msg = Message(body="Hey!")
bsender.send(msg)
bsender.close()
bconn.close()
killer.join()
class SessionKiller(FakeBroker):
"""DISPATCH-1092: force a session close when the link closes. This should
cause the router to re-create the session when the next client attaches.
"""
def __init__(self, url):
super(SessionKiller, self).__init__(url)
def on_link_closing(self, event):
event.link.close()
event.session.close()
class FakeBrokerDrain(FakeBroker):
"""
DISPATCH-1496 - Make sure that the router does not grant additional credit
when drain is issued by a receiver connected to the router on a
link routed address
"""
def __init__(self, url):
super(FakeBrokerDrain, self).__init__(url)
self.first_flow_received = False
self.first_drain_mode = False
self.second_drain_mode = False
self.error = None
self.num_flows = 0
self.success = False
def on_link_flow(self, event):
if event.link.is_sender:
if event.sender.drain_mode:
if not self.first_drain_mode:
self.first_drain_mode = True
event.sender.drained()
elif not self.second_drain_mode:
self.second_drain_mode = True
if event.link.credit == 1000:
# Without the patch for DISPATCH-1496,
# the event.link.credit value would be 2000
self.success = True
else:
self.success = False
event.sender.drained()
else:
if not self.first_flow_received:
self.first_flow_received = True
msg = Message(body="First Drain Transfer")
event.link.send(msg)
class DrainReceiver(MessagingHandler):
def __init__(self, url, fake_broker):
super(DrainReceiver, self).__init__(prefetch=0, auto_accept=False)
self.url = url
self.received = 0
self.receiver = None
self.first_drain_sent = False
self.second_drain_sent = False
self.first_flow_sent = False
self.receiver_conn = None
self.error = None
self.num_flows = 0
self.fake_broker = fake_broker
def on_start(self, event):
self.receiver_conn = event.container.connect(self.url)
self.receiver = event.container.create_receiver(self.receiver_conn, "org.apache")
# Step 1: Send a flow of 1000 to the router. The router will forward this
# flow to the FakeBroker
self.receiver.flow(1000)
self.first_flow_sent = True
def on_link_flow(self, event):
if event.receiver == self.receiver:
self.num_flows += 1
if self.num_flows == 1:
# Step 4: The response drain received from the FakeBroker
# Step 5: Send second flow of 1000 credits. This is forwarded to the FakeBroker
self.receiver.flow(1000)
self.timer = event.reactor.schedule(3, TestTimeout(self))
elif self.num_flows == 2:
if not self.fake_broker.success:
self.error = "The FakeBroker did not receive correct credit of 1000"
self.receiver_conn.close()
def timeout(self):
# Step 6: The second drain is sent to the router. The router was forwarding the wrong credit (2000) to the FakeBroker
# but with the fix for DISPATCH-1496, the correct credit is forwarded (1000)
self.receiver.drain(0)
self.second_drain_sent = True
def on_message(self, event):
if event.receiver == self.receiver:
self.received += 1
# Step 2: In response to Step 1, the broker has sent the only message in its queue
if self.received == 1:
self.first_drain_sent = True
#print ("First message received. Doing first drain")
# Step 3: The receiver drains after receiving the first message.
# This drain is forwarded to the FakeBroker
self.receiver.drain(0)
def run(self):
Container(self).run()
class LinkRouteDrainTest(TestCase):
"""
Test link route drain implementation.
DISPATCH-1496 alleges that the router is granting extra credit when
forwarding the drain.
Uses a router which connects to a FakeBroker (FB)
+-------------+ +---------+
| | <------ | |
| fake broker | | QDR.A |
| | ------> | | ------> +-------------------+
+-------------+ +---------+ | receiver |
+-------------------+
The router will grant extra credit when the following sequence is used
1. The receiver attaches to the router on a a link routed address called "org.apache"
2. Receiver issues a flow of 1000. The FakeBroker has only one message in its
"examples" queue and it sends it over to the router which forwards it to the receiver
3. After receiving the message the receiver issues a drain(0). This drain is
forwarded to the FakeBroker by the router and the FB responds. There
is not problem with this drain
4. The receiver again gives a flow of 1000 and it is forwarded to the FB. There
are no messages in the broker queue, so the FB sends no messages
5. The receiver again issues a drain(0). At this time, without the fix for
DISPATCH-1496, the router issues double the credit to the FB. Instead
of issuing a credit of 1000, it issues a credit of 2000.
"""
@classmethod
def setUpClass(cls):
"""Configure and start QDR.A"""
super(LinkRouteDrainTest, cls).setUpClass()
config = [
('router', {'mode': 'standalone', 'id': 'QDR.A'}),
# for client connections:
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the fake broker
('connector', {'name': 'broker',
'role': 'route-container',
'host': '127.0.0.1',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# forward 'org.apache' messages to + from fake broker:
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'out'})
]
config = Qdrouterd.Config(config)
cls.router = cls.tester.qdrouterd('A', config, wait=False)
def _fake_broker(self, cls):
"""Spawn a fake broker listening on the broker's connector
"""
fake_broker = cls(self.router.connector_addresses[0])
# wait until the connection to the fake broker activates
self.router.wait_connectors()
return fake_broker
def test_DISPATCH_1496(self):
fake_broker = self._fake_broker(FakeBrokerDrain)
drain_receiver = DrainReceiver(self.router.addresses[0], fake_broker)
drain_receiver.run()
self.assertEquals(drain_receiver.error, None)
class ConnectionLinkRouteTest(TestCase):
"""
Test connection scoped link route implementation
Base configuration:
+-----------------+
+---------+ +---------+<--| blocking_sender |
+-----------------+ | | | | +-----------------+
| Fake LR Service |<==>| QDR.A |<==>| QDR.B |
+-----------------+ | | | | +-------------------+
+---------+ +---------+-->| blocking_receiver |
+-------------------+
The Fake Link Route Service will create connection-scoped link routes to
QDR.A, while blocking sender/receivers on QDR.B will send/receive messages
via the link route.
"""
_AS_TYPE = "org.apache.qpid.dispatch.router.connection.linkRoute"
@classmethod
def setUpClass(cls):
super(ConnectionLinkRouteTest, cls).setUpClass()
b_port = cls.tester.get_port()
configs = [
# QDR.A:
[('router', {'mode': 'interior', 'id': 'QDR.A'}),
# for fake connection-scoped LRs:
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for fake route-container LR connections:
('listener', {'role': 'route-container',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the QDR.B
('connector', {'role': 'inter-router',
'host': '127.0.0.1',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'})],
# QDR.B:
[('router', {'mode': 'interior', 'id': 'QDR.B'}),
# for client connections
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for connection to QDR.A
('listener', {'role': 'inter-router',
'host': '0.0.0.0',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'})]
]
cls.routers=[]
for c in configs:
config = Qdrouterd.Config(c)
cls.routers.append(cls.tester.qdrouterd(config=config, wait=False))
cls.QDR_A = cls.routers[0]
cls.QDR_B = cls.routers[1]
cls.QDR_A.wait_router_connected('QDR.B')
cls.QDR_B.wait_router_connected('QDR.A')
def _get_address(self, mgmt, addr):
a_type = 'org.apache.qpid.dispatch.router.address'
return list(filter(lambda a: a['name'].endswith(addr),
mgmt.query(a_type)))
def test_config_file_bad(self):
# verify that specifying a connection link route in the configuration
# file fails
config = [('router', {'mode': 'interior', 'id': 'QDR.X'}),
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': self.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
('connection.linkRoute',
{'pattern': "i/am/bad",
'direction': "out"})
]
cfg = Qdrouterd.Config(config)
router = self.tester.qdrouterd("X", cfg, wait=False)
# we expect the router to fail
while router.poll() is None:
sleep(0.1)
self.assertRaises(RuntimeError, router.teardown)
self.assertNotEqual(0, router.returncode)
def test_mgmt(self):
# test create, delete, and query
mgmt_conn = BlockingConnection(self.QDR_A.addresses[0])
mgmt_proxy = ConnLinkRouteMgmtProxy(mgmt_conn)
for i in range(10):
rsp = mgmt_proxy.create_conn_link_route("lr1-%d" % i,
{'pattern': "*/hi/there/%d" % i,
'direction':
'out' if i % 2 else 'in'})
self.assertEqual(201, rsp.status_code)
# test query
rsp = mgmt_proxy.query_conn_link_routes()
self.assertEqual(200, rsp.status_code)
self.assertEqual(10, len(rsp.results))
entities = rsp.results
# test read
rsp = mgmt_proxy.read_conn_link_route('lr1-5')
self.assertEqual(200, rsp.status_code)
self.assertEqual("lr1-5", rsp.attrs['name'])
self.assertEqual("*/hi/there/5", rsp.attrs['pattern'])
self.assertEqual(mgmt_conn.container.container_id,
rsp.attrs['containerId'])
# bad creates
attrs = [{'pattern': "bad", 'direction': "bad"},
{'direction': 'in'},
{},
{'pattern': ''},
{'pattern': 7}]
for a in attrs:
rsp = mgmt_proxy.create_conn_link_route("iamnoone", a)
self.assertEqual(400, rsp.status_code)
# bad read
rsp = mgmt_proxy.read_conn_link_route('iamnoone')
self.assertEqual(404, rsp.status_code)
# bad delete
rsp = mgmt_proxy.delete_conn_link_route('iamnoone')
self.assertEqual(404, rsp.status_code)
# delete all
for r in entities:
self.assertEqual(200, r.status_code)
rsp = mgmt_proxy.delete_conn_link_route(r.attrs['name'])
self.assertEqual(204, rsp.status_code)
# query - should be none left
rsp = mgmt_proxy.query_conn_link_routes()
self.assertEqual(200, rsp.status_code)
self.assertEqual(0, len(rsp.results))
def test_address_propagation(self):
# test service that creates and deletes connection link routes
fs = ConnLinkRouteService(self.QDR_A.addresses[1], container_id="FakeService",
config = [("clr1",
{"pattern": "flea.*",
"direction": "out"}),
("clr2",
{"pattern": "flea.*",
"direction": "in"})])
self.assertEqual(2, len(fs.values))
# the address should propagate to A and B
self.QDR_A.wait_address(address="Eflea.*")
self.QDR_A.wait_address(address="Fflea.*")
self.QDR_B.wait_address(address="Eflea.*")
self.QDR_B.wait_address(address="Fflea.*")
# now have the service delete the config
fs.delete_config()
# eventually the addresses will be un-published
mgmt_A = QdManager(self, address=self.QDR_A.addresses[0])
mgmt_B = QdManager(self, address=self.QDR_B.addresses[0])
deadline = time() + TIMEOUT
while (self._get_address(mgmt_A, "flea.*")
or self._get_address(mgmt_B, "flea.*")):
self.assertTrue(time() < deadline)
sleep(0.1)
fs.join();
# simple forwarding tests with auto delete
def test_send_receive(self):
COUNT = 5
mgmt_A = QdManager(self, address=self.QDR_A.addresses[0])
mgmt_B = QdManager(self, address=self.QDR_B.addresses[0])
# connect broker to A route-container
fs = ConnLinkRouteService(self.QDR_A.addresses[1], container_id="FakeService",
config = [("clr1",
{"pattern": "flea.*",
"direction": "out"}),
("clr2",
{"pattern": "flea.*",
"direction": "in"})])
self.assertEqual(2, len(fs.values))
# wait for the address to propagate to B
self.QDR_B.wait_address(address="Eflea.*")
self.QDR_B.wait_address(address="Fflea.*")
# ensure the link routes are not visible via other connections
clrs = mgmt_A.query(self._AS_TYPE)
self.assertEqual(0, len(clrs))
# send from A to B
r = AsyncTestReceiver(self.QDR_B.addresses[0],
"flea.B",
container_id="flea.BReceiver")
s = AsyncTestSender(self.QDR_A.addresses[0],
"flea.B",
container_id="flea.BSender",
message=Message(body="SENDING TO flea.B"),
count=COUNT)
s.wait() # for sender to complete
for i in range(COUNT):
self.assertEqual("SENDING TO flea.B",
r.queue.get(timeout=TIMEOUT).body)
r.stop()
self.assertEqual(COUNT, fs.in_count)
# send from B to A
r = AsyncTestReceiver(self.QDR_A.addresses[0],
"flea.A",
container_id="flea.AReceiver")
s = AsyncTestSender(self.QDR_B.addresses[0],
"flea.A",
container_id="flea.ASender",
message=Message(body="SENDING TO flea.A"),
count=COUNT)
s.wait()
for i in range(COUNT):
self.assertEqual("SENDING TO flea.A",
r.queue.get(timeout=TIMEOUT).body)
r.stop()
self.assertEqual(2 * COUNT, fs.in_count)
# once the fake service closes its conn the link routes
# are removed so the link route addresses must be gone
fs.join()
mgmt_A = QdManager(self, address=self.QDR_A.addresses[0])
mgmt_B = QdManager(self, address=self.QDR_B.addresses[0])
deadline = time() + TIMEOUT
while (self._get_address(mgmt_A, "flea.*")
or self._get_address(mgmt_B, "flea.*")):
self.assertTrue(time() < deadline)
sleep(0.1)
class ConnLinkRouteService(FakeBroker):
def __init__(self, url, container_id, config, timeout=TIMEOUT):
self.conn = None
self.mgmt_proxy = None
self.mgmt_sender = None
self.mgmt_receiver = None
self._config = config
self._config_index = 0
self._config_done = Event()
self._config_error = None
self._config_values = []
self._cleaning_up = False
self._delete_done = Event()
self._delete_count = 0
self._event_injector = EventInjector()
self._delete_event = ApplicationEvent("delete_config")
super(ConnLinkRouteService, self).__init__(url, container_id)
if self._config_done.wait(timeout) is False:
raise Exception("Timed out waiting for configuration setup")
if self._config_error is not None:
raise Exception("Error: %s" % self._config_error)
@property
def values(self):
return self._config_values
def delete_config(self):
self._event_injector.trigger(self._delete_event)
if self._delete_done.wait(TIMEOUT) is False:
raise Exception("Timed out waiting for configuration delete")
def on_start(self, event):
"""
Do not create an acceptor, actively connect instead
"""
event.container.selectable(self._event_injector)
self.conn = event.container.connect(self.url)
def on_connection_opened(self, event):
if event.connection == self.conn:
if self.mgmt_receiver is None:
self.mgmt_receiver = event.container.create_receiver(self.conn,
dynamic=True)
super(ConnLinkRouteService, self).on_connection_opened(event)
def on_connection_closed(self, event):
if self._event_injector:
self._event_injector.close()
self._event_injector = None
super(ConnLinkRouteService, self).on_connection_closed(event)
def on_link_opened(self, event):
if event.link == self.mgmt_receiver:
self.mgmt_proxy = MgmtMsgProxy(self.mgmt_receiver.remote_source.address)
self.mgmt_sender = event.container.create_sender(self.conn,
target="$management")
def on_link_error(self, event):
# when a remote client disconnects the service will get a link error
# that is expected - simply clean up the link
self.on_link_closing(event)
def on_sendable(self, event):
if event.sender == self.mgmt_sender:
if not self._cleaning_up:
if self._config_index < len(self._config):
cfg = self._config[self._config_index]
msg = self.mgmt_proxy.create_conn_link_route(cfg[0], cfg[1])
self.mgmt_sender.send(msg)
self._config_index += 1
elif self._config_values:
cv = self._config_values.pop()
msg = self.mgmt_proxy.delete_conn_link_route(cv['name'])
self._delete_count += 1
else:
super(ConnLinkRouteService, self).on_sendable(event)
def on_message(self, event):
if event.receiver == self.mgmt_receiver:
response = self.mgmt_proxy.response(event.message)
if response.status_code == 201:
# created:
self._config_values.append(response.attrs)
if len(self._config_values) == len(self._config):
self._config_done.set()
elif response.status_code == 204:
# deleted
self._delete_count -= 1
if (not self._config_values) and self._delete_count == 0:
self._delete_done.set()
else:
# error
self._config_error = ("mgmt failed: %s" %
response.status_description)
self._config_done.set()
self._delete_done.set()
else:
super(ConnLinkRouteService, self).on_message(event)
def on_delete_config(self, event):
if not self._cleaning_up:
self._cleaning_up = True
if not self._config_values:
self._delete_done.set()
else:
try:
while self.mgmt_sender.credit > 0:
cv = self._config_values.pop()
msg = self.mgmt_proxy.delete_conn_link_route(cv["name"])
self.mgmt_sender.send(msg)
self._delete_count += 1
except IndexError:
pass
class ConnLinkRouteMgmtProxy(object):
"""
Manage connection scoped link routes over a given connection.
While the connection remains open the connection scoped links will remain
configured and active
"""
def __init__(self, bconn, credit=250):
self._receiver = bconn.create_receiver(address=None, dynamic=True, credit=credit)
self._sender = bconn.create_sender(address="$management")
self._proxy = MgmtMsgProxy(self._receiver.link.remote_source.address)
def __getattr__(self, key):
# wrap accesses to the management message functions so we can send and
# receive the messages using the blocking links
f = getattr(self._proxy, key)
if not callable(f):
return f
def _func(*args, **kwargs):
self._sender.send(f(*args, **kwargs))
return self._proxy.response(self._receiver.receive())
return _func
class InvalidTagTest(MessagingHandler):
"""Verify that a message with an invalid tag length is rejected
"""
def __init__(self, router_addr):
super(InvalidTagTest, self).__init__(auto_accept=False, auto_settle=False)
self.test_conn = None
self.test_address = router_addr
self.tx_ct = 0;
self.accept_ct = 0;
self.reject_ct = 0;
self.error = None
def timeout(self):
self.error = "Timeout expired: sent=%d rcvd=%d" % (self.tx_ct,
self.accept_ct
+ self.reject_ct)
if self.test_conn:
self.test_conn.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.test_conn = event.container.connect(self.test_address)
rx = event.container.create_receiver(self.test_conn, "org.apache.foo")
def on_link_opened(self, event):
if event.receiver:
event.receiver.flow(100)
event.container.create_sender(event.connection, "org.apache.foo")
def on_sendable(self, event):
if self.tx_ct < 10:
self.tx_ct += 1
if self.tx_ct == 5:
event.sender.send(Message(body="YO"), tag=str("X" * 64))
else:
event.sender.send(Message(body="YO"), tag=str("BLAH%d" %
self.tx_ct))
def on_accepted(self, event):
self.accept_ct += 1
event.delivery.settle()
if self.accept_ct == 9 and self.reject_ct == 1:
event.connection.close()
self.timer.cancel()
def on_rejected(self, event):
self.reject_ct += 1
event.delivery.settle()
def on_message(self, event):
event.delivery.update(Delivery.ACCEPTED)
event.delivery.settle()
def run(self):
Container(self).run()
class Dispatch1428(TestCase):
"""
Sets up 2 routers (one of which are acting as brokers (QDR.A)).
QDR.A acting broker #1
+---------+ +---------+
| | <------ | |
| QDR.A | | QDR.B |
| | ------> | |
+---------+ +---------+
"""
@classmethod
def get_router(cls, index):
return cls.routers[index]
@classmethod
def setUpClass(cls):
"""Start two routers"""
super(Dispatch1428, cls).setUpClass()
def router(name, connection):
config = [
('router', {'mode': 'interior', 'id': 'QDR.%s'%name}),
] + connection
config = Qdrouterd.Config(config)
cls.routers.append(cls.tester.qdrouterd(name, config, wait=False))
cls.routers = []
a_listener_port = cls.tester.get_port()
b_listener_port = cls.tester.get_port()
router('A',
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
])
router('B',
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': b_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
('connector', {'name': 'one', 'role': 'route-container', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
('connector', {'name': 'two', 'role': 'route-container', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'})
]
)
sleep(2)
def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK, address=None):
p = self.popen(
['qdmanage'] + cmd.split(' ') + ['--bus', address or self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
universal_newlines=True)
out = p.communicate(input)[0]
try:
p.teardown()
except Exception as e:
raise Exception("%s\n%s" % (e, out))
return out
def test_both_link_routes_active(self):
cmds = [
'CREATE --type=linkRoute name=foo prefix=foo direction=in connection=one',
'CREATE --type=linkRoute name=bar prefix=bar direction=in connection=two',
'CREATE --type=linkRoute name=baz prefix=baz direction=in containerId=QDR.A'
]
for c in cmds:
self.run_qdmanage(cmd=c, address=self.routers[1].addresses[0])
# Now that the qdmanage has run, query the link routes and make sure that their "operStatus" is "active" before
# running any of the tests.
long_type = 'org.apache.qpid.dispatch.router.config.linkRoute'
qd_manager = QdManager(self, address=self.routers[1].addresses[0])
for i in range(5):
all_link_routes_activated = True
link_routes = qd_manager.query(long_type)
for link_route in link_routes:
oper_status = link_route['operStatus']
if oper_status != "active":
all_link_routes_activated = False
break
if not all_link_routes_activated:
# One or more of the link routes have not been activated.
# Check after one second.
sleep(1)
else:
break
# All link routes created in this test MUST be activated before
# we can continue further testing.
self.assertTrue(all_link_routes_activated)
first = SendReceive("%s/foo" % self.routers[1].addresses[0], "%s/foo" % self.routers[0].addresses[0])
first.run()
self.assertEqual(None, first.error)
second = SendReceive("%s/bar" % self.routers[1].addresses[0], "%s/bar" % self.routers[0].addresses[0])
second.run()
self.assertEqual(None, second.error)
third = SendReceive("%s/baz" % self.routers[1].addresses[0], "%s/baz" % self.routers[0].addresses[0])
third.run()
self.assertEqual(None, third.error)
class SendReceive(MessagingHandler):
def __init__(self, send_url, recv_url, message=None):
super(SendReceive, self).__init__()
self.send_url = send_url
self.recv_url = recv_url
self.message = message or Message(body="SendReceiveTest")
self.sent = False
self.error = None
def close(self):
self.sender.close()
self.receiver.close()
self.sender.connection.close()
self.receiver.connection.close()
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.close()
def stop(self):
self.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
event.container.container_id = "SendReceiveTestClient"
self.sender = event.container.create_sender(self.send_url)
self.receiver = event.container.create_receiver(self.recv_url)
def on_sendable(self, event):
if not self.sent:
event.sender.send(self.message)
self.sent = True
def on_message(self, event):
if self.message.body != event.message.body:
self.error = "Incorrect message. Got %s, expected %s" % (event.message.body, self.message.body)
def on_accepted(self, event):
self.stop()
def run(self):
Container(self).run()
class LinkRoute3Hop(TestCase):
"""
Sets up a linear 3 hop router network for testing multi-hop link routes.
+---------+ +---------+ +---------+ +------------------+
| | <------ | | <----- | |<----| blocking_senders |
| QDR.A | | QDR.B | | QDR.C | +------------------+
| | ------> | | ------> | | +--------------------+
+---------+ +---------+ +---------+---->| blocking_receivers |
^ +--------------------+
|
V
+-------------+
| FakeService |
+-------------+
"""
@classmethod
def setUpClass(cls):
super(LinkRoute3Hop, cls).setUpClass()
b_port = cls.tester.get_port()
configs = [
# QDR.A:
[('router', {'mode': 'interior', 'id': 'QDR.A'}),
# for client access
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for fake service:
('listener', {'role': 'route-container',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the QDR.B
('connector', {'role': 'inter-router',
'host': '127.0.0.1',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'}),
# the routes
('linkRoute', {'prefix': 'closest/test-client', 'containerId': 'FakeService', 'direction': 'in'}),
('linkRoute', {'prefix': 'closest/test-client', 'containerId': 'FakeService', 'direction': 'out'})
],
# QDR.B:
[('router', {'mode': 'interior', 'id': 'QDR.B'}),
# for client connections
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for inter-router connections from QDR.A and QDR.C
('listener', {'role': 'inter-router',
'host': '0.0.0.0',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'in'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'out'})
],
# QDR.C
[('router', {'mode': 'interior', 'id': 'QDR.C'}),
# for client connections
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the QDR.B
('connector', {'role': 'inter-router',
'host': '127.0.0.1',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'in'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'out'})
]
]
cls.routers=[]
for c in configs:
config = Qdrouterd.Config(c)
cls.routers.append(cls.tester.qdrouterd(config=config, wait=False))
cls.QDR_A = cls.routers[0]
cls.QDR_B = cls.routers[1]
cls.QDR_C = cls.routers[2]
cls.QDR_A.wait_router_connected('QDR.B')
cls.QDR_B.wait_router_connected('QDR.A')
cls.QDR_B.wait_router_connected('QDR.C')
cls.QDR_C.wait_router_connected('QDR.B')
cls.QDR_C.wait_router_connected('QDR.A')
cls.QDR_A.wait_router_connected('QDR.C')
cls.fake_service = FakeService(cls.QDR_A.addresses[1],
container_id="FakeService")
cls.QDR_C.wait_address("closest/test-client",
remotes=1)
def test_01_parallel_link_routes(self):
"""
Verify Q2/Q3 recovery in the case of multiple link-routes sharing the
same session.
"""
send_clients = 10
send_batch = 25
total = send_clients * send_batch
start_in = self.fake_service.in_count
start_out = self.fake_service.out_count
env = dict(os.environ, PN_TRACE_FRM="1")
rx = self.popen(["test-receiver",
"-a", self.QDR_C.addresses[0],
"-c", str(total),
"-s", "closest/test-client"],
env=env,
expect=Process.EXIT_OK)
def _spawn_sender(x):
return self.popen(["test-sender",
"-a", self.QDR_C.addresses[0],
"-c", str(send_batch),
"-i", "TestSender-%s" % x,
"-sx", # huge message size to trigger Q2/Q3
"-t", "closest/test-client"],
env=env,
expect=Process.EXIT_OK)
senders = [_spawn_sender(s) for s in range(send_clients)]
if rx.wait(timeout=TIMEOUT):
raise Exception("Receiver failed to consume all messages in=%s out=%s",
self.fake_service.in_count,
self.fake_service.out_count)
for tx in senders:
out_text, out_err = tx.communicate(timeout=TIMEOUT)
if tx.returncode:
raise Exception("Sender failed: %s %s" % (out_text, out_err))
self.assertEqual(start_in + total, self.fake_service.in_count)
self.assertEqual(start_out + total, self.fake_service.out_count)
if __name__ == '__main__':
unittest.main(main_module())
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
internal/operator/pgdump/dump.go
|
package pgdump
/*
Copyright 2019 - 2021 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"
"context"
"encoding/json"
"os"
"github.com/crunchydata/postgres-operator/internal/config"
"github.com/crunchydata/postgres-operator/internal/kubeapi"
"github.com/crunchydata/postgres-operator/internal/operator"
"github.com/crunchydata/postgres-operator/internal/operator/pvc"
"github.com/crunchydata/postgres-operator/internal/util"
crv1 "github.com/crunchydata/postgres-operator/pkg/apis/crunchydata.com/v1"
log "github.com/sirupsen/logrus"
v1batch "k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
type pgDumpJobTemplateFields struct {
JobName string
TaskName string
Name string // ??
ClusterName string
Command string // ??
CommandOpts string
PvcName string
PodName string // ??
CCPImagePrefix string
CCPImageTag string
SecurityContext string
PgDumpHost string
PgDumpUserSecret string
PgDumpDB string
PgDumpPort string
PgDumpOpts string
PgDumpFilename string
PgDumpAll string
PgDumpPVC string
Tolerations string
CustomLabels string
}
// Dump ...
func Dump(namespace string, clientset kubeapi.Interface, task *crv1.Pgtask) {
ctx := context.TODO()
var err error
// make sure the provided clustername is not empty
clusterName := task.Spec.Parameters[config.LABEL_PG_CLUSTER]
if clusterName == "" {
log.Error("unable to create pgdump job, clustername is empty.")
return
}
// get the pgcluster CRD for cases where a CCPImagePrefix is specified
cluster, err := clientset.CrunchydataV1().Pgclusters(namespace).Get(ctx, clusterName, metav1.GetOptions{})
if err != nil {
log.Error(err)
return
}
// create the Job to run the pgdump command
cmd := task.Spec.Parameters[config.LABEL_PGDUMP_COMMAND]
pvcName := task.Spec.Parameters[config.LABEL_PVC_NAME]
// create the PVC if name is empty or it doesn't exist
if !(len(pvcName) > 0) || !pvc.Exists(clientset, pvcName, namespace) {
// set pvcName if empty - should not be empty as apiserver code should have specified.
if !(len(pvcName) > 0) {
pvcName = task.Spec.Name + "-pvc"
}
pvcName, err = pvc.CreatePVC(clientset, &task.Spec.StorageSpec, pvcName,
task.Spec.Parameters[config.LABEL_PGDUMP_HOST], namespace, util.GetCustomLabels(cluster))
if err != nil {
log.Error(err.Error())
} else {
log.Info("created backup PVC =" + pvcName + " in namespace " + namespace)
}
}
// this task name should match
taskName := task.Name
jobName := taskName + "-" + util.RandStringBytesRmndr(4)
jobFields := pgDumpJobTemplateFields{
JobName: jobName,
TaskName: taskName,
ClusterName: task.Spec.Parameters[config.LABEL_PG_CLUSTER],
PodName: task.Spec.Parameters[config.LABEL_POD_NAME],
SecurityContext: operator.GetPodSecurityContext(task.Spec.StorageSpec.GetSupplementalGroups()),
Command: cmd, //??
CommandOpts: task.Spec.Parameters[config.LABEL_PGDUMP_OPTS],
CCPImagePrefix: util.GetValueOrDefault(cluster.Spec.CCPImagePrefix, operator.Pgo.Cluster.CCPImagePrefix),
CCPImageTag: util.GetValueOrDefault(util.GetStandardImageTag(cluster.Spec.CCPImage, cluster.Spec.CCPImageTag),
operator.Pgo.Cluster.CCPImageTag),
PgDumpHost: task.Spec.Parameters[config.LABEL_PGDUMP_HOST],
PgDumpUserSecret: task.Spec.Parameters[config.LABEL_PGDUMP_USER],
PgDumpDB: task.Spec.Parameters[config.LABEL_PGDUMP_DB],
PgDumpPort: task.Spec.Parameters[config.LABEL_PGDUMP_PORT],
PgDumpOpts: task.Spec.Parameters[config.LABEL_PGDUMP_OPTS],
PgDumpAll: task.Spec.Parameters[config.LABEL_PGDUMP_ALL],
PgDumpPVC: pvcName,
Tolerations: util.GetTolerations(cluster.Spec.Tolerations),
CustomLabels: operator.GetLabelsFromMap(util.GetCustomLabels(cluster), false),
}
var doc2 bytes.Buffer
err = config.PgDumpBackupJobTemplate.Execute(&doc2, jobFields)
if err != nil {
log.Error(err.Error())
return
}
if operator.CRUNCHY_DEBUG {
_ = config.PgDumpBackupJobTemplate.Execute(os.Stdout, jobFields)
}
newjob := v1batch.Job{}
err = json.Unmarshal(doc2.Bytes(), &newjob)
if err != nil {
log.Error("error unmarshalling json into Job " + err.Error())
return
}
// set the container image to an override value, if one exists
operator.SetContainerImageOverride(config.CONTAINER_IMAGE_CRUNCHY_POSTGRES_HA,
&newjob.Spec.Template.Spec.Containers[0])
_, err = clientset.BatchV1().Jobs(namespace).Create(ctx, &newjob, metav1.CreateOptions{})
if err != nil {
return
}
// update the pgdump task status to submitted - updates task, not the job.
patch, err := kubeapi.NewJSONPatch().Add("spec", "status")(crv1.PgBackupJobSubmitted).Bytes()
if err == nil {
log.Debugf("patching task %s: %s", task.Spec.Name, patch)
_, err = clientset.CrunchydataV1().Pgtasks(namespace).
Patch(ctx, task.Spec.Name, types.JSONPatchType, patch, metav1.PatchOptions{})
}
if err != nil {
log.Error(err.Error())
}
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
kegwasher-service/kegwasher/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 Kyle Hultman <[email protected]>
import logging
import os
from kegwasher.actions import *
from kegwasher.config import *
from kegwasher.hardware import *
from kegwasher.linked_list import *
from kegwasher.operations import *
from kegwasher.pca955x import *
from kegwasher.service import *
# Setup Logging
logging_levels = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG
}
log = logging.getLogger(os.getenv('LOGGER_NAME', 'kegwasher'))
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)
log.setLevel(logging_levels.get(os.getenv('LOG_LEVEL', 'INFO'), logging.INFO))
|
[] |
[] |
[
"LOGGER_NAME",
"LOG_LEVEL"
] |
[]
|
["LOGGER_NAME", "LOG_LEVEL"]
|
python
| 2 | 0 | |
setup.py
|
#!/usr/bin/env python
import os
import re
import shutil
import subprocess
from pathlib import Path
from setuptools import setup, find_packages
import distutils.command.clean
from tools import setup_helpers
ROOT_DIR = Path(__file__).parent.resolve()
def _run_cmd(cmd):
try:
return subprocess.check_output(cmd, cwd=ROOT_DIR).decode('ascii').strip()
except Exception:
return None
def _get_version(sha):
version = '0.11.0a0'
if os.getenv('BUILD_VERSION'):
version = os.getenv('BUILD_VERSION')
elif sha is not None:
version += '+' + sha[:7]
return version
def _make_version_file(version, sha):
sha = 'Unknown' if sha is None else sha
version_path = ROOT_DIR / 'torchaudio' / 'version.py'
with open(version_path, 'w') as f:
f.write(f"__version__ = '{version}'\n")
f.write(f"git_version = '{sha}'\n")
def _get_pytorch_version():
if 'PYTORCH_VERSION' in os.environ:
return f"torch=={os.environ['PYTORCH_VERSION']}"
return 'torch'
class clean(distutils.command.clean.clean):
def run(self):
# Run default behavior first
distutils.command.clean.clean.run(self)
# Remove torchaudio extension
for path in (ROOT_DIR / 'torchaudio').glob('**/*.so'):
print(f'removing \'{path}\'')
path.unlink()
# Remove build directory
build_dirs = [
ROOT_DIR / 'build',
]
for path in build_dirs:
if path.exists():
print(f'removing \'{path}\' (and everything under it)')
shutil.rmtree(str(path), ignore_errors=True)
def _get_packages(branch_name, tag):
exclude = [
"build*",
"test*",
"torchaudio.csrc*",
"third_party*",
"tools*",
]
exclude_prototype = False
if branch_name is not None and branch_name.startswith('release/'):
exclude_prototype = True
if tag is not None and re.match(r'v[\d.]+(-rc\d+)?', tag):
exclude_prototype = True
if exclude_prototype:
print('Excluding torchaudio.prototype from the package.')
exclude.append("torchaudio.prototype")
return find_packages(exclude=exclude)
def _main():
sha = _run_cmd(['git', 'rev-parse', 'HEAD'])
branch = _run_cmd(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
tag = _run_cmd(['git', 'describe', '--tags', '--exact-match', '@'])
print('-- Git branch:', branch)
print('-- Git SHA:', sha)
print('-- Git tag:', tag)
pytorch_package_dep = _get_pytorch_version()
print('-- PyTorch dependency:', pytorch_package_dep)
version = _get_version(sha)
print('-- Building version', version)
_make_version_file(version, sha)
setup(
name="torchaudio",
version=version,
description="An audio package for PyTorch",
url="https://github.com/pytorch/audio",
author="Soumith Chintala, David Pollack, Sean Naren, Peter Goldsborough",
author_email="[email protected]",
classifiers=[
"Environment :: Plugins",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: C++",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Multimedia :: Sound/Audio",
"Topic :: Scientific/Engineering :: Artificial Intelligence"
],
packages=_get_packages(branch, tag),
ext_modules=setup_helpers.get_ext_modules(),
cmdclass={
'build_ext': setup_helpers.CMakeBuild,
'clean': clean,
},
install_requires=[pytorch_package_dep],
zip_safe=False,
)
if __name__ == '__main__':
_main()
|
[] |
[] |
[
"BUILD_VERSION",
"PYTORCH_VERSION"
] |
[]
|
["BUILD_VERSION", "PYTORCH_VERSION"]
|
python
| 2 | 0 | |
tfx/components/example_gen/custom_executors/parquet_component_test.py
|
# Lint as: python2, python3
# Copyright 2019 Google LLC. 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.
"""Tests for using parquet_executor with example_gen component."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import mock
import tensorflow as tf
from ml_metadata.proto import metadata_store_pb2
from tfx.components.base import executor_spec
from tfx.components.example_gen.component import FileBasedExampleGen
from tfx.components.example_gen.custom_executors import parquet_executor
from tfx.orchestration import data_types
from tfx.orchestration import publisher
from tfx.orchestration.launcher import in_process_component_launcher
from tfx.proto import example_gen_pb2
from tfx.types import artifact_utils
from tfx.types import standard_artifacts
from tfx.utils.dsl_utils import external_input
class ExampleGenComponentWithParquetExecutorTest(tf.test.TestCase):
def setUp(self):
super(ExampleGenComponentWithParquetExecutorTest, self).setUp()
# Create input_base.
input_data_dir = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'testdata')
self.parquet_dir_path = os.path.join(input_data_dir, 'external')
# Create input_config.
self.input_config = example_gen_pb2.Input(splits=[
example_gen_pb2.Input.Split(name='parquet',
pattern='parquet/*.parquet'),
])
# Create output_config.
self.output_config = example_gen_pb2.Output(
split_config=example_gen_pb2.SplitConfig(splits=[
example_gen_pb2.SplitConfig.Split(name='train', hash_buckets=2),
example_gen_pb2.SplitConfig.Split(name='eval', hash_buckets=1)
]))
@mock.patch.object(publisher, 'Publisher')
def testRun(self, mock_publisher):
mock_publisher.return_value.publish_execution.return_value = {}
example_gen = FileBasedExampleGen(
custom_executor_spec=executor_spec.ExecutorClassSpec(
parquet_executor.Executor),
input=external_input(self.parquet_dir_path),
input_config=self.input_config,
output_config=self.output_config,
instance_name='ParquetExampleGen')
output_data_dir = os.path.join(
os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR', self.get_temp_dir()),
self._testMethodName)
pipeline_root = os.path.join(output_data_dir, 'Test')
tf.io.gfile.makedirs(pipeline_root)
pipeline_info = data_types.PipelineInfo(
pipeline_name='Test', pipeline_root=pipeline_root, run_id='123')
driver_args = data_types.DriverArgs(enable_cache=True)
connection_config = metadata_store_pb2.ConnectionConfig()
connection_config.sqlite.SetInParent()
launcher = in_process_component_launcher.InProcessComponentLauncher.create(
component=example_gen,
pipeline_info=pipeline_info,
driver_args=driver_args,
metadata_connection_config=connection_config,
beam_pipeline_args=[],
additional_pipeline_args={})
self.assertEqual(
launcher._component_info.component_type,
'.'.join([FileBasedExampleGen.__module__,
FileBasedExampleGen.__name__]))
launcher.launch()
mock_publisher.return_value.publish_execution.assert_called_once()
# Get output paths.
component_id = example_gen.id
output_path = os.path.join(pipeline_root, component_id, 'examples/1')
examples = standard_artifacts.Examples()
examples.uri = output_path
examples.split_names = artifact_utils.encode_split_names(['train', 'eval'])
# Check parquet example gen outputs.
train_output_file = os.path.join(examples.uri, 'train',
'data_tfrecord-00000-of-00001.gz')
eval_output_file = os.path.join(examples.uri, 'eval',
'data_tfrecord-00000-of-00001.gz')
self.assertTrue(tf.io.gfile.exists(train_output_file))
self.assertTrue(tf.io.gfile.exists(eval_output_file))
self.assertGreater(
tf.io.gfile.GFile(train_output_file).size(),
tf.io.gfile.GFile(eval_output_file).size())
if __name__ == '__main__':
tf.test.main()
|
[] |
[] |
[
"TEST_UNDECLARED_OUTPUTS_DIR"
] |
[]
|
["TEST_UNDECLARED_OUTPUTS_DIR"]
|
python
| 1 | 0 | |
check/test_test.go
|
// Copyright © 2017 Aqua Security Software Ltd. <[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.
package check
import (
"io/ioutil"
"os"
"strings"
"testing"
)
var (
in []byte
controls *Controls
)
func init() {
var err error
in, err = ioutil.ReadFile("data")
if err != nil {
panic("Failed reading test data: " + err.Error())
}
// substitute variables in data file
user := os.Getenv("USER")
s := strings.Replace(string(in), "$user", user, -1)
controls, err = NewControls(MASTER, []byte(s))
// controls, err = NewControls(MASTER, in)
if err != nil {
panic("Failed creating test controls: " + err.Error())
}
}
func TestTestExecute(t *testing.T) {
cases := []struct {
*Check
str string
}{
{
controls.Groups[0].Checks[0],
"2:45 ../kubernetes/kube-apiserver --allow-privileged=false --option1=20,30,40",
},
{
controls.Groups[0].Checks[1],
"2:45 ../kubernetes/kube-apiserver --allow-privileged=false",
},
{
controls.Groups[0].Checks[2],
"niinai 13617 2635 99 19:26 pts/20 00:03:08 ./kube-apiserver --insecure-port=0 --anonymous-auth",
},
{
controls.Groups[0].Checks[3],
"2:45 ../kubernetes/kube-apiserver --secure-port=0 --audit-log-maxage=40 --option",
},
{
controls.Groups[0].Checks[4],
"2:45 ../kubernetes/kube-apiserver --max-backlog=20 --secure-port=0 --audit-log-maxage=40 --option",
},
{
controls.Groups[0].Checks[5],
"2:45 ../kubernetes/kube-apiserver --option --admission-control=WebHook,RBAC ---audit-log-maxage=40",
},
{
controls.Groups[0].Checks[6],
"2:45 .. --kubelet-clientkey=foo --kubelet-client-certificate=bar --admission-control=Webhook,RBAC",
},
{
controls.Groups[0].Checks[7],
"2:45 .. --secure-port=0 --kubelet-client-certificate=bar --admission-control=Webhook,RBAC",
},
{
controls.Groups[0].Checks[8],
"644",
},
{
controls.Groups[0].Checks[9],
"640",
},
{
controls.Groups[0].Checks[9],
"600",
},
{
controls.Groups[0].Checks[10],
"2:45 ../kubernetes/kube-apiserver --option --admission-control=WebHook,RBAC ---audit-log-maxage=40",
},
{
controls.Groups[0].Checks[11],
"2:45 ../kubernetes/kube-apiserver --option --admission-control=WebHook,RBAC ---audit-log-maxage=40",
},
{
controls.Groups[0].Checks[12],
"2:45 ../kubernetes/kube-apiserver --option --admission-control=WebHook,Something,RBAC ---audit-log-maxage=40",
},
{
controls.Groups[0].Checks[13],
"2:45 ../kubernetes/kube-apiserver --option --admission-control=Something ---audit-log-maxage=40",
},
{
// check for ':' as argument-value separator, with space between arg and val
controls.Groups[0].Checks[14],
"2:45 kube-apiserver some-arg: some-val --admission-control=Something ---audit-log-maxage=40",
},
{
// check for ':' as argument-value separator, with no space between arg and val
controls.Groups[0].Checks[14],
"2:45 kube-apiserver some-arg:some-val --admission-control=Something ---audit-log-maxage=40",
},
{
controls.Groups[0].Checks[15],
"{\"readOnlyPort\": 15000}",
},
{
controls.Groups[0].Checks[16],
"{\"stringValue\": \"WebHook,Something,RBAC\"}",
},
{
controls.Groups[0].Checks[17],
"{\"trueValue\": true}",
},
{
controls.Groups[0].Checks[18],
"{\"readOnlyPort\": 15000}",
},
{
controls.Groups[0].Checks[19],
"{\"authentication\": { \"anonymous\": {\"enabled\": false}}}",
},
{
controls.Groups[0].Checks[20],
"readOnlyPort: 15000",
},
{
controls.Groups[0].Checks[21],
"readOnlyPort: 15000",
},
{
controls.Groups[0].Checks[22],
"authentication:\n anonymous:\n enabled: false",
},
{
controls.Groups[0].Checks[26],
"currentMasterVersion: 1.12.7",
},
}
for _, c := range cases {
res := c.Tests.execute(c.str).testResult
if !res {
t.Errorf("%s, expected:%v, got:%v\n", c.Text, true, res)
}
}
}
func TestTestExecuteExceptions(t *testing.T) {
cases := []struct {
*Check
str string
}{
{
controls.Groups[0].Checks[23],
"this is not valid json {} at all",
},
{
controls.Groups[0].Checks[24],
"{\"key\": \"value\"}",
},
{
controls.Groups[0].Checks[25],
"broken } yaml\nenabled: true",
},
{
controls.Groups[0].Checks[26],
"currentMasterVersion: 1.11",
},
{
controls.Groups[0].Checks[26],
"currentMasterVersion: ",
},
}
for _, c := range cases {
res := c.Tests.execute(c.str).testResult
if res {
t.Errorf("%s, expected:%v, got:%v\n", c.Text, false, res)
}
}
}
func TestTestUnmarshal(t *testing.T) {
type kubeletConfig struct {
Kind string
ApiVersion string
Address string
}
cases := []struct {
content string
jsonInterface interface{}
expectedToFail bool
}{
{
`{
"kind": "KubeletConfiguration",
"apiVersion": "kubelet.config.k8s.io/v1beta1",
"address": "0.0.0.0"
}
`,
kubeletConfig{},
false,
}, {
`
kind: KubeletConfiguration
address: 0.0.0.0
apiVersion: kubelet.config.k8s.io/v1beta1
authentication:
anonymous:
enabled: false
webhook:
cacheTTL: 2m0s
enabled: true
x509:
clientCAFile: /etc/kubernetes/pki/ca.crt
tlsCipherSuites:
- TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
`,
kubeletConfig{},
false,
},
{
`
kind: ddress: 0.0.0.0
apiVersion: kubelet.config.k8s.io/v1beta
`,
kubeletConfig{},
true,
},
}
for _, c := range cases {
err := unmarshal(c.content, &c.jsonInterface)
if err != nil {
if !c.expectedToFail {
t.Errorf("%s, expectedToFail:%v, got:%v\n", c.content, c.expectedToFail, err)
}
} else {
if c.expectedToFail {
t.Errorf("%s, expectedToFail:%v, got:Did not fail\n", c.content, c.expectedToFail)
}
}
}
}
func TestExecuteJSONPath(t *testing.T) {
type kubeletConfig struct {
Kind string
ApiVersion string
Address string
}
cases := []struct {
jsonPath string
jsonInterface kubeletConfig
expectedResult string
expectedToFail bool
}{
{
// JSONPath parse works, results don't match
"{.Kind}",
kubeletConfig{
Kind: "KubeletConfiguration",
ApiVersion: "kubelet.config.k8s.io/v1beta1",
Address: "127.0.0.0",
},
"blah",
true,
},
{
// JSONPath parse works, results match
"{.Kind}",
kubeletConfig{
Kind: "KubeletConfiguration",
ApiVersion: "kubelet.config.k8s.io/v1beta1",
Address: "127.0.0.0",
},
"KubeletConfiguration",
false,
},
{
// JSONPath parse fails
"{.ApiVersion",
kubeletConfig{
Kind: "KubeletConfiguration",
ApiVersion: "kubelet.config.k8s.io/v1beta1",
Address: "127.0.0.0",
},
"",
true,
},
}
for _, c := range cases {
result, err := executeJSONPath(c.jsonPath, c.jsonInterface)
if err != nil && !c.expectedToFail {
t.Fatalf("jsonPath:%q, expectedResult:%q got:%v\n", c.jsonPath, c.expectedResult, err)
}
if c.expectedResult != result && !c.expectedToFail {
t.Errorf("jsonPath:%q, expectedResult:%q got:%q\n", c.jsonPath, c.expectedResult, result)
}
}
}
func TestAllElementsValid(t *testing.T) {
cases := []struct {
source []string
target []string
valid bool
}{
{
source: []string{},
target: []string{},
valid: true,
},
{
source: []string{"blah"},
target: []string{},
valid: false,
},
{
source: []string{},
target: []string{"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_GCM_SHA256"},
valid: false,
},
{
source: []string{"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"},
target: []string{"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_GCM_SHA256"},
valid: true,
},
{
source: []string{"blah"},
target: []string{"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_GCM_SHA256"},
valid: false,
},
{
source: []string{"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "blah"},
target: []string{"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_GCM_SHA256"},
valid: false,
},
}
for _, c := range cases {
if !allElementsValid(c.source, c.target) && c.valid {
t.Errorf("Not All Elements in %q are found in %q \n", c.source, c.target)
}
}
}
func TestSplitAndRemoveLastSeparator(t *testing.T) {
cases := []struct {
source string
valid bool
elementCnt int
}{
{
source: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_128_GCM_SHA256",
valid: true,
elementCnt: 8,
},
{
source: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,",
valid: true,
elementCnt: 2,
},
{
source: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,",
valid: true,
elementCnt: 2,
},
{
source: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, ",
valid: true,
elementCnt: 2,
},
{
source: " TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,",
valid: true,
elementCnt: 2,
},
}
for _, c := range cases {
as := splitAndRemoveLastSeparator(c.source, defaultArraySeparator)
if len(as) == 0 && c.valid {
t.Errorf("Split did not work with %q \n", c.source)
}
if c.elementCnt != len(as) {
t.Errorf("Split did not work with %q expected: %d got: %d\n", c.source, c.elementCnt, len(as))
}
}
}
func TestCompareOp(t *testing.T) {
cases := []struct {
label string
op string
flagVal string
compareValue string
expectedResultPattern string
testResult bool
}{
// Test Op not matching
{label: "empty - op", op: "", flagVal: "", compareValue: "", expectedResultPattern: "", testResult: false},
{label: "op=blah", op: "blah", flagVal: "foo", compareValue: "bar", expectedResultPattern: "", testResult: false},
// Test Op "eq"
{label: "op=eq, both empty", op: "eq", flagVal: "", compareValue: "", expectedResultPattern: "'' is equal to ''", testResult: true},
{label: "op=eq, true==true", op: "eq", flagVal: "true",
compareValue: "true",
expectedResultPattern: "'true' is equal to 'true'",
testResult: true},
{label: "op=eq, false==false", op: "eq", flagVal: "false",
compareValue: "false",
expectedResultPattern: "'false' is equal to 'false'",
testResult: true},
{label: "op=eq, false==true", op: "eq", flagVal: "false",
compareValue: "true",
expectedResultPattern: "'false' is equal to 'true'",
testResult: false},
{label: "op=eq, strings match", op: "eq", flagVal: "KubeletConfiguration",
compareValue: "KubeletConfiguration",
expectedResultPattern: "'KubeletConfiguration' is equal to 'KubeletConfiguration'",
testResult: true},
{label: "op=eq, flagVal=empty", op: "eq", flagVal: "",
compareValue: "KubeletConfiguration",
expectedResultPattern: "'' is equal to 'KubeletConfiguration'",
testResult: false},
{label: "op=eq, compareValue=empty", op: "eq", flagVal: "KubeletConfiguration",
compareValue: "",
expectedResultPattern: "'KubeletConfiguration' is equal to ''",
testResult: false},
// Test Op "noteq"
{label: "op=noteq, both empty", op: "noteq", flagVal: "",
compareValue: "", expectedResultPattern: "'' is not equal to ''",
testResult: false},
{label: "op=noteq, true!=true", op: "noteq", flagVal: "true",
compareValue: "true",
expectedResultPattern: "'true' is not equal to 'true'",
testResult: false},
{label: "op=noteq, false!=false", op: "noteq", flagVal: "false",
compareValue: "false",
expectedResultPattern: "'false' is not equal to 'false'",
testResult: false},
{label: "op=noteq, false!=true", op: "noteq", flagVal: "false",
compareValue: "true",
expectedResultPattern: "'false' is not equal to 'true'",
testResult: true},
{label: "op=noteq, strings match", op: "noteq", flagVal: "KubeletConfiguration",
compareValue: "KubeletConfiguration",
expectedResultPattern: "'KubeletConfiguration' is not equal to 'KubeletConfiguration'",
testResult: false},
{label: "op=noteq, flagVal=empty", op: "noteq", flagVal: "",
compareValue: "KubeletConfiguration",
expectedResultPattern: "'' is not equal to 'KubeletConfiguration'",
testResult: true},
{label: "op=noteq, compareValue=empty", op: "noteq", flagVal: "KubeletConfiguration",
compareValue: "",
expectedResultPattern: "'KubeletConfiguration' is not equal to ''",
testResult: true},
// Test Op "gt"
// TODO: test for non-numeric values.
// toNumeric function currently uses os.Exit, which stops tests.
// {label: "op=gt, both empty", op: "gt", flagVal: "",
// compareValue: "", expectedResultPattern: "'' is greater than ''",
// testResult: true},
{label: "op=gt, 0 > 0", op: "gt", flagVal: "0",
compareValue: "0", expectedResultPattern: "0 is greater than 0",
testResult: false},
{label: "op=gt, 4 > 5", op: "gt", flagVal: "4",
compareValue: "5", expectedResultPattern: "4 is greater than 5",
testResult: false},
{label: "op=gt, 5 > 4", op: "gt", flagVal: "5",
compareValue: "4", expectedResultPattern: "5 is greater than 4",
testResult: true},
{label: "op=gt, 5 > 5", op: "gt", flagVal: "5",
compareValue: "5", expectedResultPattern: "5 is greater than 5",
testResult: false},
// Test Op "lt"
// TODO: test for non-numeric values.
// toNumeric function currently uses os.Exit, which stops tests.
// {label: "op=lt, both empty", op: "lt", flagVal: "",
// compareValue: "", expectedResultPattern: "'' is lower than ''",
// testResult: true},
{label: "op=gt, 0 < 0", op: "lt", flagVal: "0",
compareValue: "0", expectedResultPattern: "0 is lower than 0",
testResult: false},
{label: "op=gt, 4 < 5", op: "lt", flagVal: "4",
compareValue: "5", expectedResultPattern: "4 is lower than 5",
testResult: true},
{label: "op=gt, 5 < 4", op: "lt", flagVal: "5",
compareValue: "4", expectedResultPattern: "5 is lower than 4",
testResult: false},
{label: "op=gt, 5 < 5", op: "lt", flagVal: "5",
compareValue: "5", expectedResultPattern: "5 is lower than 5",
testResult: false},
// Test Op "gte"
// TODO: test for non-numeric values.
// toNumeric function currently uses os.Exit, which stops tests.
// {label: "op=gt, both empty", op: "gte", flagVal: "",
// compareValue: "", expectedResultPattern: "'' is greater or equal to ''",
// testResult: true},
{label: "op=gt, 0 >= 0", op: "gte", flagVal: "0",
compareValue: "0", expectedResultPattern: "0 is greater or equal to 0",
testResult: true},
{label: "op=gt, 4 >= 5", op: "gte", flagVal: "4",
compareValue: "5", expectedResultPattern: "4 is greater or equal to 5",
testResult: false},
{label: "op=gt, 5 >= 4", op: "gte", flagVal: "5",
compareValue: "4", expectedResultPattern: "5 is greater or equal to 4",
testResult: true},
{label: "op=gt, 5 >= 5", op: "gte", flagVal: "5",
compareValue: "5", expectedResultPattern: "5 is greater or equal to 5",
testResult: true},
// Test Op "lte"
// TODO: test for non-numeric values.
// toNumeric function currently uses os.Exit, which stops tests.
// {label: "op=gt, both empty", op: "lte", flagVal: "",
// compareValue: "", expectedResultPattern: "'' is lower or equal to ''",
// testResult: true},
{label: "op=gt, 0 <= 0", op: "lte", flagVal: "0",
compareValue: "0", expectedResultPattern: "0 is lower or equal to 0",
testResult: true},
{label: "op=gt, 4 <= 5", op: "lte", flagVal: "4",
compareValue: "5", expectedResultPattern: "4 is lower or equal to 5",
testResult: true},
{label: "op=gt, 5 <= 4", op: "lte", flagVal: "5",
compareValue: "4", expectedResultPattern: "5 is lower or equal to 4",
testResult: false},
{label: "op=gt, 5 <= 5", op: "lte", flagVal: "5",
compareValue: "5", expectedResultPattern: "5 is lower or equal to 5",
testResult: true},
// Test Op "has"
{label: "op=gt, both empty", op: "has", flagVal: "",
compareValue: "", expectedResultPattern: "'' has ''",
testResult: true},
{label: "op=gt, flagVal=empty", op: "has", flagVal: "",
compareValue: "blah", expectedResultPattern: "'' has 'blah'",
testResult: false},
{label: "op=gt, compareValue=empty", op: "has", flagVal: "blah",
compareValue: "", expectedResultPattern: "'blah' has ''",
testResult: true},
{label: "op=gt, 'blah' has 'la'", op: "has", flagVal: "blah",
compareValue: "la", expectedResultPattern: "'blah' has 'la'",
testResult: true},
{label: "op=gt, 'blah' has 'LA'", op: "has", flagVal: "blah",
compareValue: "LA", expectedResultPattern: "'blah' has 'LA'",
testResult: false},
{label: "op=gt, 'blah' has 'lo'", op: "has", flagVal: "blah",
compareValue: "lo", expectedResultPattern: "'blah' has 'lo'",
testResult: false},
// Test Op "nothave"
{label: "op=gt, both empty", op: "nothave", flagVal: "",
compareValue: "", expectedResultPattern: " '' not have ''",
testResult: false},
{label: "op=gt, flagVal=empty", op: "nothave", flagVal: "",
compareValue: "blah", expectedResultPattern: " '' not have 'blah'",
testResult: true},
{label: "op=gt, compareValue=empty", op: "nothave", flagVal: "blah",
compareValue: "", expectedResultPattern: " 'blah' not have ''",
testResult: false},
{label: "op=gt, 'blah' not have 'la'", op: "nothave", flagVal: "blah",
compareValue: "la", expectedResultPattern: " 'blah' not have 'la'",
testResult: false},
{label: "op=gt, 'blah' not have 'LA'", op: "nothave", flagVal: "blah",
compareValue: "LA", expectedResultPattern: " 'blah' not have 'LA'",
testResult: true},
{label: "op=gt, 'blah' not have 'lo'", op: "nothave", flagVal: "blah",
compareValue: "lo", expectedResultPattern: " 'blah' not have 'lo'",
testResult: true},
// Test Op "regex"
{label: "op=gt, both empty", op: "regex", flagVal: "",
compareValue: "", expectedResultPattern: " '' matched by ''",
testResult: true},
{label: "op=gt, flagVal=empty", op: "regex", flagVal: "",
compareValue: "blah", expectedResultPattern: " '' matched by 'blah'",
testResult: false},
// Test Op "valid_elements"
{label: "op=valid_elements, valid_elements both empty", op: "valid_elements", flagVal: "",
compareValue: "", expectedResultPattern: "'' contains valid elements from ''",
testResult: true},
{label: "op=valid_elements, valid_elements flagVal empty", op: "valid_elements", flagVal: "",
compareValue: "a,b", expectedResultPattern: "'' contains valid elements from 'a,b'",
testResult: false},
{label: "op=valid_elements, valid_elements expectedResultPattern empty", op: "valid_elements", flagVal: "a,b",
compareValue: "", expectedResultPattern: "'a,b' contains valid elements from ''",
testResult: false},
}
for _, c := range cases {
expectedResultPattern, testResult := compareOp(c.op, c.flagVal, c.compareValue)
if expectedResultPattern != c.expectedResultPattern {
t.Errorf("'expectedResultPattern' did not match - label: %q op: %q expected 'expectedResultPattern':%q got:%q\n", c.label, c.op, c.expectedResultPattern, expectedResultPattern)
}
if testResult != c.testResult {
t.Errorf("'testResult' did not match - label: %q op: %q expected 'testResult':%t got:%t\n", c.label, c.op, c.testResult, testResult)
}
}
}
func TestToNumeric(t *testing.T) {
cases := []struct {
firstValue string
secondValue string
expectedToFail bool
}{
{
firstValue: "a",
secondValue: "b",
expectedToFail: true,
},
{
firstValue: "5",
secondValue: "b",
expectedToFail: true,
},
{
firstValue: "5",
secondValue: "6",
expectedToFail: false,
},
}
for _, c := range cases {
f, s, err := toNumeric(c.firstValue, c.secondValue)
if c.expectedToFail && err == nil {
t.Errorf("TestToNumeric - Expected error while converting %s and %s", c.firstValue, c.secondValue)
}
if !c.expectedToFail && (f != 5 || s != 6) {
t.Errorf("TestToNumeric - Expected to return %d,%d , but instead got %d,%d", 5, 6, f, s)
}
}
}
|
[
"\"USER\""
] |
[] |
[
"USER"
] |
[]
|
["USER"]
|
go
| 1 | 0 | |
scan/scanner_test.go
|
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scan
import (
"fmt"
"go/ast"
goparser "go/parser"
"io/ioutil"
"log"
"os"
"regexp"
"sort"
"strings"
"testing"
"github.com/go-openapi/loads"
"github.com/go-openapi/spec"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/validate"
"github.com/stretchr/testify/assert"
"golang.org/x/tools/go/loader"
_ "github.com/go-swagger/scan-repo-boundary/makeplans"
)
var classificationProg *loader.Program
var noModelDefs map[string]spec.Schema
type namedParam struct {
Index int
Name string
}
type namedParams []namedParam
func (g namedParams) Len() int { return len(g) }
func (g namedParams) Swap(i, j int) { g[i], g[j] = g[j], g[i] }
func (g namedParams) Less(i, j int) bool { return g[i].Name < g[j].Name }
func init() {
classificationProg = classifierProgram()
docFile := "../fixtures/goparsing/classification/models/nomodel.go"
fileTree, err := goparser.ParseFile(classificationProg.Fset, docFile, nil, goparser.ParseComments)
if err != nil {
log.Fatal(err)
}
sp := newSchemaParser(classificationProg)
noModelDefs = make(map[string]spec.Schema)
err = sp.Parse(fileTree, noModelDefs)
if err != nil {
log.Fatal(err)
}
}
// only used within this group of tests but never used within actual code base.
func newSchemaAnnotationParser(goName string) *schemaAnnotationParser {
return &schemaAnnotationParser{GoName: goName, rx: rxModelOverride}
}
type schemaAnnotationParser struct {
GoName string
Name string
rx *regexp.Regexp
}
func (sap *schemaAnnotationParser) Matches(line string) bool {
return sap.rx.MatchString(line)
}
func (sap *schemaAnnotationParser) Parse(lines []string) error {
if sap.Name != "" {
return nil
}
if len(lines) > 0 {
for _, line := range lines {
matches := sap.rx.FindStringSubmatch(line)
if len(matches) > 1 && len(matches[1]) > 0 {
sap.Name = matches[1]
return nil
}
}
}
return nil
}
func extraModelsClassifier(t testing.TB) (*loader.Program, map[string]spec.Schema) {
prog := classifierProgram()
docFile := "../fixtures/goparsing/classification/models/extranomodel.go"
fileTree, err := goparser.ParseFile(prog.Fset, docFile, nil, goparser.ParseComments)
if err != nil {
t.Fatal(err)
}
sp := newSchemaParser(prog)
defs := make(map[string]spec.Schema)
err = sp.Parse(fileTree, defs)
if err != nil {
t.Fatal(err)
}
return prog, defs
}
func TestAppScanner_NewSpec(t *testing.T) {
scanner, err := newAppScanner(&Opts{BasePath: "../fixtures/goparsing/petstore/petstore-fixture"}, nil, nil)
assert.NoError(t, err)
assert.NotNil(t, scanner)
doc, err := scanner.Parse()
assert.NoError(t, err)
if assert.NotNil(t, doc) {
verifyParsedPetStore(t, doc)
}
}
func TestAppScanner_Definitions(t *testing.T) {
scanner, err := newAppScanner(&Opts{BasePath: "../fixtures/goparsing/bookings"}, nil, nil)
assert.NoError(t, err)
assert.NotNil(t, scanner)
doc, err := scanner.Parse()
assert.NoError(t, err)
if assert.NotNil(t, doc) {
_, ok := doc.Definitions["Booking"]
assert.True(t, ok, "Should include cross repo structs")
_, ok = doc.Definitions["Customer"]
assert.True(t, ok, "Should include package structs with swagger:model")
_, ok = doc.Definitions["DateRange"]
assert.True(t, ok, "Should include package structs that are used in responses")
_, ok = doc.Definitions["BookingResponse"]
assert.False(t, ok, "Should not include responses")
_, ok = doc.Definitions["IgnoreMe"]
assert.False(t, ok, "Should not include un-annotated/un-referenced structs")
}
}
func verifyParsedPetStore(t testing.TB, doc *spec.Swagger) {
assert.EqualValues(t, []string{"application/json"}, doc.Consumes)
assert.EqualValues(t, []string{"application/json"}, doc.Produces)
assert.EqualValues(t, []string{"http", "https"}, doc.Schemes)
assert.Equal(t, "localhost", doc.Host)
assert.Equal(t, "/v2", doc.BasePath)
verifyInfo(t, doc.Info)
if assert.NotNil(t, doc.Paths) {
assert.Len(t, doc.Paths.Paths, 4)
}
var keys []string
for k := range doc.Definitions {
keys = append(keys, k)
}
assert.Len(t, keys, 3)
assert.Len(t, doc.Responses, 3)
definitions := doc.Definitions
mod, ok := definitions["tag"]
assert.True(t, ok)
assert.Equal(t, spec.StringOrArray([]string{"object"}), mod.Type)
assert.Equal(t, "A Tag is an extra piece of data to provide more information about a pet.", mod.Title)
assert.Equal(t, "It is used to describe the animals available in the store.", mod.Description)
assert.Len(t, mod.Required, 2)
assertProperty(t, &mod, "integer", "id", "int64", "ID")
prop, ok := mod.Properties["id"]
assert.True(t, ok, "should have had an 'id' property")
assert.Equal(t, "The id of the tag.", prop.Description)
assertProperty(t, &mod, "string", "value", "", "Value")
prop, ok = mod.Properties["value"]
assert.True(t, ok)
assert.Equal(t, "The value of the tag.", prop.Description)
mod, ok = definitions["pet"]
assert.True(t, ok)
assert.Equal(t, spec.StringOrArray([]string{"object"}), mod.Type)
assert.Equal(t, "A Pet is the main product in the store.", mod.Title)
assert.Equal(t, "It is used to describe the animals available in the store.", mod.Description)
assert.Len(t, mod.Required, 2)
assertProperty(t, &mod, "integer", "id", "int64", "ID")
prop, ok = mod.Properties["id"]
assert.True(t, ok, "should have had an 'id' property")
assert.Equal(t, "The id of the pet.", prop.Description)
assertProperty(t, &mod, "string", "name", "", "Name")
prop, ok = mod.Properties["name"]
assert.True(t, ok)
assert.Equal(t, "The name of the pet.", prop.Description)
assert.EqualValues(t, 3, *prop.MinLength)
assert.EqualValues(t, 50, *prop.MaxLength)
assert.Equal(t, "\\w[\\w-]+", prop.Pattern)
assertArrayProperty(t, &mod, "string", "photoUrls", "", "PhotoURLs")
prop, ok = mod.Properties["photoUrls"]
assert.True(t, ok)
assert.Equal(t, "The photo urls for the pet.\nThis only accepts jpeg or png images.", prop.Description)
if assert.NotNil(t, prop.Items) && assert.NotNil(t, prop.Items.Schema) {
assert.Equal(t, "\\.(jpe?g|png)$", prop.Items.Schema.Pattern)
}
assertProperty(t, &mod, "string", "status", "", "Status")
prop, ok = mod.Properties["status"]
assert.True(t, ok)
assert.Equal(t, "The current status of the pet in the store.", prop.Description)
assertProperty(t, &mod, "string", "birthday", "date", "Birthday")
prop, ok = mod.Properties["birthday"]
assert.True(t, ok)
assert.Equal(t, "The pet's birthday", prop.Description)
assertArrayRef(t, &mod, "tags", "Tags", "#/definitions/tag")
prop, ok = mod.Properties["tags"]
assert.True(t, ok)
assert.Equal(t, "Extra bits of information attached to this pet.", prop.Description)
mod, ok = definitions["order"]
assert.True(t, ok)
assert.Len(t, mod.Properties, 4)
assert.Len(t, mod.Required, 3)
assertProperty(t, &mod, "integer", "id", "int64", "ID")
prop, ok = mod.Properties["id"]
assert.True(t, ok, "should have had an 'id' property")
assert.Equal(t, "the ID of the order", prop.Description)
assertProperty(t, &mod, "integer", "userId", "int64", "UserID")
prop, ok = mod.Properties["userId"]
assert.True(t, ok, "should have had an 'userId' property")
assert.Equal(t, "the id of the user who placed the order.", prop.Description)
assertProperty(t, &mod, "string", "orderedAt", "date-time", "OrderedAt")
prop, ok = mod.Properties["orderedAt"]
assert.Equal(t, "the time at which this order was made.", prop.Description)
assert.True(t, ok, "should have an 'orderedAt' property")
assertArrayProperty(t, &mod, "object", "items", "", "Items")
prop, ok = mod.Properties["items"]
assert.True(t, ok, "should have an 'items' slice")
assert.NotNil(t, prop.Items, "items should have had an items property")
assert.NotNil(t, prop.Items.Schema, "items.items should have had a schema property")
itprop := prop.Items.Schema
assert.Len(t, itprop.Properties, 2)
assert.Len(t, itprop.Required, 2)
assertProperty(t, itprop, "integer", "petId", "int64", "PetID")
iprop, ok := itprop.Properties["petId"]
assert.True(t, ok, "should have had a 'petId' property")
assert.Equal(t, "the id of the pet to order", iprop.Description)
assertProperty(t, itprop, "integer", "qty", "int32", "Quantity")
iprop, ok = itprop.Properties["qty"]
assert.True(t, ok, "should have had a 'qty' property")
assert.Equal(t, "the quantity of this pet to order", iprop.Description)
assert.EqualValues(t, 1, *iprop.Minimum)
// responses
resp, ok := doc.Responses["genericError"]
assert.True(t, ok)
assert.NotNil(t, resp.Schema)
assert.Len(t, resp.Schema.Properties, 2)
assertProperty(t, resp.Schema, "integer", "code", "int32", "Code")
assertProperty(t, resp.Schema, "string", "message", "", "Message")
resp, ok = doc.Responses["validationError"]
assert.True(t, ok)
assert.NotNil(t, resp.Schema)
assert.Len(t, resp.Schema.Properties, 3)
assertProperty(t, resp.Schema, "integer", "code", "int32", "Code")
assertProperty(t, resp.Schema, "string", "message", "", "Message")
assertProperty(t, resp.Schema, "string", "field", "", "Field")
paths := doc.Paths.Paths
// path /pets
op, ok := paths["/pets"]
assert.True(t, ok)
assert.NotNil(t, op)
// listPets
assert.NotNil(t, op.Get)
assert.Equal(t, "Lists the pets known to the store.", op.Get.Summary)
assert.Equal(t, "By default it will only lists pets that are available for sale.\nThis can be changed with the status flag.", op.Get.Description)
assert.Equal(t, "listPets", op.Get.ID)
assert.EqualValues(t, []string{"pets"}, op.Get.Tags)
var names namedParams
for i, v := range op.Get.Parameters {
names = append(names, namedParam{Index: i, Name: v.Name})
}
sort.Sort(names)
sparam := op.Get.Parameters[names[1].Index]
assert.Equal(t, "Status", sparam.Description)
assert.Equal(t, "query", sparam.In)
assert.Equal(t, "string", sparam.Type)
assert.Equal(t, "", sparam.Format)
assert.False(t, sparam.Required)
assert.Equal(t, "Status", sparam.Extensions["x-go-name"])
assert.Equal(t, "#/responses/genericError", op.Get.Responses.Default.Ref.String())
assert.Len(t, op.Get.Parameters, 2)
sparam1 := op.Get.Parameters[names[0].Index]
assert.Equal(t, "Birthday", sparam1.Description)
assert.Equal(t, "query", sparam1.In)
assert.Equal(t, "string", sparam1.Type)
assert.Equal(t, "date", sparam1.Format)
assert.False(t, sparam1.Required)
assert.Equal(t, "Birthday", sparam1.Extensions["x-go-name"])
rs, ok := op.Get.Responses.StatusCodeResponses[200]
assert.True(t, ok)
assert.NotNil(t, rs.Schema)
aprop := rs.Schema
assert.Equal(t, "array", aprop.Type[0])
assert.NotNil(t, aprop.Items)
assert.NotNil(t, aprop.Items.Schema)
assert.Equal(t, "#/definitions/pet", aprop.Items.Schema.Ref.String())
// createPet
assert.NotNil(t, op.Post)
assert.Equal(t, "Creates a new pet in the store.", op.Post.Summary)
assert.Equal(t, "", op.Post.Description)
assert.Equal(t, "createPet", op.Post.ID)
assert.EqualValues(t, []string{"pets"}, op.Post.Tags)
verifyRefParam(t, op.Post.Parameters[0], "The pet to submit.", "pet")
assert.Equal(t, "#/responses/genericError", op.Post.Responses.Default.Ref.String())
rs, ok = op.Post.Responses.StatusCodeResponses[200]
assert.True(t, ok)
assert.NotNil(t, rs.Schema)
aprop = rs.Schema
assert.Equal(t, "#/definitions/pet", aprop.Ref.String())
// path /pets/{id}
op, ok = paths["/pets/{id}"]
assert.True(t, ok)
assert.NotNil(t, op)
// getPetById
assert.NotNil(t, op.Get)
assert.Equal(t, "Gets the details for a pet.", op.Get.Summary)
assert.Equal(t, "", op.Get.Description)
assert.Equal(t, "getPetById", op.Get.ID)
assert.EqualValues(t, []string{"pets"}, op.Get.Tags)
verifyIDParam(t, op.Get.Parameters[0], "The ID of the pet")
assert.Equal(t, "#/responses/genericError", op.Get.Responses.Default.Ref.String())
rs, ok = op.Get.Responses.StatusCodeResponses[200]
assert.True(t, ok)
assert.NotNil(t, rs.Schema)
aprop = rs.Schema
assert.Equal(t, "#/definitions/pet", aprop.Ref.String())
// updatePet
assert.NotNil(t, op.Put)
assert.Equal(t, "Updates the details for a pet.", op.Put.Summary)
assert.Equal(t, "", op.Put.Description)
assert.Equal(t, "updatePet", op.Put.ID)
assert.EqualValues(t, []string{"pets"}, op.Put.Tags)
verifyIDParam(t, op.Put.Parameters[0], "The ID of the pet")
verifyRefParam(t, op.Put.Parameters[1], "The pet to submit.", "pet")
assert.Equal(t, "#/responses/genericError", op.Put.Responses.Default.Ref.String())
rs, ok = op.Put.Responses.StatusCodeResponses[200]
assert.True(t, ok)
assert.NotNil(t, rs.Schema)
aprop = rs.Schema
assert.Equal(t, "#/definitions/pet", aprop.Ref.String())
// deletePet
assert.NotNil(t, op.Delete)
assert.Equal(t, "Deletes a pet from the store.", op.Delete.Summary)
assert.Equal(t, "", op.Delete.Description)
assert.Equal(t, "deletePet", op.Delete.ID)
assert.EqualValues(t, []string{"pets"}, op.Delete.Tags)
verifyIDParam(t, op.Delete.Parameters[0], "The ID of the pet")
assert.Equal(t, "#/responses/genericError", op.Delete.Responses.Default.Ref.String())
_, ok = op.Delete.Responses.StatusCodeResponses[204]
assert.True(t, ok)
// path /orders/{id}
op, ok = paths["/orders/{id}"]
assert.True(t, ok)
assert.NotNil(t, op)
// getOrderDetails
assert.NotNil(t, op.Get)
assert.Equal(t, "Gets the details for an order.", op.Get.Summary)
assert.Equal(t, "", op.Get.Description)
assert.Equal(t, "getOrderDetails", op.Get.ID)
assert.EqualValues(t, []string{"orders"}, op.Get.Tags)
verifyIDParam(t, op.Get.Parameters[0], "The ID of the order")
assert.Equal(t, "#/responses/genericError", op.Get.Responses.Default.Ref.String())
rs, ok = op.Get.Responses.StatusCodeResponses[200]
assert.True(t, ok)
assert.Equal(t, "#/responses/orderResponse", rs.Ref.String())
rsm := doc.Responses["orderResponse"]
assert.NotNil(t, rsm.Schema)
assert.Equal(t, "#/definitions/order", rsm.Schema.Ref.String())
// cancelOrder
assert.NotNil(t, op.Delete)
assert.Equal(t, "Deletes an order.", op.Delete.Summary)
assert.Equal(t, "", op.Delete.Description)
assert.Equal(t, "cancelOrder", op.Delete.ID)
assert.EqualValues(t, []string{"orders"}, op.Delete.Tags)
verifyIDParam(t, op.Delete.Parameters[0], "The ID of the order")
assert.Equal(t, "#/responses/genericError", op.Delete.Responses.Default.Ref.String())
_, ok = op.Delete.Responses.StatusCodeResponses[204]
assert.True(t, ok)
// updateOrder
assert.NotNil(t, op.Put)
assert.Equal(t, "Updates an order.", op.Put.Summary)
assert.Equal(t, "", op.Put.Description)
assert.Equal(t, "updateOrder", op.Put.ID)
assert.EqualValues(t, []string{"orders"}, op.Put.Tags)
verifyIDParam(t, op.Put.Parameters[0], "The ID of the order")
verifyRefParam(t, op.Put.Parameters[1], "The order to submit", "order")
assert.Equal(t, "#/responses/genericError", op.Put.Responses.Default.Ref.String())
rs, ok = op.Put.Responses.StatusCodeResponses[200]
assert.True(t, ok)
assert.NotNil(t, rs.Schema)
aprop = rs.Schema
assert.Equal(t, "#/definitions/order", aprop.Ref.String())
// path /orders
op, ok = paths["/orders"]
assert.True(t, ok)
assert.NotNil(t, op)
// createOrder
assert.NotNil(t, op.Post)
assert.Equal(t, "Creates an order.", op.Post.Summary)
assert.Equal(t, "", op.Post.Description)
assert.Equal(t, "createOrder", op.Post.ID)
assert.EqualValues(t, []string{"orders"}, op.Post.Tags)
verifyRefParam(t, op.Post.Parameters[0], "The order to submit", "order")
assert.Equal(t, "#/responses/genericError", op.Post.Responses.Default.Ref.String())
rs, ok = op.Post.Responses.StatusCodeResponses[200]
assert.True(t, ok)
assert.Equal(t, "#/responses/orderResponse", rs.Ref.String())
rsm = doc.Responses["orderResponse"]
assert.NotNil(t, rsm.Schema)
assert.Equal(t, "#/definitions/order", rsm.Schema.Ref.String())
}
func verifyIDParam(t testing.TB, param spec.Parameter, description string) {
assert.Equal(t, description, param.Description)
assert.Equal(t, "path", param.In)
assert.Equal(t, "integer", param.Type)
assert.Equal(t, "int64", param.Format)
assert.True(t, param.Required)
assert.Equal(t, "ID", param.Extensions["x-go-name"])
}
func verifyRefParam(t testing.TB, param spec.Parameter, description, refed string) {
assert.Equal(t, description, param.Description)
assert.Equal(t, "body", param.In)
assert.Equal(t, "#/definitions/"+refed, param.Schema.Ref.String())
assert.True(t, param.Required)
}
func TestSectionedParser_TitleDescription(t *testing.T) {
text := `This has a title, separated by a whitespace line
In this example the punctuation for the title should not matter for swagger.
For go it will still make a difference though.
`
text2 := `This has a title without whitespace.
The punctuation here does indeed matter. But it won't for go.
`
text3 := `This has a title, and markdown in the description
See how markdown works now, we can have lists:
+ first item
+ second item
+ third item
[Links works too](http://localhost)
`
text4 := `This has whitespace sensitive markdown in the description
|+ first item
| + nested item
| + also nested item
Sample code block:
| fmt.Println("Hello World!")
`
var err error
st := §ionedParser{}
st.setTitle = func(lines []string) {}
err = st.Parse(ascg(text))
assert.NoError(t, err)
assert.EqualValues(t, []string{"This has a title, separated by a whitespace line"}, st.Title())
assert.EqualValues(t, []string{"In this example the punctuation for the title should not matter for swagger.", "For go it will still make a difference though."}, st.Description())
st = §ionedParser{}
st.setTitle = func(lines []string) {}
err = st.Parse(ascg(text2))
assert.NoError(t, err)
assert.EqualValues(t, []string{"This has a title without whitespace."}, st.Title())
assert.EqualValues(t, []string{"The punctuation here does indeed matter. But it won't for go."}, st.Description())
st = §ionedParser{}
st.setTitle = func(lines []string) {}
err = st.Parse(ascg(text3))
assert.NoError(t, err)
assert.EqualValues(t, []string{"This has a title, and markdown in the description"}, st.Title())
assert.EqualValues(t, []string{"See how markdown works now, we can have lists:", "", "+ first item", "+ second item", "+ third item", "", "[Links works too](http://localhost)"}, st.Description())
st = §ionedParser{}
st.setTitle = func(lines []string) {}
err = st.Parse(ascg(text4))
assert.NoError(t, err)
assert.EqualValues(t, []string{"This has whitespace sensitive markdown in the description"}, st.Title())
assert.EqualValues(t, []string{"+ first item", " + nested item", " + also nested item", "", "Sample code block:", "", " fmt.Println(\"Hello World!\")"}, st.Description())
}
func dummyBuilder() schemaValidations {
return schemaValidations{new(spec.Schema)}
}
func TestSectionedParser_TagsDescription(t *testing.T) {
block := `This has a title without whitespace.
The punctuation here does indeed matter. But it won't for go.
minimum: 10
maximum: 20
`
block2 := `This has a title without whitespace.
The punctuation here does indeed matter. But it won't for go.
minimum: 10
maximum: 20
`
var err error
st := §ionedParser{}
st.setTitle = func(lines []string) {}
st.taggers = []tagParser{
{"Maximum", false, false, nil, &setMaximum{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMaximumFmt, ""))}},
{"Minimum", false, false, nil, &setMinimum{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMinimumFmt, ""))}},
{"MultipleOf", false, false, nil, &setMultipleOf{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMultipleOfFmt, ""))}},
}
err = st.Parse(ascg(block))
assert.NoError(t, err)
assert.EqualValues(t, []string{"This has a title without whitespace."}, st.Title())
assert.EqualValues(t, []string{"The punctuation here does indeed matter. But it won't for go."}, st.Description())
assert.Len(t, st.matched, 2)
_, ok := st.matched["Maximum"]
assert.True(t, ok)
_, ok = st.matched["Minimum"]
assert.True(t, ok)
st = §ionedParser{}
st.setTitle = func(lines []string) {}
st.taggers = []tagParser{
{"Maximum", false, false, nil, &setMaximum{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMaximumFmt, ""))}},
{"Minimum", false, false, nil, &setMinimum{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMinimumFmt, ""))}},
{"MultipleOf", false, false, nil, &setMultipleOf{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMultipleOfFmt, ""))}},
}
err = st.Parse(ascg(block2))
assert.NoError(t, err)
assert.EqualValues(t, []string{"This has a title without whitespace."}, st.Title())
assert.EqualValues(t, []string{"The punctuation here does indeed matter. But it won't for go."}, st.Description())
assert.Len(t, st.matched, 2)
_, ok = st.matched["Maximum"]
assert.True(t, ok)
_, ok = st.matched["Minimum"]
assert.True(t, ok)
}
func TestSectionedParser_Empty(t *testing.T) {
block := `swagger:response someResponse`
var err error
st := §ionedParser{}
st.setTitle = func(lines []string) {}
ap := newSchemaAnnotationParser("SomeResponse")
ap.rx = rxResponseOverride
st.annotation = ap
err = st.Parse(ascg(block))
assert.NoError(t, err)
assert.Empty(t, st.Title())
assert.Empty(t, st.Description())
assert.Empty(t, st.taggers)
assert.Equal(t, "SomeResponse", ap.GoName)
assert.Equal(t, "someResponse", ap.Name)
}
func TestSectionedParser_SkipSectionAnnotation(t *testing.T) {
block := `swagger:model someModel
This has a title without whitespace.
The punctuation here does indeed matter. But it won't for go.
minimum: 10
maximum: 20
`
var err error
st := §ionedParser{}
st.setTitle = func(lines []string) {}
ap := newSchemaAnnotationParser("SomeModel")
st.annotation = ap
st.taggers = []tagParser{
{"Maximum", false, false, nil, &setMaximum{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMaximumFmt, ""))}},
{"Minimum", false, false, nil, &setMinimum{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMinimumFmt, ""))}},
{"MultipleOf", false, false, nil, &setMultipleOf{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMultipleOfFmt, ""))}},
}
err = st.Parse(ascg(block))
assert.NoError(t, err)
assert.EqualValues(t, []string{"This has a title without whitespace."}, st.Title())
assert.EqualValues(t, []string{"The punctuation here does indeed matter. But it won't for go."}, st.Description())
assert.Len(t, st.matched, 2)
_, ok := st.matched["Maximum"]
assert.True(t, ok)
_, ok = st.matched["Minimum"]
assert.True(t, ok)
assert.Equal(t, "SomeModel", ap.GoName)
assert.Equal(t, "someModel", ap.Name)
}
func TestSectionedParser_TerminateOnNewAnnotation(t *testing.T) {
block := `swagger:model someModel
This has a title without whitespace.
The punctuation here does indeed matter. But it won't for go.
minimum: 10
swagger:meta
maximum: 20
`
var err error
st := §ionedParser{}
st.setTitle = func(lines []string) {}
ap := newSchemaAnnotationParser("SomeModel")
st.annotation = ap
st.taggers = []tagParser{
{"Maximum", false, false, nil, &setMaximum{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMaximumFmt, ""))}},
{"Minimum", false, false, nil, &setMinimum{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMinimumFmt, ""))}},
{"MultipleOf", false, false, nil, &setMultipleOf{dummyBuilder(), regexp.MustCompile(fmt.Sprintf(rxMultipleOfFmt, ""))}},
}
err = st.Parse(ascg(block))
assert.NoError(t, err)
assert.EqualValues(t, []string{"This has a title without whitespace."}, st.Title())
assert.EqualValues(t, []string{"The punctuation here does indeed matter. But it won't for go."}, st.Description())
assert.Len(t, st.matched, 1)
_, ok := st.matched["Maximum"]
assert.False(t, ok)
_, ok = st.matched["Minimum"]
assert.True(t, ok)
assert.Equal(t, "SomeModel", ap.GoName)
assert.Equal(t, "someModel", ap.Name)
}
func ascg(txt string) *ast.CommentGroup {
var cg ast.CommentGroup
for _, line := range strings.Split(txt, "\n") {
var cmt ast.Comment
cmt.Text = "// " + line
cg.List = append(cg.List, &cmt)
}
return &cg
}
func TestSchemaValueExtractors(t *testing.T) {
strfmts := []string{
"// swagger:strfmt ",
"* swagger:strfmt ",
"* swagger:strfmt ",
" swagger:strfmt ",
"swagger:strfmt ",
"// swagger:strfmt ",
"* swagger:strfmt ",
"* swagger:strfmt ",
" swagger:strfmt ",
"swagger:strfmt ",
}
models := []string{
"// swagger:model ",
"* swagger:model ",
"* swagger:model ",
" swagger:model ",
"swagger:model ",
"// swagger:model ",
"* swagger:model ",
"* swagger:model ",
" swagger:model ",
"swagger:model ",
}
allOf := []string{
"// swagger:allOf ",
"* swagger:allOf ",
"* swagger:allOf ",
" swagger:allOf ",
"swagger:allOf ",
"// swagger:allOf ",
"* swagger:allOf ",
"* swagger:allOf ",
" swagger:allOf ",
"swagger:allOf ",
}
parameters := []string{
"// swagger:parameters ",
"* swagger:parameters ",
"* swagger:parameters ",
" swagger:parameters ",
"swagger:parameters ",
"// swagger:parameters ",
"* swagger:parameters ",
"* swagger:parameters ",
" swagger:parameters ",
"swagger:parameters ",
}
validParams := []string{
"yada123",
"date",
"date-time",
"long-combo-1-with-combo-2-and-a-3rd-one-too",
}
invalidParams := []string{
"1-yada-3",
"1-2-3",
"-yada-3",
"-2-3",
"*blah",
"blah*",
}
verifySwaggerOneArgSwaggerTag(t, rxStrFmt, strfmts, validParams, append(invalidParams, "", " ", " "))
verifySwaggerOneArgSwaggerTag(t, rxModelOverride, models, append(validParams, "", " ", " "), invalidParams)
verifySwaggerOneArgSwaggerTag(t, rxAllOf, allOf, append(validParams, "", " ", " "), invalidParams)
verifySwaggerMultiArgSwaggerTag(t, rxParametersOverride, parameters, validParams, invalidParams)
verifyMinMax(t, rxf(rxMinimumFmt, ""), "min", []string{"", ">", "="})
verifyMinMax(t, rxf(rxMinimumFmt, fmt.Sprintf(rxItemsPrefixFmt, 1)), "items.min", []string{"", ">", "="})
verifyMinMax(t, rxf(rxMaximumFmt, ""), "max", []string{"", "<", "="})
verifyMinMax(t, rxf(rxMaximumFmt, fmt.Sprintf(rxItemsPrefixFmt, 1)), "items.max", []string{"", "<", "="})
verifyNumeric2Words(t, rxf(rxMultipleOfFmt, ""), "multiple", "of")
verifyNumeric2Words(t, rxf(rxMultipleOfFmt, fmt.Sprintf(rxItemsPrefixFmt, 1)), "items.multiple", "of")
verifyIntegerMinMaxManyWords(t, rxf(rxMinLengthFmt, ""), "min", []string{"len", "length"})
// pattern
extraSpaces := []string{"", " ", " ", " "}
prefixes := []string{"//", "*", ""}
patArgs := []string{"^\\w+$", "[A-Za-z0-9-.]*"}
patNames := []string{"pattern", "Pattern"}
for _, pref := range prefixes {
for _, es1 := range extraSpaces {
for _, nm := range patNames {
for _, es2 := range extraSpaces {
for _, es3 := range extraSpaces {
for _, arg := range patArgs {
line := strings.Join([]string{pref, es1, nm, es2, ":", es3, arg}, "")
matches := rxf(rxPatternFmt, "").FindStringSubmatch(line)
assert.Len(t, matches, 2)
assert.Equal(t, arg, matches[1])
}
}
}
}
}
}
verifyIntegerMinMaxManyWords(t, rxf(rxMinItemsFmt, ""), "min", []string{"items"})
verifyBoolean(t, rxf(rxUniqueFmt, ""), []string{"unique"}, nil)
verifyBoolean(t, rxReadOnly, []string{"read"}, []string{"only"})
verifyBoolean(t, rxRequired, []string{"required"}, nil)
}
func makeMinMax(lower string) (res []string) {
for _, a := range []string{"", "imum"} {
res = append(res, lower+a, strings.Title(lower)+a)
}
return
}
func verifyBoolean(t *testing.T, matcher *regexp.Regexp, names, names2 []string) {
extraSpaces := []string{"", " ", " ", " "}
prefixes := []string{"//", "*", ""}
validArgs := []string{"true", "false"}
invalidArgs := []string{"TRUE", "FALSE", "t", "f", "1", "0", "True", "False", "true*", "false*"}
var nms []string
for _, nm := range names {
nms = append(nms, nm, strings.Title(nm))
}
var nms2 []string
for _, nm := range names2 {
nms2 = append(nms2, nm, strings.Title(nm))
}
var rnms []string
if len(nms2) > 0 {
for _, nm := range nms {
for _, es := range append(extraSpaces, "-") {
for _, nm2 := range nms2 {
rnms = append(rnms, strings.Join([]string{nm, es, nm2}, ""))
}
}
}
} else {
rnms = nms
}
var cnt int
for _, pref := range prefixes {
for _, es1 := range extraSpaces {
for _, nm := range rnms {
for _, es2 := range extraSpaces {
for _, es3 := range extraSpaces {
for _, vv := range validArgs {
line := strings.Join([]string{pref, es1, nm, es2, ":", es3, vv}, "")
matches := matcher.FindStringSubmatch(line)
assert.Len(t, matches, 2)
assert.Equal(t, vv, matches[1])
cnt++
}
for _, iv := range invalidArgs {
line := strings.Join([]string{pref, es1, nm, es2, ":", es3, iv}, "")
matches := matcher.FindStringSubmatch(line)
assert.Empty(t, matches)
cnt++
}
}
}
}
}
}
var nm2 string
if len(names2) > 0 {
nm2 = " " + names2[0]
}
var Debug = os.Getenv("DEBUG") != "" || os.Getenv("SWAGGER_DEBUG") != ""
if Debug {
fmt.Printf("tested %d %s%s combinations\n", cnt, names[0], nm2)
}
}
func verifyIntegerMinMaxManyWords(t *testing.T, matcher *regexp.Regexp, name1 string, words []string) {
extraSpaces := []string{"", " ", " ", " "}
prefixes := []string{"//", "*", ""}
validNumericArgs := []string{"0", "1234"}
invalidNumericArgs := []string{"1A3F", "2e10", "*12", "12*", "-1235", "0.0", "1234.0394", "-2948.484"}
var names []string
for _, w := range words {
names = append(names, w, strings.Title(w))
}
var cnt int
for _, pref := range prefixes {
for _, es1 := range extraSpaces {
for _, nm1 := range makeMinMax(name1) {
for _, es2 := range append(extraSpaces, "-") {
for _, nm2 := range names {
for _, es3 := range extraSpaces {
for _, es4 := range extraSpaces {
for _, vv := range validNumericArgs {
line := strings.Join([]string{pref, es1, nm1, es2, nm2, es3, ":", es4, vv}, "")
matches := matcher.FindStringSubmatch(line)
//fmt.Printf("matching %q, matches (%d): %v\n", line, len(matches), matches)
assert.Len(t, matches, 2)
assert.Equal(t, vv, matches[1])
cnt++
}
for _, iv := range invalidNumericArgs {
line := strings.Join([]string{pref, es1, nm1, es2, nm2, es3, ":", es4, iv}, "")
matches := matcher.FindStringSubmatch(line)
assert.Empty(t, matches)
cnt++
}
}
}
}
}
}
}
}
var nm2 string
if len(words) > 0 {
nm2 = " " + words[0]
}
var Debug = os.Getenv("DEBUG") != "" || os.Getenv("SWAGGER_DEBUG") != ""
if Debug {
fmt.Printf("tested %d %s%s combinations\n", cnt, name1, nm2)
}
}
func verifyNumeric2Words(t *testing.T, matcher *regexp.Regexp, name1, name2 string) {
extraSpaces := []string{"", " ", " ", " "}
prefixes := []string{"//", "*", ""}
validNumericArgs := []string{"0", "1234", "-1235", "0.0", "1234.0394", "-2948.484"}
invalidNumericArgs := []string{"1A3F", "2e10", "*12", "12*"}
var cnt int
for _, pref := range prefixes {
for _, es1 := range extraSpaces {
for _, es2 := range extraSpaces {
for _, es3 := range extraSpaces {
for _, es4 := range extraSpaces {
for _, vv := range validNumericArgs {
lines := []string{
strings.Join([]string{pref, es1, name1, es2, name2, es3, ":", es4, vv}, ""),
strings.Join([]string{pref, es1, strings.Title(name1), es2, strings.Title(name2), es3, ":", es4, vv}, ""),
strings.Join([]string{pref, es1, strings.Title(name1), es2, name2, es3, ":", es4, vv}, ""),
strings.Join([]string{pref, es1, name1, es2, strings.Title(name2), es3, ":", es4, vv}, ""),
}
for _, line := range lines {
matches := matcher.FindStringSubmatch(line)
//fmt.Printf("matching %q, matches (%d): %v\n", line, len(matches), matches)
assert.Len(t, matches, 2)
assert.Equal(t, vv, matches[1])
cnt++
}
}
for _, iv := range invalidNumericArgs {
lines := []string{
strings.Join([]string{pref, es1, name1, es2, name2, es3, ":", es4, iv}, ""),
strings.Join([]string{pref, es1, strings.Title(name1), es2, strings.Title(name2), es3, ":", es4, iv}, ""),
strings.Join([]string{pref, es1, strings.Title(name1), es2, name2, es3, ":", es4, iv}, ""),
strings.Join([]string{pref, es1, name1, es2, strings.Title(name2), es3, ":", es4, iv}, ""),
}
for _, line := range lines {
matches := matcher.FindStringSubmatch(line)
//fmt.Printf("matching %q, matches (%d): %v\n", line, len(matches), matches)
assert.Empty(t, matches)
cnt++
}
}
}
}
}
}
}
var Debug = os.Getenv("DEBUG") != "" || os.Getenv("SWAGGER_DEBUG") != ""
if Debug {
fmt.Printf("tested %d %s %s combinations\n", cnt, name1, name2)
}
}
func verifyMinMax(t *testing.T, matcher *regexp.Regexp, name string, operators []string) {
extraSpaces := []string{"", " ", " ", " "}
prefixes := []string{"//", "*", ""}
validNumericArgs := []string{"0", "1234", "-1235", "0.0", "1234.0394", "-2948.484"}
invalidNumericArgs := []string{"1A3F", "2e10", "*12", "12*"}
var cnt int
for _, pref := range prefixes {
for _, es1 := range extraSpaces {
for _, wrd := range makeMinMax(name) {
for _, es2 := range extraSpaces {
for _, es3 := range extraSpaces {
for _, op := range operators {
for _, es4 := range extraSpaces {
for _, vv := range validNumericArgs {
line := strings.Join([]string{pref, es1, wrd, es2, ":", es3, op, es4, vv}, "")
matches := matcher.FindStringSubmatch(line)
// fmt.Printf("matching %q with %q, matches (%d): %v\n", line, matcher, len(matches), matches)
assert.Len(t, matches, 3)
assert.Equal(t, vv, matches[2])
cnt++
}
for _, iv := range invalidNumericArgs {
line := strings.Join([]string{pref, es1, wrd, es2, ":", es3, op, es4, iv}, "")
matches := matcher.FindStringSubmatch(line)
assert.Empty(t, matches)
cnt++
}
}
}
}
}
}
}
}
var Debug = os.Getenv("DEBUG") != "" || os.Getenv("SWAGGER_DEBUG") != ""
if Debug {
fmt.Printf("tested %d %s combinations\n", cnt, name)
}
}
func verifySwaggerOneArgSwaggerTag(t *testing.T, matcher *regexp.Regexp, prefixes, validParams, invalidParams []string) {
for _, pref := range prefixes {
for _, param := range validParams {
line := pref + param
matches := matcher.FindStringSubmatch(line)
if assert.Len(t, matches, 2) {
assert.Equal(t, strings.TrimSpace(param), matches[1])
}
}
}
for _, pref := range prefixes {
for _, param := range invalidParams {
line := pref + param
matches := matcher.FindStringSubmatch(line)
assert.Empty(t, matches)
}
}
}
func verifySwaggerMultiArgSwaggerTag(t *testing.T, matcher *regexp.Regexp, prefixes, validParams, invalidParams []string) {
var actualParams []string
for i := 0; i < len(validParams); i++ {
var vp []string
for j := 0; j < (i + 1); j++ {
vp = append(vp, validParams[j])
}
actualParams = append(actualParams, strings.Join(vp, " "))
}
for _, pref := range prefixes {
for _, param := range actualParams {
line := pref + param
matches := matcher.FindStringSubmatch(line)
// fmt.Printf("matching %q with %q, matches (%d): %v\n", line, matcher, len(matches), matches)
assert.Len(t, matches, 2)
assert.Equal(t, strings.TrimSpace(param), matches[1])
}
}
for _, pref := range prefixes {
for _, param := range invalidParams {
line := pref + param
matches := matcher.FindStringSubmatch(line)
assert.Empty(t, matches)
}
}
}
func TestEnhancement793(t *testing.T) {
scanner, err := newAppScanner(&Opts{
BasePath: "../fixtures/enhancements/793",
ScanModels: true,
}, nil, nil)
assert.NoError(t, err)
assert.NotNil(t, scanner)
doc, err := scanner.Parse()
assert.NoError(t, err)
if assert.NotNil(t, doc) {
bytes, err := doc.MarshalJSON()
assert.NoError(t, err)
assert.NotEmpty(t, bytes)
file, err := ioutil.TempFile(os.TempDir(), "scanner")
file.Write(bytes)
file.Close()
doc, err := loads.Spec(file.Name())
if assert.NoError(t, err) {
validator := validate.NewSpecValidator(doc.Schema(), strfmt.Default)
res, _ := validator.Validate(doc)
assert.Empty(t, res.Errors)
assert.True(t, res.IsValid())
}
}
}
|
[
"\"DEBUG\"",
"\"SWAGGER_DEBUG\"",
"\"DEBUG\"",
"\"SWAGGER_DEBUG\"",
"\"DEBUG\"",
"\"SWAGGER_DEBUG\"",
"\"DEBUG\"",
"\"SWAGGER_DEBUG\""
] |
[] |
[
"SWAGGER_DEBUG",
"DEBUG"
] |
[]
|
["SWAGGER_DEBUG", "DEBUG"]
|
go
| 2 | 0 | |
main.go
|
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/damejeras/cryptbin/api"
"github.com/damejeras/cryptbin/internal/bin"
"github.com/pacedotdev/oto/otohttp"
)
var (
rootDir string
)
func main() {
flag.StringVar(&rootDir, "root", "frontend/public", "set SPA files root dir")
flag.Parse()
apiServer := otohttp.NewServer()
apiServer.Basepath = "/api/"
repository := bin.NewInMemoryRepository()
binService := bin.NewService(repository)
api.RegisterBinService(apiServer, binService)
spa := spaHandler{staticPath: rootDir, indexPath: "index.html"}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/") {
apiServer.ServeHTTP(w, r)
return
}
spa.ServeHTTP(w, r)
})
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", os.Getenv("PORT")), nil))
}
// spaHandler implements the http.Handler interface, so we can use it
// to respond to HTTP requests. The path to the static directory and
// path to the index file within that static directory are used to
// serve the SPA in the given static directory.
type spaHandler struct {
staticPath string
indexPath string
}
// ServeHTTP inspects the URL path to locate a file within the static dir
// on the SPA handler. If a file is found, it will be served. If not, the
// file located at the index path on the SPA handler will be served. This
// is suitable behavior for serving an SPA (single page application).
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// get the absolute path to prevent directory traversal
path, err := filepath.Abs(r.URL.Path)
if err != nil {
// if we failed to get the absolute path respond with a 400 bad request
// and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// prepend the path with the path to the static directory
path = filepath.Join(h.staticPath, path)
// check whether a file exists at the given path
_, err = os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
return
} else if err != nil {
// if we got an error (that wasn't that the file doesn't exist) stating the
// file, return a 500 internal server error and stop
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// otherwise, use http.FileServer to serve the static dir
http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}
|
[
"\"PORT\""
] |
[] |
[
"PORT"
] |
[]
|
["PORT"]
|
go
| 1 | 0 | |
passbook/root/wsgi.py
|
"""
WSGI config for passbook 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 time import time
from defusedxml import defuse_stdlib
from django.core.wsgi import get_wsgi_application
from structlog import get_logger
from passbook.lib.utils.http import _get_client_ip_from_meta
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "passbook.root.settings")
defuse_stdlib()
class WSGILogger:
""" This is the generalized WSGI middleware for any style request logging. """
def __init__(self, application):
self.application = application
self.logger = get_logger("passbook.wsgi")
def __healthcheck(self, start_response):
start_response("204 OK", [])
return [b""]
def __call__(self, environ, start_response):
start = time()
status_codes = []
content_lengths = []
if environ.get("HTTP_HOST", "").startswith("kubernetes-healthcheck-host"):
# Don't log kubernetes health/readiness requests
return self.__healthcheck(start_response)
def custom_start_response(status, response_headers, exc_info=None):
status_codes.append(int(status.partition(" ")[0]))
for name, value in response_headers:
if name.lower() == "content-length":
content_lengths.append(int(value))
break
return start_response(status, response_headers, exc_info)
retval = self.application(environ, custom_start_response)
runtime = int((time() - start) * 10 ** 6)
content_length = content_lengths[0] if content_lengths else 0
self.log(status_codes[0], environ, content_length, runtime=runtime)
return retval
def log(self, status_code, environ, content_length, **kwargs):
"""
Apache log format 'NCSA extended/combined log':
"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
see http://httpd.apache.org/docs/current/mod/mod_log_config.html#formats
"""
host = _get_client_ip_from_meta(environ)
query_string = ""
if environ.get("QUERY_STRING") != "":
query_string = f"?{environ.get('QUERY_STRING')}"
self.logger.info(
"request",
path=f"{environ.get('PATH_INFO', '')}{query_string}",
host=host,
method=environ.get("REQUEST_METHOD", ""),
protocol=environ.get("SERVER_PROTOCOL", ""),
status=status_code,
size=content_length / 1000 if content_length > 0 else "-",
runtime=kwargs.get("runtime"),
)
application = WSGILogger(get_wsgi_application())
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
pkgs/jupyter_core-4.1.0-py27_0/lib/python2.7/site-packages/jupyter_core/tests/test_migrate.py
|
"""Test config file migration"""
# coding: utf-8
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import re
import shutil
from subprocess import check_call
from tempfile import mkdtemp
try:
from unittest.mock import patch
except ImportError:
from mock import patch
import pytest
from ipython_genutils.path import ensure_dir_exists
try:
from IPython.paths import locate_profile
except ImportError:
from IPython.utils.path import locate_profile
from jupyter_core.paths import jupyter_data_dir
from jupyter_core.migrate import (
migrate, migrate_one, migrate_config,
migrate_dir, migrate_file, migrate_static_custom,
)
from jupyter_core import migrate as migrate_mod
pjoin = os.path.join
here = os.path.dirname(__file__)
dotipython = pjoin(here, 'dotipython')
dotipython_empty = pjoin(here, 'dotipython_empty')
@pytest.fixture
def td(request):
"""Fixture for a temporary directory"""
td = mkdtemp(u'μnïcø∂e')
request.addfinalizer(lambda : shutil.rmtree(td))
return td
@pytest.fixture
def env(request):
"""Fixture for a full testing environment"""
td = mkdtemp()
env = {
'TESTDIR': td,
'IPYTHONDIR': pjoin(td, 'ipython'),
'JUPYTER_CONFIG_DIR': pjoin(td, 'jupyter'),
'JUPYTER_DATA_DIR': pjoin(td, 'jupyter_data'),
'JUPYTER_RUNTIME_DIR': pjoin(td, 'jupyter_runtime'),
'JUPYTER_PATH': '',
}
env_patch = patch.dict(os.environ, env)
env_patch.start()
def fin():
"""Cleanup test env"""
env_patch.stop()
shutil.rmtree(td)
request.addfinalizer(fin)
return env
def touch(path, content=''):
ensure_dir_exists(os.path.dirname(path))
with open(path, 'w') as f:
f.write(content)
def assert_files_equal(a, b):
"""Verify that two files match"""
assert os.path.exists(b)
with open(a) as f:
a_txt = f.read()
with open(b) as f:
b_txt = f.read()
assert a_txt == b_txt
def test_migrate_file(td):
src = pjoin(td, 'src')
dst = pjoin(td, 'dst')
touch(src, 'test file')
assert migrate_file(src, dst)
assert_files_equal(src, dst)
src2 = pjoin(td, 'src2')
touch(src2, 'different src')
assert not migrate_file(src2, dst)
assert_files_equal(src, dst)
def test_migrate_dir(td):
src = pjoin(td, 'src')
dst = pjoin(td, 'dst')
os.mkdir(src)
assert not migrate_dir(src, dst)
assert not os.path.exists(dst)
touch(pjoin(src, 'f'), 'test file')
assert migrate_dir(src, dst)
assert_files_equal(pjoin(src, 'f'), pjoin(dst, 'f'))
touch(pjoin(src, 'g'), 'other test file')
assert not migrate_dir(src, dst)
assert not os.path.exists(pjoin(dst, 'g'))
shutil.rmtree(dst)
os.mkdir(dst)
assert migrate_dir(src, dst)
assert_files_equal(pjoin(src, 'f'), pjoin(dst, 'f'))
assert_files_equal(pjoin(src, 'g'), pjoin(dst, 'g'))
def test_migrate_one(td):
src = pjoin(td, 'src')
srcdir = pjoin(td, 'srcdir')
dst = pjoin(td, 'dst')
dstdir = pjoin(td, 'dstdir')
touch(src, 'test file')
touch(pjoin(srcdir, 'f'), 'test dir file')
called = {}
def notice_m_file(src, dst):
called['migrate_file'] = True
return migrate_file(src, dst)
def notice_m_dir(src, dst):
called['migrate_dir'] = True
return migrate_dir(src, dst)
with patch.object(migrate_mod, 'migrate_file', notice_m_file), \
patch.object(migrate_mod, 'migrate_dir', notice_m_dir):
assert migrate_one(src, dst)
assert called == {'migrate_file': True}
called.clear()
assert migrate_one(srcdir, dstdir)
assert called == {'migrate_dir': True}
called.clear()
assert not migrate_one(pjoin(td, 'dne'), dst)
assert called == {}
def test_migrate_config(td):
profile = pjoin(td, 'profile')
jpy = pjoin(td, 'jupyter_config')
ensure_dir_exists(profile)
env = {
'profile': profile,
'jupyter_config': jpy,
}
cfg_py = pjoin(profile, 'ipython_test_config.py')
touch(cfg_py, 'c.Klass.trait = 5\n')
empty_cfg_py = pjoin(profile, 'ipython_empty_config.py')
touch(empty_cfg_py, '# c.Klass.trait = 5\n')
assert not migrate_config('empty', env)
assert not os.path.exists(jpy)
with patch.dict(migrate_mod.config_substitutions, {
re.compile(r'\bKlass\b'): 'Replaced',
}):
assert migrate_config('test', env)
assert os.path.isdir(jpy)
assert sorted(os.listdir(jpy)) == [
'jupyter_test_config.py',
]
with open(pjoin(jpy, 'jupyter_test_config.py')) as f:
text = f.read()
assert text == 'c.Replaced.trait = 5\n'
def test_migrate_custom_default(td):
profile = pjoin(dotipython, 'profile_default')
src = pjoin(profile, 'static', 'custom')
assert os.path.exists(src)
assert not migrate_static_custom(src, td)
src = pjoin(td, 'src')
dst = pjoin(td, 'dst')
os.mkdir(src)
src_custom_js = pjoin(src, 'custom.js')
src_custom_css = pjoin(src, 'custom.css')
touch(src_custom_js, 'var a=5;')
touch(src_custom_css, 'div { height: 5px; }')
assert migrate_static_custom(src, dst)
def test_migrate_nothing(env):
migrate()
assert os.listdir(env['JUPYTER_CONFIG_DIR']) == ['migrated']
assert not os.path.exists(env['JUPYTER_DATA_DIR'])
def test_migrate_default(env):
shutil.copytree(dotipython_empty, env['IPYTHONDIR'])
migrate()
assert os.listdir(env['JUPYTER_CONFIG_DIR']) == ['migrated']
assert not os.path.exists(env['JUPYTER_DATA_DIR'])
def test_migrate(env):
shutil.copytree(dotipython, env['IPYTHONDIR'])
migrate()
assert os.path.exists(env['JUPYTER_CONFIG_DIR'])
assert os.path.exists(env['JUPYTER_DATA_DIR'])
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
org/companyname/cryptocoinsinfobot/cryptocoinsinfobot.py
|
import telebot
import os
import requests
from flask import Flask, request
from org.companyname.cryptocoinsinfobot.requestAPI import requestAPI
# set up config variables en your heroku environment
# your bot TOKEN
token = os.environ.get('TOKEN')
# your heroku app URL and add path "bot" for active update
appURL = os.environ.get('APPURL') + '/bot'
yourAlias = os.environ.get('YOURALIAS')
# end of read config variables
bot = telebot.TeleBot(token)
server = Flask(__name__)
# create userkeyboard, resize = true, autohide=false
user_markup = telebot.types.ReplyKeyboardMarkup(True, False)
user_markup.row("Bitcoin", "Ethereum")
user_markup.row("BitConnect", "BitcoinCash")
user_markup.row("Ripple", "➡ 2")
user_markup2 = telebot.types.ReplyKeyboardMarkup(True, False)
user_markup2.row("Litecoin", "Cardano")
user_markup2.row("IOTA", "Dash")
user_markup2.row("1 ⬅", "➡ 3")
user_markup3 = telebot.types.ReplyKeyboardMarkup(True, False)
user_markup3.row("NEM", "Monero")
user_markup3.row("NEO", "feedback")
user_markup3.row("2 ⬅", "settings")
# send a start message
@bot.message_handler(func=lambda message: message.text == 'start')
def start(message):
bot.send_message(message.from_user.id, 'Hello, ' + message.from_user.first_name
+ '. I am your Crypto Coins Info Bot! Use a keyboard for receive info about a price of a crypto coin.',
reply_markup=user_markup)
# more coins list
@bot.message_handler(func=lambda message: message.text == '➡ 3')
def other_coins(message):
bot.send_message(message.from_user.id, 'page 3', reply_markup=user_markup3)
# more coins list
@bot.message_handler(func=lambda message: message.text == '➡ 2' or message.text == '2 ⬅')
def other_coins(message):
bot.send_message(message.from_user.id, 'page 2', reply_markup=user_markup2)
# main coins list
@bot.message_handler(func=lambda message: message.text == '1 ⬅')
def more_coins(message):
bot.send_message(message.from_user.id, 'page 1', reply_markup=user_markup)
# settings command handler
@bot.message_handler(func=lambda message: message.text == 'settings')
def settings(message):
# send a message to a user with new keyboard
bot.send_message(message.from_user.id, 'coming soon... maybe', reply_markup=user_markup3)
# feedback command handler
@bot.message_handler(func=lambda message: message.text == 'feedback')
def feedback(message):
# send a message to a user with new keyboard
bot.send_message(message.from_user.id, 'Send your opinion about the bot to ' + yourAlias + ', please',
reply_markup=user_markup3)
################################################## handlers for the coins text name
### BTC
@bot.message_handler(func=lambda message: message.text == 'Bitcoin')
def bitcoin(message):
text = requestAPI(message, "bitcoin", user_markup, bot)
### ETH
@bot.message_handler(func=lambda message: message.text == 'Ethereum')
def ethereum(message):
text = requestAPI(message, "ethereum", user_markup, bot)
### BCC
@bot.message_handler(func=lambda message: message.text == 'BitConnect')
def bitconnect(message):
text = requestAPI(message, "bitconnect", user_markup, bot)
### BCH
@bot.message_handler(func=lambda message: message.text == 'BitcoinCash')
def bitcoincash(message):
text = requestAPI(message, "bitcoin-cash", user_markup, bot)
### XRP
@bot.message_handler(func=lambda message: message.text == 'Ripple')
def ripple(message):
text = requestAPI(message, "ripple", user_markup, bot)
### LTC
@bot.message_handler(func=lambda message: message.text == 'Litecoin')
def litecoin(message):
text = requestAPI(message, "litecoin", user_markup2, bot)
### ADA
@bot.message_handler(func=lambda message: message.text == 'Cardano')
def cardano(message):
text = requestAPI(message, "cardano", user_markup2, bot)
### MIOTA
@bot.message_handler(func=lambda message: message.text == 'IOTA')
def iota(message):
text = requestAPI(message, "iota", user_markup2, bot)
### Dash
@bot.message_handler(func=lambda message: message.text == 'Dash')
def dash(message):
text = requestAPI(message, "dash", user_markup2, bot)
### NEM
@bot.message_handler(func=lambda message: message.text == 'NEM')
def nem(message):
text = requestAPI(message, "nem", user_markup3, bot)
### Monero
@bot.message_handler(func=lambda message: message.text == 'Monero')
def monero(message):
text = requestAPI(message, "monero", user_markup3, bot)
### NEO
@bot.message_handler(func=lambda message: message.text == 'NEO')
def neo(message):
text = requestAPI(message, "neo", user_markup3, bot)
################################## end of handlers for the coins text name
### text messages handler for send user keyboard for all users
@bot.message_handler(func=lambda message: True)
def settings(message):
bot.send_message(message.from_user.id, 'Hello, ' + message.from_user.first_name + '.', reply_markup=user_markup)
################################## end of settings block
@server.route("/bot", methods=['POST'])
def getMessage():
bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
return "!", 200
@server.route("/")
def webhook():
bot.remove_webhook()
bot.set_webhook(url=appURL)
return "!", 200
server.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))
server = Flask(__name__)
|
[] |
[] |
[
"YOURALIAS",
"PORT",
"APPURL",
"TOKEN"
] |
[]
|
["YOURALIAS", "PORT", "APPURL", "TOKEN"]
|
python
| 4 | 0 | |
integration-cli/docker_cli_run_test.go
|
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/Microsoft/hcsshim/osversion"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/integration-cli/cli/build"
"github.com/docker/docker/libnetwork/resolvconf"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/docker/runconfig"
"github.com/docker/docker/testutil"
"github.com/docker/docker/testutil/fakecontext"
"github.com/docker/go-connections/nat"
"github.com/moby/sys/mountinfo"
"gotest.tools/v3/assert"
"gotest.tools/v3/icmd"
"gotest.tools/v3/skip"
)
// "test123" should be printed by docker run
func (s *DockerSuite) TestRunEchoStdout(c *testing.T) {
out, _ := dockerCmd(c, "run", "busybox", "echo", "test123")
if out != "test123\n" {
c.Fatalf("container should've printed 'test123', got '%s'", out)
}
}
// "test" should be printed
func (s *DockerSuite) TestRunEchoNamedContainer(c *testing.T) {
out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
if out != "test\n" {
c.Errorf("container should've printed 'test'")
}
}
// docker run should not leak file descriptors. This test relies on Unix
// specific functionality and cannot run on Windows.
func (s *DockerSuite) TestRunLeakyFileDescriptors(c *testing.T) {
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd")
// normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
if out != "0 1 2 3\n" {
c.Errorf("container should've printed '0 1 2 3', not: %s", out)
}
}
// it should be possible to lookup Google DNS
// this will fail when Internet access is unavailable
func (s *DockerSuite) TestRunLookupGoogleDNS(c *testing.T) {
testRequires(c, Network, NotArm)
if testEnv.OSType == "windows" {
// nslookup isn't present in Windows busybox. Is built-in. Further,
// nslookup isn't present in nanoserver. Hence just use PowerShell...
dockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "powershell", "Resolve-DNSName", "google.com")
} else {
dockerCmd(c, "run", "busybox", "nslookup", "google.com")
}
}
// the exit code should be 0
func (s *DockerSuite) TestRunExitCodeZero(c *testing.T) {
dockerCmd(c, "run", "busybox", "true")
}
// the exit code should be 1
func (s *DockerSuite) TestRunExitCodeOne(c *testing.T) {
_, exitCode, err := dockerCmdWithError("run", "busybox", "false")
assert.ErrorContains(c, err, "")
assert.Equal(c, exitCode, 1)
}
// it should be possible to pipe in data via stdin to a process running in a container
func (s *DockerSuite) TestRunStdinPipe(c *testing.T) {
// TODO Windows: This needs some work to make compatible.
testRequires(c, DaemonIsLinux)
result := icmd.RunCmd(icmd.Cmd{
Command: []string{dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat"},
Stdin: strings.NewReader("blahblah"),
})
result.Assert(c, icmd.Success)
out := result.Stdout()
out = strings.TrimSpace(out)
dockerCmd(c, "wait", out)
logsOut, _ := dockerCmd(c, "logs", out)
containerLogs := strings.TrimSpace(logsOut)
if containerLogs != "blahblah" {
c.Errorf("logs didn't print the container's logs %s", containerLogs)
}
dockerCmd(c, "rm", out)
}
// the container's ID should be printed when starting a container in detached mode
func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *testing.T) {
out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
out = strings.TrimSpace(out)
dockerCmd(c, "wait", out)
rmOut, _ := dockerCmd(c, "rm", out)
rmOut = strings.TrimSpace(rmOut)
if rmOut != out {
c.Errorf("rm didn't print the container ID %s %s", out, rmOut)
}
}
// the working directory should be set correctly
func (s *DockerSuite) TestRunWorkingDirectory(c *testing.T) {
dir := "/root"
image := "busybox"
if testEnv.OSType == "windows" {
dir = `C:/Windows`
}
// First with -w
out, _ := dockerCmd(c, "run", "-w", dir, image, "pwd")
out = strings.TrimSpace(out)
if out != dir {
c.Errorf("-w failed to set working directory")
}
// Then with --workdir
out, _ = dockerCmd(c, "run", "--workdir", dir, image, "pwd")
out = strings.TrimSpace(out)
if out != dir {
c.Errorf("--workdir failed to set working directory")
}
}
// pinging Google's DNS resolver should fail when we disable the networking
func (s *DockerSuite) TestRunWithoutNetworking(c *testing.T) {
count := "-c"
image := "busybox"
if testEnv.OSType == "windows" {
count = "-n"
image = testEnv.PlatformDefaults.BaseImage
}
// First using the long form --net
out, exitCode, err := dockerCmdWithError("run", "--net=none", image, "ping", count, "1", "8.8.8.8")
if err != nil && exitCode != 1 {
c.Fatal(out, err)
}
if exitCode != 1 {
c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
}
}
// test --link use container name to link target
func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *testing.T) {
// TODO Windows: This test cannot run on a Windows daemon as the networking
// settings are not populated back yet on inspect.
testRequires(c, DaemonIsLinux)
dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox")
ip := inspectField(c, "parent", "NetworkSettings.Networks.bridge.IPAddress")
out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts")
if !strings.Contains(out, ip+" test") {
c.Fatalf("use a container name to link target failed")
}
}
// test --link use container id to link target
func (s *DockerSuite) TestRunLinksContainerWithContainerID(c *testing.T) {
// TODO Windows: This test cannot run on a Windows daemon as the networking
// settings are not populated back yet on inspect.
testRequires(c, DaemonIsLinux)
cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox")
cID = strings.TrimSpace(cID)
ip := inspectField(c, cID, "NetworkSettings.Networks.bridge.IPAddress")
out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts")
if !strings.Contains(out, ip+" test") {
c.Fatalf("use a container id to link target failed")
}
}
func (s *DockerSuite) TestUserDefinedNetworkLinks(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet")
dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top")
assert.Assert(c, waitRun("first") == nil)
// run a container in user-defined network udlinkNet with a link for an existing container
// and a link for a container that doesn't exist
dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo",
"--link=third:bar", "busybox", "top")
assert.Assert(c, waitRun("second") == nil)
// ping to first and its alias foo must succeed
_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
assert.NilError(c, err)
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
assert.NilError(c, err)
// ping to third and its alias must fail
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third")
assert.ErrorContains(c, err, "")
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
assert.ErrorContains(c, err, "")
// start third container now
dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=third", "busybox", "top")
assert.Assert(c, waitRun("third") == nil)
// ping to third and its alias must succeed now
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third")
assert.NilError(c, err)
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
assert.NilError(c, err)
}
func (s *DockerSuite) TestUserDefinedNetworkLinksWithRestart(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet")
dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top")
assert.Assert(c, waitRun("first") == nil)
dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo",
"busybox", "top")
assert.Assert(c, waitRun("second") == nil)
// ping to first and its alias foo must succeed
_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
assert.NilError(c, err)
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
assert.NilError(c, err)
// Restart first container
dockerCmd(c, "restart", "first")
assert.Assert(c, waitRun("first") == nil)
// ping to first and its alias foo must still succeed
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
assert.NilError(c, err)
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
assert.NilError(c, err)
// Restart second container
dockerCmd(c, "restart", "second")
assert.Assert(c, waitRun("second") == nil)
// ping to first and its alias foo must still succeed
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
assert.NilError(c, err)
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
assert.NilError(c, err)
}
func (s *DockerSuite) TestRunWithNetAliasOnDefaultNetworks(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
defaults := []string{"bridge", "host", "none"}
for _, net := range defaults {
out, _, err := dockerCmdWithError("run", "-d", "--net", net, "--net-alias", "alias_"+net, "busybox", "top")
assert.ErrorContains(c, err, "")
assert.Assert(c, strings.Contains(out, runconfig.ErrUnsupportedNetworkAndAlias.Error()))
}
}
func (s *DockerSuite) TestUserDefinedNetworkAlias(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
dockerCmd(c, "network", "create", "-d", "bridge", "net1")
cid1, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo1", "--net-alias=foo2", "busybox:glibc", "top")
assert.Assert(c, waitRun("first") == nil)
// Check if default short-id alias is added automatically
id := strings.TrimSpace(cid1)
aliases := inspectField(c, id, "NetworkSettings.Networks.net1.Aliases")
assert.Assert(c, strings.Contains(aliases, stringid.TruncateID(id)))
cid2, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox:glibc", "top")
assert.Assert(c, waitRun("second") == nil)
// Check if default short-id alias is added automatically
id = strings.TrimSpace(cid2)
aliases = inspectField(c, id, "NetworkSettings.Networks.net1.Aliases")
assert.Assert(c, strings.Contains(aliases, stringid.TruncateID(id)))
// ping to first and its network-scoped aliases
_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
assert.NilError(c, err)
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1")
assert.NilError(c, err)
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2")
assert.NilError(c, err)
// ping first container's short-id alias
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid1))
assert.NilError(c, err)
// Restart first container
dockerCmd(c, "restart", "first")
assert.Assert(c, waitRun("first") == nil)
// ping to first and its network-scoped aliases must succeed
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
assert.NilError(c, err)
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1")
assert.NilError(c, err)
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2")
assert.NilError(c, err)
// ping first container's short-id alias
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid1))
assert.NilError(c, err)
}
// Issue 9677.
func (s *DockerSuite) TestRunWithDaemonFlags(c *testing.T) {
out, _, err := dockerCmdWithError("--exec-opt", "foo=bar", "run", "-i", "busybox", "true")
assert.ErrorContains(c, err, "")
assert.Assert(c, strings.Contains(out, "unknown flag: --exec-opt"))
}
// Regression test for #4979
func (s *DockerSuite) TestRunWithVolumesFromExited(c *testing.T) {
var (
out string
exitCode int
)
// Create a file in a volume
if testEnv.OSType == "windows" {
out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", `c:\some\dir`, testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `echo hello > c:\some\dir\file`)
} else {
out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
}
if exitCode != 0 {
c.Fatal("1", out, exitCode)
}
// Read the file from another container using --volumes-from to access the volume in the second container
if testEnv.OSType == "windows" {
out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `type c:\some\dir\file`)
} else {
out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
}
if exitCode != 0 {
c.Fatal("2", out, exitCode)
}
}
// Volume path is a symlink which also exists on the host, and the host side is a file not a dir
// But the volume call is just a normal volume, not a bind mount
func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *testing.T) {
var (
dockerFile string
containerPath string
cmd string
)
// This test cannot run on a Windows daemon as
// Windows does not support symlinks inside a volume path
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
name := "test-volume-symlink"
dir, err := os.MkdirTemp("", name)
if err != nil {
c.Fatal(err)
}
defer os.RemoveAll(dir)
// In the case of Windows to Windows CI, if the machine is setup so that
// the temp directory is not the C: drive, this test is invalid and will
// not work.
if testEnv.OSType == "windows" && strings.ToLower(dir[:1]) != "c" {
c.Skip("Requires TEMP to point to C: drive")
}
f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700)
if err != nil {
c.Fatal(err)
}
f.Close()
if testEnv.OSType == "windows" {
dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir %s\nRUN mklink /D c:\\test %s", testEnv.PlatformDefaults.BaseImage, dir, dir)
containerPath = `c:\test\test`
cmd = "tasklist"
} else {
dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir)
containerPath = "/test/test"
cmd = "true"
}
buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile))
dockerCmd(c, "run", "-v", containerPath, name, cmd)
}
// Volume path is a symlink in the container
func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir2(c *testing.T) {
var (
dockerFile string
containerPath string
cmd string
)
// This test cannot run on a Windows daemon as
// Windows does not support symlinks inside a volume path
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
name := "test-volume-symlink2"
if testEnv.OSType == "windows" {
dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir c:\\%s\nRUN mklink /D c:\\test c:\\%s", testEnv.PlatformDefaults.BaseImage, name, name)
containerPath = `c:\test\test`
cmd = "tasklist"
} else {
dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p /%s\nRUN ln -s /%s /test", name, name)
containerPath = "/test/test"
cmd = "true"
}
buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile))
dockerCmd(c, "run", "-v", containerPath, name, cmd)
}
func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *testing.T) {
if _, code, err := dockerCmdWithError("run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile"); err == nil || code == 0 {
c.Fatalf("run should fail because volume is ro: exit code %d", code)
}
}
func (s *DockerSuite) TestRunVolumesFromInReadonlyModeFails(c *testing.T) {
var (
volumeDir string
fileInVol string
)
if testEnv.OSType == "windows" {
volumeDir = `c:/test` // Forward-slash as using busybox
fileInVol = `c:/test/file`
} else {
testRequires(c, DaemonIsLinux)
volumeDir = "/test"
fileInVol = `/test/file`
}
dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true")
if _, code, err := dockerCmdWithError("run", "--volumes-from", "parent:ro", "busybox", "touch", fileInVol); err == nil || code == 0 {
c.Fatalf("run should fail because volume is ro: exit code %d", code)
}
}
// Regression test for #1201
func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *testing.T) {
var (
volumeDir string
fileInVol string
)
if testEnv.OSType == "windows" {
volumeDir = `c:/test` // Forward-slash as using busybox
fileInVol = `c:/test/file`
} else {
volumeDir = "/test"
fileInVol = "/test/file"
}
dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true")
dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", fileInVol)
if out, _, err := dockerCmdWithError("run", "--volumes-from", "parent:bar", "busybox", "touch", fileInVol); err == nil || !strings.Contains(out, `invalid mode: bar`) {
c.Fatalf("running --volumes-from parent:bar should have failed with invalid mode: %q", out)
}
dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", fileInVol)
}
func (s *DockerSuite) TestVolumesFromGetsProperMode(c *testing.T) {
testRequires(c, testEnv.IsLocalDaemon)
prefix, slash := getPrefixAndSlashFromDaemonPlatform()
hostpath := RandomTmpDirPath("test", testEnv.OSType)
if err := os.MkdirAll(hostpath, 0755); err != nil {
c.Fatalf("Failed to create %s: %q", hostpath, err)
}
defer os.RemoveAll(hostpath)
dockerCmd(c, "run", "--name", "parent", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true")
// Expect this "rw" mode to be be ignored since the inherited volume is "ro"
if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent:rw", "busybox", "touch", prefix+slash+"test"+slash+"file"); err == nil {
c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
}
dockerCmd(c, "run", "--name", "parent2", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true")
// Expect this to be read-only since both are "ro"
if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent2:ro", "busybox", "touch", prefix+slash+"test"+slash+"file"); err == nil {
c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
}
}
// Test for GH#10618
func (s *DockerSuite) TestRunNoDupVolumes(c *testing.T) {
path1 := RandomTmpDirPath("test1", testEnv.OSType)
path2 := RandomTmpDirPath("test2", testEnv.OSType)
someplace := ":/someplace"
if testEnv.OSType == "windows" {
// Windows requires that the source directory exists before calling HCS
testRequires(c, testEnv.IsLocalDaemon)
someplace = `:c:\someplace`
if err := os.MkdirAll(path1, 0755); err != nil {
c.Fatalf("Failed to create %s: %q", path1, err)
}
defer os.RemoveAll(path1)
if err := os.MkdirAll(path2, 0755); err != nil {
c.Fatalf("Failed to create %s: %q", path1, err)
}
defer os.RemoveAll(path2)
}
mountstr1 := path1 + someplace
mountstr2 := path2 + someplace
if out, _, err := dockerCmdWithError("run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil {
c.Fatal("Expected error about duplicate mount definitions")
} else {
if !strings.Contains(out, "Duplicate mount point") {
c.Fatalf("Expected 'duplicate mount point' error, got %v", out)
}
}
// Test for https://github.com/docker/docker/issues/22093
volumename1 := "test1"
volumename2 := "test2"
volume1 := volumename1 + someplace
volume2 := volumename2 + someplace
if out, _, err := dockerCmdWithError("run", "-v", volume1, "-v", volume2, "busybox", "true"); err == nil {
c.Fatal("Expected error about duplicate mount definitions")
} else {
if !strings.Contains(out, "Duplicate mount point") {
c.Fatalf("Expected 'duplicate mount point' error, got %v", out)
}
}
// create failed should have create volume volumename1 or volumename2
// we should remove volumename2 or volumename2 successfully
out, _ := dockerCmd(c, "volume", "ls")
if strings.Contains(out, volumename1) {
dockerCmd(c, "volume", "rm", volumename1)
} else {
dockerCmd(c, "volume", "rm", volumename2)
}
}
// Test for #1351
func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *testing.T) {
prefix := ""
if testEnv.OSType == "windows" {
prefix = `c:`
}
dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo")
dockerCmd(c, "run", "--volumes-from", "parent", "-v", prefix+"/test", "busybox", "cat", prefix+"/test/foo")
}
func (s *DockerSuite) TestRunMultipleVolumesFrom(c *testing.T) {
prefix := ""
if testEnv.OSType == "windows" {
prefix = `c:`
}
dockerCmd(c, "run", "--name", "parent1", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo")
dockerCmd(c, "run", "--name", "parent2", "-v", prefix+"/other", "busybox", "touch", prefix+"/other/bar")
dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
}
// this tests verifies the ID format for the container
func (s *DockerSuite) TestRunVerifyContainerID(c *testing.T) {
out, exit, err := dockerCmdWithError("run", "-d", "busybox", "true")
if err != nil {
c.Fatal(err)
}
if exit != 0 {
c.Fatalf("expected exit code 0 received %d", exit)
}
match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
if err != nil {
c.Fatal(err)
}
if !match {
c.Fatalf("Invalid container ID: %s", out)
}
}
// Test that creating a container with a volume doesn't crash. Regression test for #995.
func (s *DockerSuite) TestRunCreateVolume(c *testing.T) {
prefix := ""
if testEnv.OSType == "windows" {
prefix = `c:`
}
dockerCmd(c, "run", "-v", prefix+"/var/lib/data", "busybox", "true")
}
// Test that creating a volume with a symlink in its path works correctly. Test for #5152.
// Note that this bug happens only with symlinks with a target that starts with '/'.
func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *testing.T) {
// Cannot run on Windows as relies on Linux-specific functionality (sh -c mount...)
testRequires(c, DaemonIsLinux)
workingDirectory, err := os.MkdirTemp("", "TestRunCreateVolumeWithSymlink")
assert.NilError(c, err)
image := "docker-test-createvolumewithsymlink"
buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-")
buildCmd.Stdin = strings.NewReader(`FROM busybox
RUN ln -s home /bar`)
buildCmd.Dir = workingDirectory
err = buildCmd.Run()
if err != nil {
c.Fatalf("could not build '%s': %v", image, err)
}
_, exitCode, err := dockerCmdWithError("run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo")
if err != nil || exitCode != 0 {
c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
}
volPath, err := inspectMountSourceField("test-createvolumewithsymlink", "/bar/foo")
assert.NilError(c, err)
_, exitCode, err = dockerCmdWithError("rm", "-v", "test-createvolumewithsymlink")
if err != nil || exitCode != 0 {
c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
}
_, err = os.Stat(volPath)
if !os.IsNotExist(err) {
c.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath)
}
}
// Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *testing.T) {
// This test cannot run on a Windows daemon as
// Windows does not support symlinks inside a volume path
testRequires(c, DaemonIsLinux)
workingDirectory, err := os.MkdirTemp("", "TestRunVolumesFromSymlinkPath")
assert.NilError(c, err)
name := "docker-test-volumesfromsymlinkpath"
prefix := ""
dfContents := `FROM busybox
RUN ln -s home /foo
VOLUME ["/foo/bar"]`
if testEnv.OSType == "windows" {
prefix = `c:`
dfContents = `FROM ` + testEnv.PlatformDefaults.BaseImage + `
RUN mkdir c:\home
RUN mklink /D c:\foo c:\home
VOLUME ["c:/foo/bar"]
ENTRYPOINT c:\windows\system32\cmd.exe`
}
buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
buildCmd.Stdin = strings.NewReader(dfContents)
buildCmd.Dir = workingDirectory
err = buildCmd.Run()
if err != nil {
c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
}
out, exitCode, err := dockerCmdWithError("run", "--name", "test-volumesfromsymlinkpath", name)
if err != nil || exitCode != 0 {
c.Fatalf("[run] (volume) err: %v, exitcode: %d, out: %s", err, exitCode, out)
}
_, exitCode, err = dockerCmdWithError("run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls "+prefix+"/foo | grep -q bar")
if err != nil || exitCode != 0 {
c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
}
}
func (s *DockerSuite) TestRunExitCode(c *testing.T) {
var (
exit int
err error
)
_, exit, err = dockerCmdWithError("run", "busybox", "/bin/sh", "-c", "exit 72")
if err == nil {
c.Fatal("should not have a non nil error")
}
if exit != 72 {
c.Fatalf("expected exit code 72 received %d", exit)
}
}
func (s *DockerSuite) TestRunUserDefaults(c *testing.T) {
expected := "uid=0(root) gid=0(root)"
if testEnv.OSType == "windows" {
expected = "uid=0(root) gid=0(root) groups=0(root)"
}
out, _ := dockerCmd(c, "run", "busybox", "id")
if !strings.Contains(out, expected) {
c.Fatalf("expected '%s' got %s", expected, out)
}
}
func (s *DockerSuite) TestRunUserByName(c *testing.T) {
// TODO Windows: This test cannot run on a Windows daemon as Windows does
// not support the use of -u
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-u", "root", "busybox", "id")
if !strings.Contains(out, "uid=0(root) gid=0(root)") {
c.Fatalf("expected root user got %s", out)
}
}
func (s *DockerSuite) TestRunUserByID(c *testing.T) {
// TODO Windows: This test cannot run on a Windows daemon as Windows does
// not support the use of -u
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-u", "1", "busybox", "id")
if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
c.Fatalf("expected daemon user got %s", out)
}
}
func (s *DockerSuite) TestRunUserByIDBig(c *testing.T) {
// TODO Windows: This test cannot run on a Windows daemon as Windows does
// not support the use of -u
testRequires(c, DaemonIsLinux, NotArm)
out, _, err := dockerCmdWithError("run", "-u", "2147483648", "busybox", "id")
if err == nil {
c.Fatal("No error, but must be.", out)
}
if !strings.Contains(strings.ToLower(out), "uids and gids must be in range") {
c.Fatalf("expected error about uids range, got %s", out)
}
}
func (s *DockerSuite) TestRunUserByIDNegative(c *testing.T) {
// TODO Windows: This test cannot run on a Windows daemon as Windows does
// not support the use of -u
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "-u", "-1", "busybox", "id")
if err == nil {
c.Fatal("No error, but must be.", out)
}
if !strings.Contains(strings.ToLower(out), "uids and gids must be in range") {
c.Fatalf("expected error about uids range, got %s", out)
}
}
func (s *DockerSuite) TestRunUserByIDZero(c *testing.T) {
// TODO Windows: This test cannot run on a Windows daemon as Windows does
// not support the use of -u
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "-u", "0", "busybox", "id")
if err != nil {
c.Fatal(err, out)
}
if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") {
c.Fatalf("expected daemon user got %s", out)
}
}
func (s *DockerSuite) TestRunUserNotFound(c *testing.T) {
// TODO Windows: This test cannot run on a Windows daemon as Windows does
// not support the use of -u
testRequires(c, DaemonIsLinux)
_, _, err := dockerCmdWithError("run", "-u", "notme", "busybox", "id")
if err == nil {
c.Fatal("unknown user should cause container to fail")
}
}
func (s *DockerSuite) TestRunTwoConcurrentContainers(c *testing.T) {
sleepTime := "2"
group := sync.WaitGroup{}
group.Add(2)
errChan := make(chan error, 2)
for i := 0; i < 2; i++ {
go func() {
defer group.Done()
_, _, err := dockerCmdWithError("run", "busybox", "sleep", sleepTime)
errChan <- err
}()
}
group.Wait()
close(errChan)
for err := range errChan {
assert.NilError(c, err)
}
}
func (s *DockerSuite) TestRunEnvironment(c *testing.T) {
// TODO Windows: Environment handling is different between Linux and
// Windows and this test relies currently on unix functionality.
testRequires(c, DaemonIsLinux)
result := icmd.RunCmd(icmd.Cmd{
Command: []string{dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env"},
Env: append(os.Environ(),
"TRUE=false",
"TRICKY=tri\ncky\n",
),
})
result.Assert(c, icmd.Success)
actualEnv := strings.Split(strings.TrimSuffix(result.Stdout(), "\n"), "\n")
sort.Strings(actualEnv)
goodEnv := []string{
// The first two should not be tested here, those are "inherent" environment variable. This test validates
// the -e behavior, not the default environment variable (that could be subject to change)
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"HOSTNAME=testing",
"FALSE=true",
"TRUE=false",
"TRICKY=tri",
"cky",
"",
"HOME=/root",
}
sort.Strings(goodEnv)
if len(goodEnv) != len(actualEnv) {
c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", "))
}
for i := range goodEnv {
if actualEnv[i] != goodEnv[i] {
c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
}
}
}
func (s *DockerSuite) TestRunEnvironmentErase(c *testing.T) {
// TODO Windows: Environment handling is different between Linux and
// Windows and this test relies currently on unix functionality.
testRequires(c, DaemonIsLinux)
// Test to make sure that when we use -e on env vars that are
// not set in our local env that they're removed (if present) in
// the container
result := icmd.RunCmd(icmd.Cmd{
Command: []string{dockerBinary, "run", "-e", "FOO", "-e", "HOSTNAME", "busybox", "env"},
Env: appendBaseEnv(true),
})
result.Assert(c, icmd.Success)
actualEnv := strings.Split(strings.TrimSpace(result.Combined()), "\n")
sort.Strings(actualEnv)
goodEnv := []string{
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"HOME=/root",
}
sort.Strings(goodEnv)
if len(goodEnv) != len(actualEnv) {
c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", "))
}
for i := range goodEnv {
if actualEnv[i] != goodEnv[i] {
c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
}
}
}
func (s *DockerSuite) TestRunEnvironmentOverride(c *testing.T) {
// TODO Windows: Environment handling is different between Linux and
// Windows and this test relies currently on unix functionality.
testRequires(c, DaemonIsLinux)
// Test to make sure that when we use -e on env vars that are
// already in the env that we're overriding them
result := icmd.RunCmd(icmd.Cmd{
Command: []string{dockerBinary, "run", "-e", "HOSTNAME", "-e", "HOME=/root2", "busybox", "env"},
Env: appendBaseEnv(true, "HOSTNAME=bar"),
})
result.Assert(c, icmd.Success)
actualEnv := strings.Split(strings.TrimSpace(result.Combined()), "\n")
sort.Strings(actualEnv)
goodEnv := []string{
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"HOME=/root2",
"HOSTNAME=bar",
}
sort.Strings(goodEnv)
if len(goodEnv) != len(actualEnv) {
c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", "))
}
for i := range goodEnv {
if actualEnv[i] != goodEnv[i] {
c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
}
}
}
func (s *DockerSuite) TestRunContainerNetwork(c *testing.T) {
if testEnv.OSType == "windows" {
// Windows busybox does not have ping. Use built in ping instead.
dockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1")
} else {
dockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
}
}
func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *testing.T) {
// TODO Windows: This is Linux specific as --link is not supported and
// this will be deprecated in favor of container networking model.
testRequires(c, DaemonIsLinux, NotUserNamespace)
dockerCmd(c, "run", "--name", "linked", "busybox", "true")
_, _, err := dockerCmdWithError("run", "--net=host", "--link", "linked:linked", "busybox", "true")
if err == nil {
c.Fatal("Expected error")
}
}
// #7851 hostname outside container shows FQDN, inside only shortname
// For testing purposes it is not required to set host's hostname directly
// and use "--net=host" (as the original issue submitter did), as the same
// codepath is executed with "docker run -h <hostname>". Both were manually
// tested, but this testcase takes the simpler path of using "run -h .."
func (s *DockerSuite) TestRunFullHostnameSet(c *testing.T) {
// TODO Windows: -h is not yet functional.
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname")
if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" {
c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual)
}
}
func (s *DockerSuite) TestRunPrivilegedCanMknod(c *testing.T) {
// Not applicable for Windows as Windows daemon does not support
// the concept of --privileged, and mknod is a Unix concept.
testRequires(c, DaemonIsLinux, NotUserNamespace)
out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
if actual := strings.Trim(out, "\r\n"); actual != "ok" {
c.Fatalf("expected output ok received %s", actual)
}
}
func (s *DockerSuite) TestRunUnprivilegedCanMknod(c *testing.T) {
// Not applicable for Windows as Windows daemon does not support
// the concept of --privileged, and mknod is a Unix concept.
testRequires(c, DaemonIsLinux, NotUserNamespace)
out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
if actual := strings.Trim(out, "\r\n"); actual != "ok" {
c.Fatalf("expected output ok received %s", actual)
}
}
func (s *DockerSuite) TestRunCapDropInvalid(c *testing.T) {
// Not applicable for Windows as there is no concept of --cap-drop
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "--cap-drop=CHPASS", "busybox", "ls")
if err == nil {
c.Fatal(err, out)
}
}
func (s *DockerSuite) TestRunCapDropCannotMknod(c *testing.T) {
// Not applicable for Windows as there is no concept of --cap-drop or mknod
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
if err == nil {
c.Fatal(err, out)
}
if actual := strings.Trim(out, "\r\n"); actual == "ok" {
c.Fatalf("expected output not ok received %s", actual)
}
}
func (s *DockerSuite) TestRunCapDropCannotMknodLowerCase(c *testing.T) {
// Not applicable for Windows as there is no concept of --cap-drop or mknod
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
if err == nil {
c.Fatal(err, out)
}
if actual := strings.Trim(out, "\r\n"); actual == "ok" {
c.Fatalf("expected output not ok received %s", actual)
}
}
func (s *DockerSuite) TestRunCapDropALLCannotMknod(c *testing.T) {
// Not applicable for Windows as there is no concept of --cap-drop or mknod
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
if err == nil {
c.Fatal(err, out)
}
if actual := strings.Trim(out, "\r\n"); actual == "ok" {
c.Fatalf("expected output not ok received %s", actual)
}
}
func (s *DockerSuite) TestRunCapDropALLAddMknodCanMknod(c *testing.T) {
// Not applicable for Windows as there is no concept of --cap-drop or mknod
testRequires(c, DaemonIsLinux, NotUserNamespace)
out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
if actual := strings.Trim(out, "\r\n"); actual != "ok" {
c.Fatalf("expected output ok received %s", actual)
}
}
func (s *DockerSuite) TestRunCapAddInvalid(c *testing.T) {
// Not applicable for Windows as there is no concept of --cap-add
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "--cap-add=CHPASS", "busybox", "ls")
if err == nil {
c.Fatal(err, out)
}
}
func (s *DockerSuite) TestRunCapAddCanDownInterface(c *testing.T) {
// Not applicable for Windows as there is no concept of --cap-add
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
if actual := strings.Trim(out, "\r\n"); actual != "ok" {
c.Fatalf("expected output ok received %s", actual)
}
}
func (s *DockerSuite) TestRunCapAddALLCanDownInterface(c *testing.T) {
// Not applicable for Windows as there is no concept of --cap-add
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
if actual := strings.Trim(out, "\r\n"); actual != "ok" {
c.Fatalf("expected output ok received %s", actual)
}
}
func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *testing.T) {
// Not applicable for Windows as there is no concept of --cap-add
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
if err == nil {
c.Fatal(err, out)
}
if actual := strings.Trim(out, "\r\n"); actual == "ok" {
c.Fatalf("expected output not ok received %s", actual)
}
}
func (s *DockerSuite) TestRunGroupAdd(c *testing.T) {
// Not applicable for Windows as there is no concept of --group-add
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=staff", "--group-add=777", "busybox", "sh", "-c", "id")
groupsList := "uid=0(root) gid=0(root) groups=10(wheel),29(audio),50(staff),777"
if actual := strings.Trim(out, "\r\n"); actual != groupsList {
c.Fatalf("expected output %s received %s", groupsList, actual)
}
}
func (s *DockerSuite) TestRunPrivilegedCanMount(c *testing.T) {
// Not applicable for Windows as there is no concept of --privileged
testRequires(c, DaemonIsLinux, NotUserNamespace)
out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
if actual := strings.Trim(out, "\r\n"); actual != "ok" {
c.Fatalf("expected output ok received %s", actual)
}
}
func (s *DockerSuite) TestRunUnprivilegedCannotMount(c *testing.T) {
// Not applicable for Windows as there is no concept of unprivileged
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
if err == nil {
c.Fatal(err, out)
}
if actual := strings.Trim(out, "\r\n"); actual == "ok" {
c.Fatalf("expected output not ok received %s", actual)
}
}
func (s *DockerSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *testing.T) {
// Not applicable for Windows as there is no concept of unprivileged
testRequires(c, DaemonIsLinux, NotArm)
if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/sys/kernel/profiling"); err == nil || code == 0 {
c.Fatal("sys should not be writable in a non privileged container")
}
}
func (s *DockerSuite) TestRunSysWritableInPrivilegedContainers(c *testing.T) {
// Not applicable for Windows as there is no concept of unprivileged
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
if _, code, err := dockerCmdWithError("run", "--privileged", "busybox", "touch", "/sys/kernel/profiling"); err != nil || code != 0 {
c.Fatalf("sys should be writable in privileged container")
}
}
func (s *DockerSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *testing.T) {
// Not applicable for Windows as there is no concept of unprivileged
testRequires(c, DaemonIsLinux)
if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/proc/sysrq-trigger"); err == nil || code == 0 {
c.Fatal("proc should not be writable in a non privileged container")
}
}
func (s *DockerSuite) TestRunProcWritableInPrivilegedContainers(c *testing.T) {
// Not applicable for Windows as there is no concept of --privileged
testRequires(c, DaemonIsLinux, NotUserNamespace)
if _, code := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "touch /proc/sysrq-trigger"); code != 0 {
c.Fatalf("proc should be writable in privileged container")
}
}
func (s *DockerSuite) TestRunDeviceNumbers(c *testing.T) {
// Not applicable on Windows as /dev/ is a Unix specific concept
// TODO: NotUserNamespace could be removed here if "root" "root" is replaced w user
testRequires(c, DaemonIsLinux, NotUserNamespace)
out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null")
deviceLineFields := strings.Fields(out)
deviceLineFields[6] = ""
deviceLineFields[7] = ""
deviceLineFields[8] = ""
expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"}
if !(reflect.DeepEqual(deviceLineFields, expected)) {
c.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out)
}
}
func (s *DockerSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *testing.T) {
// Not applicable on Windows as /dev/ is a Unix specific concept
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
}
}
func (s *DockerSuite) TestRunUnprivilegedWithChroot(c *testing.T) {
// Not applicable on Windows as it does not support chroot
testRequires(c, DaemonIsLinux)
dockerCmd(c, "run", "busybox", "chroot", "/", "true")
}
func (s *DockerSuite) TestRunAddingOptionalDevices(c *testing.T) {
// Not applicable on Windows as Windows does not support --device
testRequires(c, DaemonIsLinux, NotUserNamespace)
out, _ := dockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
c.Fatalf("expected output /dev/nulo, received %s", actual)
}
}
func (s *DockerSuite) TestRunAddingOptionalDevicesNoSrc(c *testing.T) {
// Not applicable on Windows as Windows does not support --device
testRequires(c, DaemonIsLinux, NotUserNamespace)
out, _ := dockerCmd(c, "run", "--device", "/dev/zero:rw", "busybox", "sh", "-c", "ls /dev/zero")
if actual := strings.Trim(out, "\r\n"); actual != "/dev/zero" {
c.Fatalf("expected output /dev/zero, received %s", actual)
}
}
func (s *DockerSuite) TestRunAddingOptionalDevicesInvalidMode(c *testing.T) {
// Not applicable on Windows as Windows does not support --device
testRequires(c, DaemonIsLinux, NotUserNamespace)
_, _, err := dockerCmdWithError("run", "--device", "/dev/zero:ro", "busybox", "sh", "-c", "ls /dev/zero")
if err == nil {
c.Fatalf("run container with device mode ro should fail")
}
}
func (s *DockerSuite) TestRunModeHostname(c *testing.T) {
// Not applicable on Windows as Windows does not support -h
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
c.Fatalf("expected 'testhostname', but says: %q", actual)
}
out, _ = dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname")
hostname, err := os.Hostname()
if err != nil {
c.Fatal(err)
}
if actual := strings.Trim(out, "\r\n"); actual != hostname {
c.Fatalf("expected %q, but says: %q", hostname, actual)
}
}
func (s *DockerSuite) TestRunRootWorkdir(c *testing.T) {
out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd")
expected := "/\n"
if testEnv.OSType == "windows" {
expected = "C:" + expected
}
if out != expected {
c.Fatalf("pwd returned %q (expected %s)", s, expected)
}
}
func (s *DockerSuite) TestRunAllowBindMountingRoot(c *testing.T) {
if testEnv.OSType == "windows" {
// Windows busybox will fail with Permission Denied on items such as pagefile.sys
dockerCmd(c, "run", "-v", `c:\:c:\host`, testEnv.PlatformDefaults.BaseImage, "cmd", "-c", "dir", `c:\host`)
} else {
dockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host")
}
}
func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *testing.T) {
mount := "/:/"
targetDir := "/host"
if testEnv.OSType == "windows" {
mount = `c:\:c\`
targetDir = "c:/host" // Forward slash as using busybox
}
out, _, err := dockerCmdWithError("run", "-v", mount, "busybox", "ls", targetDir)
if err == nil {
c.Fatal(out, err)
}
}
// Verify that a container gets default DNS when only localhost resolvers exist
func (s *DockerSuite) TestRunDNSDefaultOptions(c *testing.T) {
// Not applicable on Windows as this is testing Unix specific functionality
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
// preserve original resolv.conf for restoring after test
origResolvConf, err := os.ReadFile("/etc/resolv.conf")
if os.IsNotExist(err) {
c.Fatalf("/etc/resolv.conf does not exist")
}
// defer restored original conf
defer func() {
if err := os.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
c.Fatal(err)
}
}()
// test 3 cases: standard IPv4 localhost, commented out localhost, and IPv6 localhost
// 2 are removed from the file at container start, and the 3rd (commented out) one is ignored by
// GetNameservers(), leading to a replacement of nameservers with the default set
tmpResolvConf := []byte("nameserver 127.0.0.1\n#nameserver 127.0.2.1\nnameserver ::1")
if err := os.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
c.Fatal(err)
}
actual, _ := dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
// check that the actual defaults are appended to the commented out
// localhost resolver (which should be preserved)
// NOTE: if we ever change the defaults from google dns, this will break
expected := "#nameserver 127.0.2.1\n\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n"
if actual != expected {
c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual)
}
}
func (s *DockerSuite) TestRunDNSOptions(c *testing.T) {
// Not applicable on Windows as Windows does not support --dns*, or
// the Unix-specific functionality of resolv.conf.
testRequires(c, DaemonIsLinux)
result := cli.DockerCmd(c, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "--dns-opt=ndots:9", "busybox", "cat", "/etc/resolv.conf")
// The client will get a warning on stderr when setting DNS to a localhost address; verify this:
if !strings.Contains(result.Stderr(), "Localhost DNS setting") {
c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", result.Stderr())
}
actual := strings.Replace(strings.Trim(result.Stdout(), "\r\n"), "\n", " ", -1)
if actual != "search mydomain nameserver 127.0.0.1 options ndots:9" {
c.Fatalf("expected 'search mydomain nameserver 127.0.0.1 options ndots:9', but says: %q", actual)
}
out := cli.DockerCmd(c, "run", "--dns=1.1.1.1", "--dns-search=.", "--dns-opt=ndots:3", "busybox", "cat", "/etc/resolv.conf").Combined()
actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
if actual != "nameserver 1.1.1.1 options ndots:3" {
c.Fatalf("expected 'nameserver 1.1.1.1 options ndots:3', but says: %q", actual)
}
}
func (s *DockerSuite) TestRunDNSRepeatOptions(c *testing.T) {
testRequires(c, DaemonIsLinux)
out := cli.DockerCmd(c, "run", "--dns=1.1.1.1", "--dns=2.2.2.2", "--dns-search=mydomain", "--dns-search=mydomain2", "--dns-opt=ndots:9", "--dns-opt=timeout:3", "busybox", "cat", "/etc/resolv.conf").Stdout()
actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
if actual != "search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3" {
c.Fatalf("expected 'search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3', but says: %q", actual)
}
}
func (s *DockerSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *testing.T) {
// Not applicable on Windows as testing Unix specific functionality
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
origResolvConf, err := os.ReadFile("/etc/resolv.conf")
if os.IsNotExist(err) {
c.Fatalf("/etc/resolv.conf does not exist")
}
hostNameservers := resolvconf.GetNameservers(origResolvConf, resolvconf.IP)
hostSearch := resolvconf.GetSearchDomains(origResolvConf)
var out string
out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
if actualNameservers := resolvconf.GetNameservers([]byte(out), resolvconf.IP); actualNameservers[0] != "127.0.0.1" {
c.Fatalf("expected '127.0.0.1', but says: %q", actualNameservers[0])
}
actualSearch := resolvconf.GetSearchDomains([]byte(out))
if len(actualSearch) != len(hostSearch) {
c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
}
for i := range actualSearch {
if actualSearch[i] != hostSearch[i] {
c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
}
}
out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
actualNameservers := resolvconf.GetNameservers([]byte(out), resolvconf.IP)
if len(actualNameservers) != len(hostNameservers) {
c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNameservers), len(actualNameservers))
}
for i := range actualNameservers {
if actualNameservers[i] != hostNameservers[i] {
c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNameservers[i])
}
}
if actualSearch = resolvconf.GetSearchDomains([]byte(out)); actualSearch[0] != "mydomain" {
c.Fatalf("expected 'mydomain', but says: %q", actualSearch[0])
}
// test with file
tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1")
if err := os.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
c.Fatal(err)
}
// put the old resolvconf back
defer func() {
if err := os.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
c.Fatal(err)
}
}()
resolvConf, err := os.ReadFile("/etc/resolv.conf")
if os.IsNotExist(err) {
c.Fatalf("/etc/resolv.conf does not exist")
}
hostSearch = resolvconf.GetSearchDomains(resolvConf)
out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
if actualNameservers = resolvconf.GetNameservers([]byte(out), resolvconf.IP); actualNameservers[0] != "12.34.56.78" || len(actualNameservers) != 1 {
c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers)
}
actualSearch = resolvconf.GetSearchDomains([]byte(out))
if len(actualSearch) != len(hostSearch) {
c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
}
for i := range actualSearch {
if actualSearch[i] != hostSearch[i] {
c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
}
}
}
// Test to see if a non-root user can resolve a DNS name. Also
// check if the container resolv.conf file has at least 0644 perm.
func (s *DockerSuite) TestRunNonRootUserResolvName(c *testing.T) {
// Not applicable on Windows as Windows does not support --user
testRequires(c, testEnv.IsLocalDaemon, Network, DaemonIsLinux, NotArm)
dockerCmd(c, "run", "--name=testperm", "--user=nobody", "busybox", "nslookup", "example.com")
cID := getIDByName(c, "testperm")
fmode := (os.FileMode)(0644)
finfo, err := os.Stat(containerStorageFile(cID, "resolv.conf"))
if err != nil {
c.Fatal(err)
}
if (finfo.Mode() & fmode) != fmode {
c.Fatalf("Expected container resolv.conf mode to be at least %s, instead got %s", fmode.String(), finfo.Mode().String())
}
}
// Test if container resolv.conf gets updated the next time it restarts
// if host /etc/resolv.conf has changed. This only applies if the container
// uses the host's /etc/resolv.conf and does not have any dns options provided.
func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) {
// Not applicable on Windows as testing unix specific functionality
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
c.Skip("Unstable test, to be re-activated once #19937 is resolved")
tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\n")
tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1")
// take a copy of resolv.conf for restoring after test completes
resolvConfSystem, err := os.ReadFile("/etc/resolv.conf")
if err != nil {
c.Fatal(err)
}
// This test case is meant to test monitoring resolv.conf when it is
// a regular file not a bind mounc. So we unmount resolv.conf and replace
// it with a file containing the original settings.
mounted, err := mountinfo.Mounted("/etc/resolv.conf")
if err != nil {
c.Fatal(err)
}
if mounted {
icmd.RunCommand("umount", "/etc/resolv.conf").Assert(c, icmd.Success)
}
// cleanup
defer func() {
if err := os.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
c.Fatal(err)
}
}()
// 1. test that a restarting container gets an updated resolv.conf
dockerCmd(c, "run", "--name=first", "busybox", "true")
containerID1 := getIDByName(c, "first")
// replace resolv.conf with our temporary copy
if err := os.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
c.Fatal(err)
}
// start the container again to pickup changes
dockerCmd(c, "start", "first")
// check for update in container
containerResolv := readContainerFile(c, containerID1, "resolv.conf")
if !bytes.Equal(containerResolv, tmpResolvConf) {
c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv))
}
/* // make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
if err := os.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
c.Fatal(err)
} */
// 2. test that a restarting container does not receive resolv.conf updates
// if it modified the container copy of the starting point resolv.conf
dockerCmd(c, "run", "--name=second", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf")
containerID2 := getIDByName(c, "second")
// make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
if err := os.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
c.Fatal(err)
}
// start the container again
dockerCmd(c, "start", "second")
// check for update in container
containerResolv = readContainerFile(c, containerID2, "resolv.conf")
if bytes.Equal(containerResolv, resolvConfSystem) {
c.Fatalf("Container's resolv.conf should not have been updated with host resolv.conf: %q", string(containerResolv))
}
// 3. test that a running container's resolv.conf is not modified while running
out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
runningContainerID := strings.TrimSpace(out)
// replace resolv.conf
if err := os.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
c.Fatal(err)
}
// check for update in container
containerResolv = readContainerFile(c, runningContainerID, "resolv.conf")
if bytes.Equal(containerResolv, tmpResolvConf) {
c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv))
}
// 4. test that a running container's resolv.conf is updated upon restart
// (the above container is still running..)
dockerCmd(c, "restart", runningContainerID)
// check for update in container
containerResolv = readContainerFile(c, runningContainerID, "resolv.conf")
if !bytes.Equal(containerResolv, tmpResolvConf) {
c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(tmpResolvConf), string(containerResolv))
}
// 5. test that additions of a localhost resolver are cleaned from
// host resolv.conf before updating container's resolv.conf copies
// replace resolv.conf with a localhost-only nameserver copy
if err = os.WriteFile("/etc/resolv.conf", tmpLocalhostResolvConf, 0644); err != nil {
c.Fatal(err)
}
// start the container again to pickup changes
dockerCmd(c, "start", "first")
// our first exited container ID should have been updated, but with default DNS
// after the cleanup of resolv.conf found only a localhost nameserver:
containerResolv = readContainerFile(c, containerID1, "resolv.conf")
expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n"
if !bytes.Equal(containerResolv, []byte(expected)) {
c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv))
}
// 6. Test that replacing (as opposed to modifying) resolv.conf triggers an update
// of containers' resolv.conf.
// Restore the original resolv.conf
if err := os.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
c.Fatal(err)
}
// Run the container so it picks up the old settings
dockerCmd(c, "run", "--name=third", "busybox", "true")
containerID3 := getIDByName(c, "third")
// Create a modified resolv.conf.aside and override resolv.conf with it
if err := os.WriteFile("/etc/resolv.conf.aside", tmpResolvConf, 0644); err != nil {
c.Fatal(err)
}
err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf")
if err != nil {
c.Fatal(err)
}
// start the container again to pickup changes
dockerCmd(c, "start", "third")
// check for update in container
containerResolv = readContainerFile(c, containerID3, "resolv.conf")
if !bytes.Equal(containerResolv, tmpResolvConf) {
c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv))
}
// cleanup, restore original resolv.conf happens in defer func()
}
func (s *DockerSuite) TestRunAddHost(c *testing.T) {
// Not applicable on Windows as it does not support --add-host
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
actual := strings.Trim(out, "\r\n")
if actual != "86.75.30.9\textra" {
c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual)
}
}
// Regression test for #6983
func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *testing.T) {
_, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true")
if exitCode != 0 {
c.Fatalf("Container should have exited with error code 0")
}
}
// Regression test for #6983
func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *testing.T) {
_, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true")
if exitCode != 0 {
c.Fatalf("Container should have exited with error code 0")
}
}
// Regression test for #6983
func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *testing.T) {
_, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
if exitCode != 0 {
c.Fatalf("Container should have exited with error code 0")
}
}
// Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode
// but using --attach instead of -a to make sure we read the flag correctly
func (s *DockerSuite) TestRunAttachWithDetach(c *testing.T) {
icmd.RunCommand(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true").Assert(c, icmd.Expected{
ExitCode: 1,
Error: "exit status 1",
Err: "Conflicting options: -a and -d",
})
}
func (s *DockerSuite) TestRunState(c *testing.T) {
// TODO Windows: This needs some rework as Windows busybox does not support top
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
id := strings.TrimSpace(out)
state := inspectField(c, id, "State.Running")
if state != "true" {
c.Fatal("Container state is 'not running'")
}
pid1 := inspectField(c, id, "State.Pid")
if pid1 == "0" {
c.Fatal("Container state Pid 0")
}
dockerCmd(c, "stop", id)
state = inspectField(c, id, "State.Running")
if state != "false" {
c.Fatal("Container state is 'running'")
}
pid2 := inspectField(c, id, "State.Pid")
if pid2 == pid1 {
c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
}
dockerCmd(c, "start", id)
state = inspectField(c, id, "State.Running")
if state != "true" {
c.Fatal("Container state is 'not running'")
}
pid3 := inspectField(c, id, "State.Pid")
if pid3 == pid1 {
c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
}
}
// Test for #1737
func (s *DockerSuite) TestRunCopyVolumeUIDGID(c *testing.T) {
// Not applicable on Windows as it does not support uid or gid in this way
testRequires(c, DaemonIsLinux)
name := "testrunvolumesuidgid"
buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
RUN echo 'dockerio:x:1001:' >> /etc/group
RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`))
// Test that the uid and gid is copied from the image to the volume
out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
out = strings.TrimSpace(out)
if out != "dockerio:dockerio" {
c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
}
}
// Test for #1582
func (s *DockerSuite) TestRunCopyVolumeContent(c *testing.T) {
// TODO Windows, post RS1. Windows does not yet support volume functionality
// that copies from the image to the volume.
testRequires(c, DaemonIsLinux)
name := "testruncopyvolumecontent"
buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
RUN mkdir -p /hello/local && echo hello > /hello/local/world`))
// Test that the content is copied from the image to the volume
out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello")
if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
c.Fatal("Container failed to transfer content to volume")
}
}
func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *testing.T) {
name := "testrunmdcleanuponentrypoint"
buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
ENTRYPOINT ["echo"]
CMD ["testingpoint"]`))
out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name)
if exit != 0 {
c.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
}
out = strings.TrimSpace(out)
expected := "root"
if testEnv.OSType == "windows" {
if strings.Contains(testEnv.PlatformDefaults.BaseImage, "servercore") {
expected = `user manager\containeradministrator`
} else {
expected = `ContainerAdministrator` // nanoserver
}
}
if out != expected {
c.Fatalf("Expected output %s, got %q. %s", expected, out, testEnv.PlatformDefaults.BaseImage)
}
}
// TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *testing.T) {
existingFile := "/bin/cat"
expected := "not a directory"
if testEnv.OSType == "windows" {
existingFile = `\windows\system32\ntdll.dll`
expected = `The directory name is invalid.`
}
out, exitCode, err := dockerCmdWithError("run", "-w", existingFile, "busybox")
if !(err != nil && exitCode == 125 && strings.Contains(out, expected)) {
c.Fatalf("Existing binary as a directory should error out with exitCode 125; we got: %s, exitCode: %d", out, exitCode)
}
}
func (s *DockerSuite) TestRunExitOnStdinClose(c *testing.T) {
name := "testrunexitonstdinclose"
meow := "/bin/cat"
delay := 60
if testEnv.OSType == "windows" {
meow = "cat"
}
runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", meow)
stdin, err := runCmd.StdinPipe()
if err != nil {
c.Fatal(err)
}
stdout, err := runCmd.StdoutPipe()
if err != nil {
c.Fatal(err)
}
if err := runCmd.Start(); err != nil {
c.Fatal(err)
}
if _, err := stdin.Write([]byte("hello\n")); err != nil {
c.Fatal(err)
}
r := bufio.NewReader(stdout)
line, err := r.ReadString('\n')
if err != nil {
c.Fatal(err)
}
line = strings.TrimSpace(line)
if line != "hello" {
c.Fatalf("Output should be 'hello', got '%q'", line)
}
if err := stdin.Close(); err != nil {
c.Fatal(err)
}
finish := make(chan error, 1)
go func() {
finish <- runCmd.Wait()
close(finish)
}()
select {
case err := <-finish:
assert.NilError(c, err)
case <-time.After(time.Duration(delay) * time.Second):
c.Fatal("docker run failed to exit on stdin close")
}
state := inspectField(c, name, "State.Running")
if state != "false" {
c.Fatal("Container must be stopped after stdin closing")
}
}
// Test run -i --restart xxx doesn't hang
func (s *DockerSuite) TestRunInteractiveWithRestartPolicy(c *testing.T) {
name := "test-inter-restart"
result := icmd.RunCmd(icmd.Cmd{
Command: []string{dockerBinary, "run", "-i", "--name", name, "--restart=always", "busybox", "sh"},
Stdin: bytes.NewBufferString("exit 11"),
})
defer func() {
cli.Docker(cli.Args("stop", name)).Assert(c, icmd.Success)
}()
result.Assert(c, icmd.Expected{ExitCode: 11})
}
// Test for #2267
func (s *DockerSuite) TestRunWriteSpecialFilesAndNotCommit(c *testing.T) {
// Cannot run on Windows as this files are not present in Windows
testRequires(c, DaemonIsLinux)
testRunWriteSpecialFilesAndNotCommit(c, "writehosts", "/etc/hosts")
testRunWriteSpecialFilesAndNotCommit(c, "writehostname", "/etc/hostname")
testRunWriteSpecialFilesAndNotCommit(c, "writeresolv", "/etc/resolv.conf")
}
func testRunWriteSpecialFilesAndNotCommit(c *testing.T, name, path string) {
command := fmt.Sprintf("echo test2267 >> %s && cat %s", path, path)
out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", command)
if !strings.Contains(out, "test2267") {
c.Fatalf("%s should contain 'test2267'", path)
}
out, _ = dockerCmd(c, "diff", name)
if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
c.Fatal("diff should be empty")
}
}
func eqToBaseDiff(out string, c *testing.T) bool {
name := "eqToBaseDiff" + testutil.GenerateRandomAlphaOnlyString(32)
dockerCmd(c, "run", "--name", name, "busybox", "echo", "hello")
cID := getIDByName(c, name)
baseDiff, _ := dockerCmd(c, "diff", cID)
baseArr := strings.Split(baseDiff, "\n")
sort.Strings(baseArr)
outArr := strings.Split(out, "\n")
sort.Strings(outArr)
return sliceEq(baseArr, outArr)
}
func sliceEq(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func (s *DockerSuite) TestRunWithBadDevice(c *testing.T) {
// Cannot run on Windows as Windows does not support --device
testRequires(c, DaemonIsLinux)
name := "baddevice"
out, _, err := dockerCmdWithError("run", "--name", name, "--device", "/etc", "busybox", "true")
if err == nil {
c.Fatal("Run should fail with bad device")
}
expected := `"/etc": not a device node`
if !strings.Contains(out, expected) {
c.Fatalf("Output should contain %q, actual out: %q", expected, out)
}
}
func (s *DockerSuite) TestRunEntrypoint(c *testing.T) {
name := "entrypoint"
out, _ := dockerCmd(c, "run", "--name", name, "--entrypoint", "echo", "busybox", "-n", "foobar")
expected := "foobar"
if out != expected {
c.Fatalf("Output should be %q, actual out: %q", expected, out)
}
}
func (s *DockerSuite) TestRunBindMounts(c *testing.T) {
testRequires(c, testEnv.IsLocalDaemon)
if testEnv.OSType == "linux" {
testRequires(c, DaemonIsLinux, NotUserNamespace)
}
if testEnv.OSType == "windows" {
// Disabled prior to RS5 due to how volumes are mapped
testRequires(c, DaemonIsWindowsAtLeastBuild(osversion.RS5))
}
prefix, _ := getPrefixAndSlashFromDaemonPlatform()
tmpDir, err := os.MkdirTemp("", "docker-test-container")
if err != nil {
c.Fatal(err)
}
defer os.RemoveAll(tmpDir)
writeFile(path.Join(tmpDir, "touch-me"), "", c)
// Test reading from a read-only bind mount
out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:%s/tmpx:ro", tmpDir, prefix), "busybox", "ls", prefix+"/tmpx")
if !strings.Contains(out, "touch-me") {
c.Fatal("Container failed to read from bind mount")
}
// test writing to bind mount
if testEnv.OSType == "windows" {
dockerCmd(c, "run", "-v", fmt.Sprintf(`%s:c:\tmp:rw`, tmpDir), "busybox", "touch", "c:/tmp/holla")
} else {
dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
}
readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
// test mounting to an illegal destination directory
_, _, err = dockerCmdWithError("run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
if err == nil {
c.Fatal("Container bind mounted illegal directory")
}
// Windows does not (and likely never will) support mounting a single file
if testEnv.OSType != "windows" {
// test mount a file
dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
expected := "yotta"
if content != expected {
c.Fatalf("Output should be %q, actual out: %q", expected, content)
}
}
}
// Ensure that CIDFile gets deleted if it's empty
// Perform this test by making `docker run` fail
func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *testing.T) {
// Skip on Windows. Base image on Windows has a CMD set in the image.
testRequires(c, DaemonIsLinux)
tmpDir, err := os.MkdirTemp("", "TestRunCidFile")
if err != nil {
c.Fatal(err)
}
defer os.RemoveAll(tmpDir)
tmpCidFile := path.Join(tmpDir, "cid")
image := "emptyfs"
if testEnv.OSType == "windows" {
// Windows can't support an emptyfs image. Just use the regular Windows image
image = testEnv.PlatformDefaults.BaseImage
}
out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, image)
if err == nil {
c.Fatalf("Run without command must fail. out=%s", out)
} else if !strings.Contains(out, "No command specified") {
c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err)
}
if _, err := os.Stat(tmpCidFile); err == nil {
c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
}
}
// #2098 - Docker cidFiles only contain short version of the containerId
// sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test"
// TestRunCidFile tests that run --cidfile returns the longid
func (s *DockerSuite) TestRunCidFileCheckIDLength(c *testing.T) {
tmpDir, err := os.MkdirTemp("", "TestRunCidFile")
if err != nil {
c.Fatal(err)
}
tmpCidFile := path.Join(tmpDir, "cid")
defer os.RemoveAll(tmpDir)
out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
id := strings.TrimSpace(out)
buffer, err := os.ReadFile(tmpCidFile)
if err != nil {
c.Fatal(err)
}
cid := string(buffer)
if len(cid) != 64 {
c.Fatalf("--cidfile should be a long id, not %q", id)
}
if cid != id {
c.Fatalf("cid must be equal to %s, got %s", id, cid)
}
}
func (s *DockerSuite) TestRunSetMacAddress(c *testing.T) {
skip.If(c, RuntimeIsWindowsContainerd(), "FIXME: Broken on Windows + containerd combination")
mac := "12:34:56:78:9a:bc"
var out string
if testEnv.OSType == "windows" {
out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'")
mac = strings.Replace(strings.ToUpper(mac), ":", "-", -1) // To Windows-style MACs
} else {
out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'")
}
actualMac := strings.TrimSpace(out)
if actualMac != mac {
c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac)
}
}
func (s *DockerSuite) TestRunInspectMacAddress(c *testing.T) {
// TODO Windows. Network settings are not propagated back to inspect.
testRequires(c, DaemonIsLinux)
mac := "12:34:56:78:9a:bc"
out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top")
id := strings.TrimSpace(out)
inspectedMac := inspectField(c, id, "NetworkSettings.Networks.bridge.MacAddress")
if inspectedMac != mac {
c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac)
}
}
// test docker run use an invalid mac address
func (s *DockerSuite) TestRunWithInvalidMacAddress(c *testing.T) {
out, _, err := dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29", "busybox")
// use an invalid mac address should with an error out
if err == nil || !strings.Contains(out, "is not a valid mac address") {
c.Fatalf("run with an invalid --mac-address should with error out")
}
}
func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *testing.T) {
// TODO Windows. Network settings are not propagated back to inspect.
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
out := cli.DockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top").Combined()
id := strings.TrimSpace(out)
ip := inspectField(c, id, "NetworkSettings.Networks.bridge.IPAddress")
icmd.RunCommand("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip),
"!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT").Assert(c, icmd.Success)
cli.DockerCmd(c, "rm", "-fv", id)
cli.DockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
}
func (s *DockerSuite) TestRunPortInUse(c *testing.T) {
// TODO Windows. The duplicate NAT message returned by Windows will be
// changing as is currently completely undecipherable. Does need modifying
// to run sh rather than top though as top isn't in Windows busybox.
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
port := "1234"
dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top")
out, _, err := dockerCmdWithError("run", "-d", "-p", port+":80", "busybox", "top")
if err == nil {
c.Fatalf("Binding on used port must fail")
}
if !strings.Contains(out, "port is already allocated") {
c.Fatalf("Out must be about \"port is already allocated\", got %s", out)
}
}
// https://github.com/docker/docker/issues/12148
func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *testing.T) {
// TODO Windows. -P is not yet supported
testRequires(c, DaemonIsLinux)
// allocate a dynamic port to get the most recent
out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top")
id := strings.TrimSpace(out)
out, _ = dockerCmd(c, "inspect", "--format", `{{index .NetworkSettings.Ports "80/tcp" 0 "HostPort" }}`, id)
out = strings.TrimSpace(out)
port, err := strconv.ParseInt(out, 10, 64)
if err != nil {
c.Fatalf("invalid port, got: %s, error: %s", out, err)
}
// allocate a static port and a dynamic port together, with static port
// takes the next recent port in dynamic port range.
dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top")
}
// Regression test for #7792
func (s *DockerSuite) TestRunMountOrdering(c *testing.T) {
// TODO Windows: Post RS1. Windows does not support nested mounts.
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
prefix, _ := getPrefixAndSlashFromDaemonPlatform()
tmpDir, err := os.MkdirTemp("", "docker_nested_mount_test")
if err != nil {
c.Fatal(err)
}
defer os.RemoveAll(tmpDir)
tmpDir2, err := os.MkdirTemp("", "docker_nested_mount_test2")
if err != nil {
c.Fatal(err)
}
defer os.RemoveAll(tmpDir2)
// Create a temporary tmpfs mounc.
fooDir := filepath.Join(tmpDir, "foo")
if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
c.Fatalf("failed to mkdir at %s - %s", fooDir, err)
}
if err := os.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
c.Fatal(err)
}
if err := os.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
c.Fatal(err)
}
if err := os.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
c.Fatal(err)
}
dockerCmd(c, "run",
"-v", fmt.Sprintf("%s:"+prefix+"/tmp", tmpDir),
"-v", fmt.Sprintf("%s:"+prefix+"/tmp/foo", fooDir),
"-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2", tmpDir2),
"-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2/foo", fooDir),
"busybox:latest", "sh", "-c",
"ls "+prefix+"/tmp/touch-me && ls "+prefix+"/tmp/foo/touch-me && ls "+prefix+"/tmp/tmp2/touch-me && ls "+prefix+"/tmp/tmp2/foo/touch-me")
}
// Regression test for https://github.com/docker/docker/issues/8259
func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *testing.T) {
// Not applicable on Windows as Windows does not support volumes
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
prefix, _ := getPrefixAndSlashFromDaemonPlatform()
tmpDir, err := os.MkdirTemp(os.TempDir(), "testlink")
if err != nil {
c.Fatal(err)
}
defer os.RemoveAll(tmpDir)
linkPath := os.TempDir() + "/testlink2"
if err := os.Symlink(tmpDir, linkPath); err != nil {
c.Fatal(err)
}
defer os.RemoveAll(linkPath)
// Create first container
dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test")
// Create second container with same symlinked path
// This will fail if the referenced issue is hit with a "Volume exists" error
dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test")
}
// GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container
func (s *DockerSuite) TestRunCreateVolumeEtc(c *testing.T) {
// While Windows supports volumes, it does not support --add-host hence
// this test is not applicable on Windows.
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf")
if !strings.Contains(out, "nameserver 127.0.0.1") {
c.Fatal("/etc volume mount hides /etc/resolv.conf")
}
out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname")
if !strings.Contains(out, "test123") {
c.Fatal("/etc volume mount hides /etc/hostname")
}
out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
out = strings.Replace(out, "\n", " ", -1)
if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
c.Fatal("/etc volume mount hides /etc/hosts")
}
}
func (s *DockerSuite) TestVolumesNoCopyData(c *testing.T) {
// TODO Windows (Post RS1). Windows does not support volumes which
// are pre-populated such as is built in the dockerfile used in this test.
testRequires(c, DaemonIsLinux)
prefix, slash := getPrefixAndSlashFromDaemonPlatform()
buildImageSuccessfully(c, "dataimage", build.WithDockerfile(`FROM busybox
RUN ["mkdir", "-p", "/foo"]
RUN ["touch", "/foo/bar"]`))
dockerCmd(c, "run", "--name", "test", "-v", prefix+slash+"foo", "busybox")
if out, _, err := dockerCmdWithError("run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
}
tmpDir := RandomTmpDirPath("docker_test_bind_mount_copy_data", testEnv.OSType)
if out, _, err := dockerCmdWithError("run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
c.Fatalf("Data was copied on bind mount but shouldn't be:\n%q", out)
}
}
func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *testing.T) {
// just run with unknown image
cmd := exec.Command(dockerBinary, "run", "asdfsg")
stdout := bytes.NewBuffer(nil)
cmd.Stdout = stdout
if err := cmd.Run(); err == nil {
c.Fatal("Run with unknown image should fail")
}
if stdout.Len() != 0 {
c.Fatalf("Stdout contains output from pull: %s", stdout)
}
}
func (s *DockerSuite) TestRunVolumesCleanPaths(c *testing.T) {
testRequires(c, testEnv.IsLocalDaemon)
prefix, slash := getPrefixAndSlashFromDaemonPlatform()
buildImageSuccessfully(c, "run_volumes_clean_paths", build.WithDockerfile(`FROM busybox
VOLUME `+prefix+`/foo/`))
dockerCmd(c, "run", "-v", prefix+"/foo", "-v", prefix+"/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
out, err := inspectMountSourceField("dark_helmet", prefix+slash+"foo"+slash)
if err != errMountNotFound {
c.Fatalf("Found unexpected volume entry for '%s/foo/' in volumes\n%q", prefix, out)
}
out, err = inspectMountSourceField("dark_helmet", prefix+slash+`foo`)
assert.NilError(c, err)
if !strings.Contains(strings.ToLower(out), strings.ToLower(testEnv.PlatformDefaults.VolumesConfigPath)) {
c.Fatalf("Volume was not defined for %s/foo\n%q", prefix, out)
}
out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar"+slash)
if err != errMountNotFound {
c.Fatalf("Found unexpected volume entry for '%s/bar/' in volumes\n%q", prefix, out)
}
out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar")
assert.NilError(c, err)
if !strings.Contains(strings.ToLower(out), strings.ToLower(testEnv.PlatformDefaults.VolumesConfigPath)) {
c.Fatalf("Volume was not defined for %s/bar\n%q", prefix, out)
}
}
// Regression test for #3631
func (s *DockerSuite) TestRunSlowStdoutConsumer(c *testing.T) {
// TODO Windows: This should be able to run on Windows if can find an
// alternate to /dev/zero and /dev/stdout.
testRequires(c, DaemonIsLinux)
args := []string{"run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | cat -v"}
cont := exec.Command(dockerBinary, args...)
stdout, err := cont.StdoutPipe()
if err != nil {
c.Fatal(err)
}
if err := cont.Start(); err != nil {
c.Fatal(err)
}
defer func() { go cont.Wait() }()
n, err := ConsumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil)
if err != nil {
c.Fatal(err)
}
expected := 2 * 1024 * 2000
if n != expected {
c.Fatalf("Expected %d, got %d", expected, n)
}
}
func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *testing.T) {
// TODO Windows: -P is not currently supported. Also network
// settings are not propagated back.
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
id := strings.TrimSpace(out)
portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports")
var ports nat.PortMap
if err := json.Unmarshal([]byte(portstr), &ports); err != nil {
c.Fatal(err)
}
for port, binding := range ports {
portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
if portnum < 3000 || portnum > 3003 {
c.Fatalf("Port %d is out of range ", portnum)
}
if len(binding) == 0 || len(binding[0].HostPort) == 0 {
c.Fatalf("Port is not mapped for the port %s", port)
}
}
}
func (s *DockerSuite) TestRunExposePort(c *testing.T) {
out, _, err := dockerCmdWithError("run", "--expose", "80000", "busybox")
assert.Assert(c, err != nil, "--expose with an invalid port should error out")
assert.Assert(c, strings.Contains(out, "invalid range format for --expose"))
}
func (s *DockerSuite) TestRunModeIpcHost(c *testing.T) {
// Not applicable on Windows as uses Unix-specific capabilities
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
hostIpc, err := os.Readlink("/proc/1/ns/ipc")
if err != nil {
c.Fatal(err)
}
out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
out = strings.Trim(out, "\n")
if hostIpc != out {
c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out)
}
out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc")
out = strings.Trim(out, "\n")
if hostIpc == out {
c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out)
}
}
func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *testing.T) {
// Not applicable on Windows as uses Unix-specific capabilities
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
if !strings.Contains(out, "abcd1234") || err == nil {
c.Fatalf("run IPC from a non exists container should with correct error out")
}
}
func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *testing.T) {
// Not applicable on Windows as uses Unix-specific capabilities
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
out, _ := dockerCmd(c, "create", "busybox")
id := strings.TrimSpace(out)
out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox")
if err == nil {
c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err)
}
}
func (s *DockerSuite) TestRunModePIDContainer(c *testing.T) {
// Not applicable on Windows as uses Unix-specific capabilities
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "top")
id := strings.TrimSpace(out)
state := inspectField(c, id, "State.Running")
if state != "true" {
c.Fatal("Container state is 'not running'")
}
pid1 := inspectField(c, id, "State.Pid")
parentContainerPid, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/pid", pid1))
if err != nil {
c.Fatal(err)
}
out, _ = dockerCmd(c, "run", fmt.Sprintf("--pid=container:%s", id), "busybox", "readlink", "/proc/self/ns/pid")
out = strings.Trim(out, "\n")
if parentContainerPid != out {
c.Fatalf("PID different with --pid=container:%s %s != %s\n", id, parentContainerPid, out)
}
}
func (s *DockerSuite) TestRunModePIDContainerNotExists(c *testing.T) {
// Not applicable on Windows as uses Unix-specific capabilities
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "-d", "--pid", "container:abcd1234", "busybox", "top")
if !strings.Contains(out, "abcd1234") || err == nil {
c.Fatalf("run PID from a non exists container should with correct error out")
}
}
func (s *DockerSuite) TestRunModePIDContainerNotRunning(c *testing.T) {
// Not applicable on Windows as uses Unix-specific capabilities
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
out, _ := dockerCmd(c, "create", "busybox")
id := strings.TrimSpace(out)
out, _, err := dockerCmdWithError("run", fmt.Sprintf("--pid=container:%s", id), "busybox")
if err == nil {
c.Fatalf("Run container with pid mode container should fail with non running container: %s\n%s", out, err)
}
}
func (s *DockerSuite) TestRunMountShmMqueueFromHost(c *testing.T) {
// Not applicable on Windows as uses Unix-specific capabilities
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
dockerCmd(c, "run", "-d", "--name", "shmfromhost", "-v", "/dev/shm:/dev/shm", "-v", "/dev/mqueue:/dev/mqueue", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && touch /dev/mqueue/toto && top")
defer os.Remove("/dev/mqueue/toto")
defer os.Remove("/dev/shm/test")
volPath, err := inspectMountSourceField("shmfromhost", "/dev/shm")
assert.NilError(c, err)
if volPath != "/dev/shm" {
c.Fatalf("volumePath should have been /dev/shm, was %s", volPath)
}
out, _ := dockerCmd(c, "run", "--name", "ipchost", "--ipc", "host", "busybox", "cat", "/dev/shm/test")
if out != "test" {
c.Fatalf("Output of /dev/shm/test expected test but found: %s", out)
}
// Check that the mq was created
if _, err := os.Stat("/dev/mqueue/toto"); err != nil {
c.Fatalf("Failed to confirm '/dev/mqueue/toto' presence on host: %s", err.Error())
}
}
func (s *DockerSuite) TestContainerNetworkMode(c *testing.T) {
// Not applicable on Windows as uses Unix-specific capabilities
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
id := strings.TrimSpace(out)
assert.NilError(c, waitRun(id))
pid1 := inspectField(c, id, "State.Pid")
parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
if err != nil {
c.Fatal(err)
}
out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
out = strings.Trim(out, "\n")
if parentContainerNet != out {
c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out)
}
}
func (s *DockerSuite) TestRunModeUTSHost(c *testing.T) {
// Not applicable on Windows as uses Unix-specific capabilities
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
hostUTS, err := os.Readlink("/proc/1/ns/uts")
if err != nil {
c.Fatal(err)
}
out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts")
out = strings.Trim(out, "\n")
if hostUTS != out {
c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out)
}
out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts")
out = strings.Trim(out, "\n")
if hostUTS == out {
c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out)
}
out, _ = dockerCmdWithFail(c, "run", "-h=name", "--uts=host", "busybox", "ps")
assert.Assert(c, strings.Contains(out, runconfig.ErrConflictUTSHostname.Error()))
}
func (s *DockerSuite) TestRunTLSVerify(c *testing.T) {
// Remote daemons use TLS and this test is not applicable when TLS is required.
testRequires(c, testEnv.IsLocalDaemon)
if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 {
c.Fatalf("Should have worked: %v:\n%v", err, out)
}
// Regardless of whether we specify true or false we need to
// test to make sure tls is turned on if --tlsverify is specified at all
result := dockerCmdWithResult("--tlsverify=false", "ps")
result.Assert(c, icmd.Expected{ExitCode: 1, Err: "error during connect"})
result = dockerCmdWithResult("--tlsverify=true", "ps")
result.Assert(c, icmd.Expected{ExitCode: 1, Err: "cert"})
}
func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *testing.T) {
// TODO Windows. Once moved to libnetwork/CNM, this may be able to be
// re-instated.
testRequires(c, DaemonIsLinux)
// first find allocator current position
out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
id := strings.TrimSpace(out)
out, _ = dockerCmd(c, "inspect", "--format", `{{index .NetworkSettings.Ports "80/tcp" 0 "HostPort" }}`, id)
out = strings.TrimSpace(out)
if out == "" {
c.Fatal("docker port command output is empty")
}
lastPort, err := strconv.Atoi(out)
if err != nil {
c.Fatal(err)
}
port := lastPort + 1
l, err := net.Listen("tcp", ":"+strconv.Itoa(port))
if err != nil {
c.Fatal(err)
}
defer l.Close()
out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
id = strings.TrimSpace(out)
dockerCmd(c, "port", id)
}
func (s *DockerSuite) TestRunTTYWithPipe(c *testing.T) {
errChan := make(chan error, 1)
go func() {
defer close(errChan)
cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true")
if _, err := cmd.StdinPipe(); err != nil {
errChan <- err
return
}
expected := "the input device is not a TTY"
if runtime.GOOS == "windows" {
expected += ". If you are using mintty, try prefixing the command with 'winpty'"
}
if out, _, err := runCommandWithOutput(cmd); err == nil {
errChan <- fmt.Errorf("run should have failed")
return
} else if !strings.Contains(out, expected) {
errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected)
return
}
}()
select {
case err := <-errChan:
assert.NilError(c, err)
case <-time.After(30 * time.Second):
c.Fatal("container is running but should have failed")
}
}
func (s *DockerSuite) TestRunNonLocalMacAddress(c *testing.T) {
addr := "00:16:3E:08:00:50"
args := []string{"run", "--mac-address", addr}
expected := addr
if testEnv.OSType != "windows" {
args = append(args, "busybox", "ifconfig")
} else {
args = append(args, testEnv.PlatformDefaults.BaseImage, "ipconfig", "/all")
expected = strings.Replace(strings.ToUpper(addr), ":", "-", -1)
}
if out, _ := dockerCmd(c, args...); !strings.Contains(out, expected) {
c.Fatalf("Output should have contained %q: %s", expected, out)
}
}
func (s *DockerSuite) TestRunNetHost(c *testing.T) {
// Not applicable on Windows as uses Unix-specific capabilities
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
hostNet, err := os.Readlink("/proc/1/ns/net")
if err != nil {
c.Fatal(err)
}
out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
out = strings.Trim(out, "\n")
if hostNet != out {
c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out)
}
out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net")
out = strings.Trim(out, "\n")
if hostNet == out {
c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out)
}
}
func (s *DockerSuite) TestRunNetHostTwiceSameName(c *testing.T) {
// TODO Windows. As Windows networking evolves and converges towards
// CNM, this test may be possible to enable on Windows.
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
}
func (s *DockerSuite) TestRunNetContainerWhichHost(c *testing.T) {
// Not applicable on Windows as uses Unix-specific capabilities
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
hostNet, err := os.Readlink("/proc/1/ns/net")
if err != nil {
c.Fatal(err)
}
dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top")
out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
out = strings.Trim(out, "\n")
if hostNet != out {
c.Fatalf("Container should have host network namespace")
}
}
func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *testing.T) {
// TODO Windows. This may be possible to enable in the future. However,
// Windows does not currently support --expose, or populate the network
// settings seen through inspect.
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
id := strings.TrimSpace(out)
portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports")
var ports nat.PortMap
err := json.Unmarshal([]byte(portstr), &ports)
assert.NilError(c, err, "failed to unmarshal: %v", portstr)
for port, binding := range ports {
portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
if portnum < 3000 || portnum > 3003 {
c.Fatalf("Port %d is out of range ", portnum)
}
if len(binding) == 0 || len(binding[0].HostPort) == 0 {
c.Fatal("Port is not mapped for the port "+port, out)
}
}
}
func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *testing.T) {
runSleepingContainer(c, "--name=testrunsetdefaultrestartpolicy")
out := inspectField(c, "testrunsetdefaultrestartpolicy", "HostConfig.RestartPolicy.Name")
if out != "no" {
c.Fatalf("Set default restart policy failed")
}
}
func (s *DockerSuite) TestRunRestartMaxRetries(c *testing.T) {
out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
timeout := 10 * time.Second
if testEnv.OSType == "windows" {
timeout = 120 * time.Second
}
id := strings.TrimSpace(out)
if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", timeout); err != nil {
c.Fatal(err)
}
count := inspectField(c, id, "RestartCount")
if count != "3" {
c.Fatalf("Container was restarted %s times, expected %d", count, 3)
}
MaximumRetryCount := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount")
if MaximumRetryCount != "3" {
c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3")
}
}
func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *testing.T) {
dockerCmd(c, "run", "--rm", "busybox", "touch", "/file")
}
func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *testing.T) {
// Not applicable on Windows which does not support --read-only
testRequires(c, DaemonIsLinux, UserNamespaceROMount)
testPriv := true
// don't test privileged mode subtest if user namespaces enabled
if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
testPriv = false
}
testReadOnlyFile(c, testPriv, "/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname")
}
func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *testing.T) {
// Not applicable on Windows due to use of Unix specific functionality, plus
// the use of --read-only which is not supported.
testRequires(c, DaemonIsLinux, UserNamespaceROMount)
// Ensure we have not broken writing /dev/pts
out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount")
if status != 0 {
c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.")
}
expected := "type devpts (rw,"
if !strings.Contains(out, expected) {
c.Fatalf("expected output to contain %s but contains %s", expected, out)
}
}
func testReadOnlyFile(c *testing.T, testPriv bool, filenames ...string) {
touch := "touch " + strings.Join(filenames, " ")
out, _, err := dockerCmdWithError("run", "--read-only", "--rm", "busybox", "sh", "-c", touch)
assert.ErrorContains(c, err, "")
for _, f := range filenames {
expected := "touch: " + f + ": Read-only file system"
assert.Assert(c, strings.Contains(out, expected))
}
if !testPriv {
return
}
out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--rm", "busybox", "sh", "-c", touch)
assert.ErrorContains(c, err, "")
for _, f := range filenames {
expected := "touch: " + f + ": Read-only file system"
assert.Assert(c, strings.Contains(out, expected))
}
}
func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *testing.T) {
// Not applicable on Windows which does not support --link
testRequires(c, DaemonIsLinux, UserNamespaceROMount)
dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top")
out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts")
if !strings.Contains(out, "testlinked") {
c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled")
}
}
func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDNSFlag(c *testing.T) {
// Not applicable on Windows which does not support either --read-only or --dns.
testRequires(c, DaemonIsLinux, UserNamespaceROMount)
out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf")
if !strings.Contains(out, "1.1.1.1") {
c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used")
}
}
func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *testing.T) {
// Not applicable on Windows which does not support --read-only
testRequires(c, DaemonIsLinux, UserNamespaceROMount)
out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts")
if !strings.Contains(out, "testreadonly") {
c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used")
}
}
func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *testing.T) {
prefix, _ := getPrefixAndSlashFromDaemonPlatform()
runSleepingContainer(c, "--name=voltest", "-v", prefix+"/foo")
runSleepingContainer(c, "--name=restarter", "--volumes-from", "voltest")
// Remove the main volume container and restart the consuming container
dockerCmd(c, "rm", "-f", "voltest")
// This should not fail since the volumes-from were already applied
dockerCmd(c, "restart", "restarter")
}
// run container with --rm should remove container if exit code != 0
func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *testing.T) {
existingContainers := ExistingContainerIDs(c)
name := "flowers"
cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "ls", "/notexists")).Assert(c, icmd.Expected{
ExitCode: 1,
})
out := cli.DockerCmd(c, "ps", "-q", "-a").Combined()
out = RemoveOutputForExistingElements(out, existingContainers)
if out != "" {
c.Fatal("Expected not to have containers", out)
}
}
func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *testing.T) {
existingContainers := ExistingContainerIDs(c)
name := "sparkles"
cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "commandNotFound")).Assert(c, icmd.Expected{
ExitCode: 127,
})
out := cli.DockerCmd(c, "ps", "-q", "-a").Combined()
out = RemoveOutputForExistingElements(out, existingContainers)
if out != "" {
c.Fatal("Expected not to have containers", out)
}
}
func (s *DockerSuite) TestRunPIDHostWithChildIsKillable(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux, NotUserNamespace)
name := "ibuildthecloud"
dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi")
assert.Assert(c, waitRun(name) == nil)
errchan := make(chan error, 1)
go func() {
if out, _, err := dockerCmdWithError("kill", name); err != nil {
errchan <- fmt.Errorf("%v:\n%s", err, out)
}
close(errchan)
}()
select {
case err := <-errchan:
assert.NilError(c, err)
case <-time.After(5 * time.Second):
c.Fatal("Kill container timed out")
}
}
func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *testing.T) {
// TODO Windows. This may be possible to enable once Windows supports memory limits on containers
testRequires(c, DaemonIsLinux)
// this memory limit is 1 byte less than the min (daemon.linuxMinMemory), which is 6MB (6291456 bytes)
out, _, err := dockerCmdWithError("create", "-m", "6291455", "busybox")
if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 6MB") {
c.Fatalf("expected run to fail when using too low a memory limit: %q", out)
}
}
func (s *DockerSuite) TestRunWriteToProcAsound(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux)
_, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version")
if err == nil || code == 0 {
c.Fatal("standard container should not be able to write to /proc/asound")
}
}
func (s *DockerSuite) TestRunReadProcTimer(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux)
out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats")
if code != 0 {
return
}
if err != nil {
c.Fatal(err)
}
if strings.Trim(out, "\n ") != "" {
c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out)
}
}
func (s *DockerSuite) TestRunReadProcLatency(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux)
// some kernels don't have this configured so skip the test if this file is not found
// on the host running the tests.
if _, err := os.Stat("/proc/latency_stats"); err != nil {
c.Skip("kernel doesn't have latency_stats configured")
return
}
out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats")
if code != 0 {
return
}
if err != nil {
c.Fatal(err)
}
if strings.Trim(out, "\n ") != "" {
c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out)
}
}
func (s *DockerSuite) TestRunReadFilteredProc(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
testReadPaths := []string{
"/proc/latency_stats",
"/proc/timer_stats",
"/proc/kcore",
}
for i, filePath := range testReadPaths {
name := fmt.Sprintf("procsieve-%d", i)
shellCmd := fmt.Sprintf("exec 3<%s", filePath)
out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
if exitCode != 0 {
return
}
if err != nil {
c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err)
}
}
}
func (s *DockerSuite) TestMountIntoProc(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux)
_, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true")
if err == nil || code == 0 {
c.Fatal("container should not be able to mount into /proc")
}
}
func (s *DockerSuite) TestMountIntoSys(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux)
testRequires(c, NotUserNamespace)
dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true")
}
func (s *DockerSuite) TestRunUnshareProc(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
// In this test goroutines are used to run test cases in parallel to prevent the test from taking a long time to run.
errChan := make(chan error)
go func() {
name := "acidburn"
out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:bullseye-slim", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount")
if err == nil ||
!(strings.Contains(strings.ToLower(out), "permission denied") ||
strings.Contains(strings.ToLower(out), "operation not permitted")) {
errChan <- fmt.Errorf("unshare with --mount-proc should have failed with 'permission denied' or 'operation not permitted', got: %s, %v", out, err)
} else {
errChan <- nil
}
}()
go func() {
name := "cereal"
out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:bullseye-slim", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc")
if err == nil ||
!(strings.Contains(strings.ToLower(out), "mount: cannot mount none") ||
strings.Contains(strings.ToLower(out), "permission denied") ||
strings.Contains(strings.ToLower(out), "operation not permitted")) {
errChan <- fmt.Errorf("unshare and mount of /proc should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err)
} else {
errChan <- nil
}
}()
/* Ensure still fails if running privileged with the default policy */
go func() {
name := "crashoverride"
out, _, err := dockerCmdWithError("run", "--privileged", "--security-opt", "seccomp=unconfined", "--security-opt", "apparmor=docker-default", "--name", name, "debian:bullseye-slim", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc")
if err == nil ||
!(strings.Contains(strings.ToLower(out), "mount: cannot mount none") ||
strings.Contains(strings.ToLower(out), "permission denied") ||
strings.Contains(strings.ToLower(out), "operation not permitted")) {
errChan <- fmt.Errorf("privileged unshare with apparmor should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err)
} else {
errChan <- nil
}
}()
var retErr error
for i := 0; i < 3; i++ {
err := <-errChan
if retErr == nil && err != nil {
retErr = err
}
}
if retErr != nil {
c.Fatal(retErr)
}
}
func (s *DockerSuite) TestRunPublishPort(c *testing.T) {
// TODO Windows: This may be possible once Windows moves to libnetwork and CNM
testRequires(c, DaemonIsLinux)
dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top")
out, _ := dockerCmd(c, "port", "test")
out = strings.Trim(out, "\r\n")
if out != "" {
c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out)
}
}
// Issue #10184.
func (s *DockerSuite) TestDevicePermissions(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux)
const permissions = "crw-rw-rw-"
out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse")
if status != 0 {
c.Fatalf("expected status 0, got %d", status)
}
if !strings.HasPrefix(out, permissions) {
c.Fatalf("output should begin with %q, got %q", permissions, out)
}
}
func (s *DockerSuite) TestRunCapAddCHOWN(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
if actual := strings.Trim(out, "\r\n"); actual != "ok" {
c.Fatalf("expected output ok received %s", actual)
}
}
// https://github.com/docker/docker/pull/14498
func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *testing.T) {
prefix, slash := getPrefixAndSlashFromDaemonPlatform()
dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "true")
dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true")
dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true")
if testEnv.OSType != "windows" {
mRO, err := inspectMountPoint("test-volumes-1", prefix+slash+"test")
assert.NilError(c, err, "failed to inspect mount point")
if mRO.RW {
c.Fatalf("Expected RO volume was RW")
}
}
mRW, err := inspectMountPoint("test-volumes-2", prefix+slash+"test")
assert.NilError(c, err, "failed to inspect mount point")
if !mRW.RW {
c.Fatalf("Expected RW volume was RO")
}
}
func (s *DockerSuite) TestRunWriteFilteredProc(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
testWritePaths := []string{
/* modprobe and core_pattern should both be denied by generic
* policy of denials for /proc/sys/kernel. These files have been
* picked to be checked as they are particularly sensitive to writes */
"/proc/sys/kernel/modprobe",
"/proc/sys/kernel/core_pattern",
"/proc/sysrq-trigger",
"/proc/kcore",
}
for i, filePath := range testWritePaths {
name := fmt.Sprintf("writeprocsieve-%d", i)
shellCmd := fmt.Sprintf("exec 3>%s", filePath)
out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
if code != 0 {
return
}
if err != nil {
c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err)
}
}
}
func (s *DockerSuite) TestRunNetworkFilesBindMount(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
expected := "test123"
filename := createTmpFile(c, expected)
defer os.Remove(filename)
// for user namespaced test runs, the temp file must be accessible to unprivileged root
if err := os.Chmod(filename, 0646); err != nil {
c.Fatalf("error modifying permissions of %s: %v", filename, err)
}
nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
for i := range nwfiles {
actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i])
if actual != expected {
c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual)
}
}
}
func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
filename := createTmpFile(c, "test123")
defer os.Remove(filename)
// for user namespaced test runs, the temp file must be accessible to unprivileged root
if err := os.Chmod(filename, 0646); err != nil {
c.Fatalf("error modifying permissions of %s: %v", filename, err)
}
nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
for i := range nwfiles {
_, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i])
if err == nil || exitCode == 0 {
c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode)
}
}
}
func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, UserNamespaceROMount)
filename := createTmpFile(c, "test123")
defer os.Remove(filename)
// for user namespaced test runs, the temp file must be accessible to unprivileged root
if err := os.Chmod(filename, 0646); err != nil {
c.Fatalf("error modifying permissions of %s: %v", filename, err)
}
nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
for i := range nwfiles {
_, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i])
if exitCode != 0 {
c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
}
}
for i := range nwfiles {
_, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i])
if err == nil || exitCode == 0 {
c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
}
}
}
func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
id := strings.TrimSpace(out)
assert.NilError(c, waitRun(id))
pid1 := inspectField(c, id, "State.Pid")
_, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
if err != nil {
c.Fatal(err)
}
}
func (s *DockerSuite) TestAppArmorDeniesPtrace(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, testEnv.IsLocalDaemon, Apparmor, DaemonIsLinux)
// Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace
// itself, but pid>1 should not be able to trace pid1.
_, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "sh -c readlink /proc/1/ns/net")
if exitCode == 0 {
c.Fatal("ptrace was not successfully restricted by AppArmor")
}
}
func (s *DockerSuite) TestAppArmorTraceSelf(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, Apparmor)
_, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net")
if exitCode != 0 {
c.Fatal("ptrace of self failed.")
}
}
func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, testEnv.IsLocalDaemon, Apparmor, DaemonIsLinux, NotUserNamespace)
_, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo")
if exitCode == 0 {
// If our test failed, attempt to repair the host system...
_, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "444", "/proc/cpuinfo")
if exitCode == 0 {
c.Fatal("AppArmor was unsuccessful in prohibiting chmod of /proc/* files.")
}
}
}
func (s *DockerSuite) TestRunCapAddSYSTIME(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux)
dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$")
}
// run create container failed should clean up the container
func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *testing.T) {
// TODO Windows. This may be possible to enable once link is supported
testRequires(c, DaemonIsLinux)
name := "unique_name"
_, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox")
assert.Assert(c, err != nil, "Expected docker run to fail!")
containerID, err := inspectFieldWithError(name, "Id")
assert.Assert(c, err != nil, "Expected not to have this container: %s!", containerID)
assert.Equal(c, containerID, "", fmt.Sprintf("Expected not to have this container: %s!", containerID))
}
func (s *DockerSuite) TestRunNamedVolume(c *testing.T) {
prefix, _ := getPrefixAndSlashFromDaemonPlatform()
testRequires(c, DaemonIsLinux)
dockerCmd(c, "run", "--name=test", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "echo hello > "+prefix+"/foo/bar")
out, _ := dockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar")
assert.Equal(c, strings.TrimSpace(out), "hello")
out, _ = dockerCmd(c, "run", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar")
assert.Equal(c, strings.TrimSpace(out), "hello")
}
func (s *DockerSuite) TestRunWithUlimits(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n")
ul := strings.TrimSpace(out)
if ul != "42" {
c.Fatalf("expected `ulimit -n` to be 42, got %s", ul)
}
}
func (s *DockerSuite) TestRunContainerWithCgroupParent(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux)
// cgroup-parent relative path
testRunContainerWithCgroupParent(c, "test", "cgroup-test")
// cgroup-parent absolute path
testRunContainerWithCgroupParent(c, "/cgroup-parent/test", "cgroup-test-absolute")
}
func testRunContainerWithCgroupParent(c *testing.T, cgroupParent, name string) {
out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
if err != nil {
c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err)
}
cgroupPaths := ParseCgroupPaths(out)
if len(cgroupPaths) == 0 {
c.Fatalf("unexpected output - %q", out)
}
id := getIDByName(c, name)
expectedCgroup := path.Join(cgroupParent, id)
found := false
for _, path := range cgroupPaths {
if strings.HasSuffix(path, expectedCgroup) {
found = true
break
}
}
if !found {
c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
}
}
// TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /.
func (s *DockerSuite) TestRunInvalidCgroupParent(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
testRequires(c, DaemonIsLinux)
testRunInvalidCgroupParent(c, "../../../../../../../../SHOULD_NOT_EXIST", "SHOULD_NOT_EXIST", "cgroup-invalid-test")
testRunInvalidCgroupParent(c, "/../../../../../../../../SHOULD_NOT_EXIST", "/SHOULD_NOT_EXIST", "cgroup-absolute-invalid-test")
}
func testRunInvalidCgroupParent(c *testing.T, cgroupParent, cleanCgroupParent, name string) {
out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
if err != nil {
// XXX: This may include a daemon crash.
c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err)
}
// We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue.
if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) {
c.Fatalf("SECURITY: --cgroup-parent with ../../ relative paths cause files to be created in the host (this is bad) !!")
}
cgroupPaths := ParseCgroupPaths(out)
if len(cgroupPaths) == 0 {
c.Fatalf("unexpected output - %q", out)
}
id := getIDByName(c, name)
expectedCgroup := path.Join(cleanCgroupParent, id)
found := false
for _, path := range cgroupPaths {
if strings.HasSuffix(path, expectedCgroup) {
found = true
break
}
}
if !found {
c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
}
}
func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *testing.T) {
// Not applicable on Windows as uses Unix specific functionality
// --read-only + userns has remount issues
testRequires(c, DaemonIsLinux, NotUserNamespace)
filename := "/sys/fs/cgroup/devices/test123"
out, _, err := dockerCmdWithError("run", "busybox", "touch", filename)
if err == nil {
c.Fatal("expected cgroup mount point to be read-only, touch file should fail")
}
expected := "Read-only file system"
if !strings.Contains(out, expected) {
c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
}
}
func (s *DockerSuite) TestRunContainerNetworkModeToSelf(c *testing.T) {
// Not applicable on Windows which does not support --net=container
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "--name=me", "--net=container:me", "busybox", "true")
if err == nil || !strings.Contains(out, "cannot join own network") {
c.Fatalf("using container net mode to self should result in an error\nerr: %q\nout: %s", err, out)
}
}
func (s *DockerSuite) TestRunContainerNetModeWithDNSMacHosts(c *testing.T) {
// Not applicable on Windows which does not support --net=container
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "-d", "--name", "parent", "busybox", "top")
if err != nil {
c.Fatalf("failed to run container: %v, output: %q", err, out)
}
out, _, err = dockerCmdWithError("run", "--dns", "1.2.3.4", "--net=container:parent", "busybox")
if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkAndDNS.Error()) {
c.Fatalf("run --net=container with --dns should error out")
}
out, _, err = dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox")
if err == nil || !strings.Contains(out, runconfig.ErrConflictContainerNetworkAndMac.Error()) {
c.Fatalf("run --net=container with --mac-address should error out")
}
out, _, err = dockerCmdWithError("run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox")
if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkHosts.Error()) {
c.Fatalf("run --net=container with --add-host should error out")
}
}
func (s *DockerSuite) TestRunContainerNetModeWithExposePort(c *testing.T) {
// Not applicable on Windows which does not support --net=container
testRequires(c, DaemonIsLinux)
dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top")
out, _, err := dockerCmdWithError("run", "-p", "5000:5000", "--net=container:parent", "busybox")
if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) {
c.Fatalf("run --net=container with -p should error out")
}
out, _, err = dockerCmdWithError("run", "-P", "--net=container:parent", "busybox")
if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) {
c.Fatalf("run --net=container with -P should error out")
}
out, _, err = dockerCmdWithError("run", "--expose", "5000", "--net=container:parent", "busybox")
if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkExposePorts.Error()) {
c.Fatalf("run --net=container with --expose should error out")
}
}
func (s *DockerSuite) TestRunLinkToContainerNetMode(c *testing.T) {
// Not applicable on Windows which does not support --net=container or --link
testRequires(c, DaemonIsLinux)
dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top")
dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top")
dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top")
dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top")
dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top")
}
func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *testing.T) {
// TODO Windows: This may be possible to convert.
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
var (
count = 0
parts = strings.Split(out, "\n")
)
for _, l := range parts {
if l != "" {
count++
}
}
if count != 1 {
c.Fatalf("Wrong interface count in container %d", count)
}
if !strings.HasPrefix(out, "1: lo") {
c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out)
}
}
// Issue #4681
func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *testing.T) {
if testEnv.OSType == "windows" {
dockerCmd(c, "run", "--net=none", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1")
} else {
dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1")
}
}
func (s *DockerSuite) TestRunModeNetContainerHostname(c *testing.T) {
// Windows does not support --net=container
testRequires(c, DaemonIsLinux)
dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top")
out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname")
out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname")
if out1 != out {
c.Fatal("containers with shared net namespace should have same hostname")
}
}
func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *testing.T) {
// TODO Windows: Network settings are not currently propagated. This may
// be resolved in the future with the move to libnetwork and CNM.
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top")
id := strings.TrimSpace(out)
res := inspectField(c, id, "NetworkSettings.Networks.none.IPAddress")
if res != "" {
c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res)
}
}
func (s *DockerSuite) TestTwoContainersInNetHost(c *testing.T) {
// Not applicable as Windows does not support --net=host
testRequires(c, DaemonIsLinux, NotUserNamespace, NotUserNamespace)
dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top")
dockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top")
dockerCmd(c, "stop", "first")
dockerCmd(c, "stop", "second")
}
func (s *DockerSuite) TestContainersInUserDefinedNetwork(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork")
dockerCmd(c, "run", "-d", "--net=testnetwork", "--name=first", "busybox", "top")
assert.Assert(c, waitRun("first") == nil)
dockerCmd(c, "run", "-t", "--net=testnetwork", "--name=second", "busybox", "ping", "-c", "1", "first")
}
func (s *DockerSuite) TestContainersInMultipleNetworks(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
// Create 2 networks using bridge driver
dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
// Run and connect containers to testnetwork1
dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
assert.Assert(c, waitRun("first") == nil)
dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
assert.Assert(c, waitRun("second") == nil)
// Check connectivity between containers in testnetwork2
dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
// Connect containers to testnetwork2
dockerCmd(c, "network", "connect", "testnetwork2", "first")
dockerCmd(c, "network", "connect", "testnetwork2", "second")
// Check connectivity between containers
dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
}
func (s *DockerSuite) TestContainersNetworkIsolation(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
// Create 2 networks using bridge driver
dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
// Run 1 container in testnetwork1 and another in testnetwork2
dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
assert.Assert(c, waitRun("first") == nil)
dockerCmd(c, "run", "-d", "--net=testnetwork2", "--name=second", "busybox", "top")
assert.Assert(c, waitRun("second") == nil)
// Check Isolation between containers : ping must fail
_, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
assert.ErrorContains(c, err, "")
// Connect first container to testnetwork2
dockerCmd(c, "network", "connect", "testnetwork2", "first")
// ping must succeed now
_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
assert.NilError(c, err)
// Disconnect first container from testnetwork2
dockerCmd(c, "network", "disconnect", "testnetwork2", "first")
// ping must fail again
_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
assert.ErrorContains(c, err, "")
}
func (s *DockerSuite) TestNetworkRmWithActiveContainers(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace)
// Create 2 networks using bridge driver
dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
// Run and connect containers to testnetwork1
dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
assert.Assert(c, waitRun("first") == nil)
dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
assert.Assert(c, waitRun("second") == nil)
// Network delete with active containers must fail
_, _, err := dockerCmdWithError("network", "rm", "testnetwork1")
assert.ErrorContains(c, err, "")
dockerCmd(c, "stop", "first")
_, _, err = dockerCmdWithError("network", "rm", "testnetwork1")
assert.ErrorContains(c, err, "")
}
func (s *DockerSuite) TestContainerRestartInMultipleNetworks(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
// Create 2 networks using bridge driver
dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
// Run and connect containers to testnetwork1
dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
assert.Assert(c, waitRun("first") == nil)
dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
assert.Assert(c, waitRun("second") == nil)
// Check connectivity between containers in testnetwork2
dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
// Connect containers to testnetwork2
dockerCmd(c, "network", "connect", "testnetwork2", "first")
dockerCmd(c, "network", "connect", "testnetwork2", "second")
// Check connectivity between containers
dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
// Stop second container and test ping failures on both networks
dockerCmd(c, "stop", "second")
_, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork1")
assert.ErrorContains(c, err, "")
_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork2")
assert.ErrorContains(c, err, "")
// Start second container and connectivity must be restored on both networks
dockerCmd(c, "start", "second")
dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
}
func (s *DockerSuite) TestContainerWithConflictingHostNetworks(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace)
// Run a container with --net=host
dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top")
assert.Assert(c, waitRun("first") == nil)
// Create a network using bridge driver
dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
// Connecting to the user defined network must fail
_, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first")
assert.ErrorContains(c, err, "")
}
func (s *DockerSuite) TestContainerWithConflictingSharedNetwork(c *testing.T) {
testRequires(c, DaemonIsLinux)
dockerCmd(c, "run", "-d", "--name=first", "busybox", "top")
assert.Assert(c, waitRun("first") == nil)
// Run second container in first container's network namespace
dockerCmd(c, "run", "-d", "--net=container:first", "--name=second", "busybox", "top")
assert.Assert(c, waitRun("second") == nil)
// Create a network using bridge driver
dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
// Connecting to the user defined network must fail
out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "second")
assert.ErrorContains(c, err, "")
assert.Assert(c, strings.Contains(out, runconfig.ErrConflictSharedNetwork.Error()))
}
func (s *DockerSuite) TestContainerWithConflictingNoneNetwork(c *testing.T) {
testRequires(c, DaemonIsLinux)
dockerCmd(c, "run", "-d", "--net=none", "--name=first", "busybox", "top")
assert.Assert(c, waitRun("first") == nil)
// Create a network using bridge driver
dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
// Connecting to the user defined network must fail
out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first")
assert.ErrorContains(c, err, "")
assert.Assert(c, strings.Contains(out, runconfig.ErrConflictNoNetwork.Error()))
// create a container connected to testnetwork1
dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
assert.Assert(c, waitRun("second") == nil)
// Connect second container to none network. it must fail as well
_, _, err = dockerCmdWithError("network", "connect", "none", "second")
assert.ErrorContains(c, err, "")
}
// #11957 - stdin with no tty does not exit if stdin is not closed even though container exited
func (s *DockerSuite) TestRunStdinBlockedAfterContainerExit(c *testing.T) {
cmd := exec.Command(dockerBinary, "run", "-i", "--name=test", "busybox", "true")
in, err := cmd.StdinPipe()
assert.NilError(c, err)
defer in.Close()
stdout := bytes.NewBuffer(nil)
cmd.Stdout = stdout
cmd.Stderr = stdout
assert.Assert(c, cmd.Start() == nil)
waitChan := make(chan error, 1)
go func() {
waitChan <- cmd.Wait()
}()
select {
case err := <-waitChan:
assert.Assert(c, err == nil, stdout.String())
case <-time.After(30 * time.Second):
c.Fatal("timeout waiting for command to exit")
}
}
func (s *DockerSuite) TestRunWrongCpusetCpusFlagValue(c *testing.T) {
// TODO Windows: This needs validation (error out) in the daemon.
testRequires(c, DaemonIsLinux)
out, exitCode, err := dockerCmdWithError("run", "--cpuset-cpus", "1-10,11--", "busybox", "true")
assert.ErrorContains(c, err, "")
expected := "Error response from daemon: Invalid value 1-10,11-- for cpuset cpus.\n"
if !(strings.Contains(out, expected) || exitCode == 125) {
c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode)
}
}
func (s *DockerSuite) TestRunWrongCpusetMemsFlagValue(c *testing.T) {
// TODO Windows: This needs validation (error out) in the daemon.
testRequires(c, DaemonIsLinux)
out, exitCode, err := dockerCmdWithError("run", "--cpuset-mems", "1-42--", "busybox", "true")
assert.ErrorContains(c, err, "")
expected := "Error response from daemon: Invalid value 1-42-- for cpuset mems.\n"
if !(strings.Contains(out, expected) || exitCode == 125) {
c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode)
}
}
// TestRunNonExecutableCmd checks that 'docker run busybox foo' exits with error code 127'
func (s *DockerSuite) TestRunNonExecutableCmd(c *testing.T) {
name := "testNonExecutableCmd"
icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "foo").Assert(c, icmd.Expected{
ExitCode: 127,
Error: "exit status 127",
})
}
// TestRunNonExistingCmd checks that 'docker run busybox /bin/foo' exits with code 127.
func (s *DockerSuite) TestRunNonExistingCmd(c *testing.T) {
name := "testNonExistingCmd"
icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "/bin/foo").Assert(c, icmd.Expected{
ExitCode: 127,
Error: "exit status 127",
})
}
// TestCmdCannotBeInvoked checks that 'docker run busybox /etc' exits with 126, or
// 127 on Windows. The difference is that in Windows, the container must be started
// as that's when the check is made (and yes, by its design...)
func (s *DockerSuite) TestCmdCannotBeInvoked(c *testing.T) {
expected := 126
if testEnv.OSType == "windows" {
expected = 127
}
name := "testCmdCannotBeInvoked"
icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "/etc").Assert(c, icmd.Expected{
ExitCode: expected,
Error: fmt.Sprintf("exit status %d", expected),
})
}
// TestRunNonExistingImage checks that 'docker run foo' exits with error msg 125 and contains 'Unable to find image'
// FIXME(vdemeester) should be a unit test
func (s *DockerSuite) TestRunNonExistingImage(c *testing.T) {
icmd.RunCommand(dockerBinary, "run", "foo").Assert(c, icmd.Expected{
ExitCode: 125,
Err: "Unable to find image",
})
}
// TestDockerFails checks that 'docker run -foo busybox' exits with 125 to signal docker run failed
// FIXME(vdemeester) should be a unit test
func (s *DockerSuite) TestDockerFails(c *testing.T) {
icmd.RunCommand(dockerBinary, "run", "-foo", "busybox").Assert(c, icmd.Expected{
ExitCode: 125,
Error: "exit status 125",
})
}
// TestRunInvalidReference invokes docker run with a bad reference.
func (s *DockerSuite) TestRunInvalidReference(c *testing.T) {
out, exit, _ := dockerCmdWithError("run", "busybox@foo")
if exit == 0 {
c.Fatalf("expected non-zero exist code; received %d", exit)
}
if !strings.Contains(out, "invalid reference format") {
c.Fatalf(`Expected "invalid reference format" in output; got: %s`, out)
}
}
// Test fix for issue #17854
func (s *DockerSuite) TestRunInitLayerPathOwnership(c *testing.T) {
// Not applicable on Windows as it does not support Linux uid/gid ownership
testRequires(c, DaemonIsLinux)
name := "testetcfileownership"
buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
RUN echo 'dockerio:x:1001:' >> /etc/group
RUN chown dockerio:dockerio /etc`))
// Test that dockerio ownership of /etc is retained at runtime
out, _ := dockerCmd(c, "run", "--rm", name, "stat", "-c", "%U:%G", "/etc")
out = strings.TrimSpace(out)
if out != "dockerio:dockerio" {
c.Fatalf("Wrong /etc ownership: expected dockerio:dockerio, got %q", out)
}
}
func (s *DockerSuite) TestRunWithOomScoreAdj(c *testing.T) {
testRequires(c, DaemonIsLinux)
expected := "642"
out, _ := dockerCmd(c, "run", "--oom-score-adj", expected, "busybox", "cat", "/proc/self/oom_score_adj")
oomScoreAdj := strings.TrimSpace(out)
if oomScoreAdj != "642" {
c.Fatalf("Expected oom_score_adj set to %q, got %q instead", expected, oomScoreAdj)
}
}
func (s *DockerSuite) TestRunWithOomScoreAdjInvalidRange(c *testing.T) {
testRequires(c, DaemonIsLinux)
out, _, err := dockerCmdWithError("run", "--oom-score-adj", "1001", "busybox", "true")
assert.ErrorContains(c, err, "")
expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]."
if !strings.Contains(out, expected) {
c.Fatalf("Expected output to contain %q, got %q instead", expected, out)
}
out, _, err = dockerCmdWithError("run", "--oom-score-adj", "-1001", "busybox", "true")
assert.ErrorContains(c, err, "")
expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]."
if !strings.Contains(out, expected) {
c.Fatalf("Expected output to contain %q, got %q instead", expected, out)
}
}
func (s *DockerSuite) TestRunNamedVolumesMountedAsShared(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace)
out, exitCode, _ := dockerCmdWithError("run", "-v", "foo:/test:shared", "busybox", "touch", "/test/somefile")
assert.Assert(c, exitCode != 0)
assert.Assert(c, strings.Contains(out, "invalid mount config"))
}
func (s *DockerSuite) TestRunNamedVolumeCopyImageData(c *testing.T) {
testRequires(c, DaemonIsLinux)
testImg := "testvolumecopy"
buildImageSuccessfully(c, testImg, build.WithDockerfile(`
FROM busybox
RUN mkdir -p /foo && echo hello > /foo/hello
`))
dockerCmd(c, "run", "-v", "foo:/foo", testImg)
out, _ := dockerCmd(c, "run", "-v", "foo:/foo", "busybox", "cat", "/foo/hello")
assert.Equal(c, strings.TrimSpace(out), "hello")
}
func (s *DockerSuite) TestRunNamedVolumeNotRemoved(c *testing.T) {
prefix, _ := getPrefixAndSlashFromDaemonPlatform()
dockerCmd(c, "volume", "create", "test")
dockerCmd(c, "run", "--rm", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
dockerCmd(c, "volume", "inspect", "test")
out, _ := dockerCmd(c, "volume", "ls", "-q")
assert.Assert(c, strings.Contains(out, "test"))
dockerCmd(c, "run", "--name=test", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
dockerCmd(c, "rm", "-fv", "test")
dockerCmd(c, "volume", "inspect", "test")
out, _ = dockerCmd(c, "volume", "ls", "-q")
assert.Assert(c, strings.Contains(out, "test"))
}
func (s *DockerSuite) TestRunNamedVolumesFromNotRemoved(c *testing.T) {
prefix, _ := getPrefixAndSlashFromDaemonPlatform()
dockerCmd(c, "volume", "create", "test")
cid, _ := dockerCmd(c, "run", "-d", "--name=parent", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
dockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true")
cli, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer cli.Close()
container, err := cli.ContainerInspect(context.Background(), strings.TrimSpace(cid))
assert.NilError(c, err)
var vname string
for _, v := range container.Mounts {
if v.Name != "test" {
vname = v.Name
}
}
assert.Assert(c, vname != "")
// Remove the parent so there are not other references to the volumes
dockerCmd(c, "rm", "-f", "parent")
// now remove the child and ensure the named volume (and only the named volume) still exists
dockerCmd(c, "rm", "-fv", "child")
dockerCmd(c, "volume", "inspect", "test")
out, _ := dockerCmd(c, "volume", "ls", "-q")
assert.Assert(c, strings.Contains(out, "test"))
assert.Assert(c, !strings.Contains(strings.TrimSpace(out), vname))
}
func (s *DockerSuite) TestRunAttachFailedNoLeak(c *testing.T) {
nroutines, err := getGoroutineNumber()
assert.NilError(c, err)
runSleepingContainer(c, "--name=test", "-p", "8000:8000")
// Wait until container is fully up and running
assert.Assert(c, waitRun("test") == nil)
out, _, err := dockerCmdWithError("run", "--name=fail", "-p", "8000:8000", "busybox", "true")
// We will need the following `inspect` to diagnose the issue if test fails (#21247)
out1, err1 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "test")
out2, err2 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "fail")
assert.Assert(c, err != nil, "Command should have failed but succeeded with: %s\nContainer 'test' [%+v]: %s\nContainer 'fail' [%+v]: %s", out, err1, out1, err2, out2)
// check for windows error as well
// TODO Windows Post TP5. Fix the error message string
outLowerCase := strings.ToLower(out)
assert.Assert(c, strings.Contains(outLowerCase, "port is already allocated") ||
strings.Contains(outLowerCase, "were not connected because a duplicate name exists") ||
strings.Contains(outLowerCase, "the specified port already exists") ||
strings.Contains(outLowerCase, "hns failed with error : failed to create endpoint") ||
strings.Contains(outLowerCase, "hns failed with error : the object already exists"), fmt.Sprintf("Output: %s", out))
dockerCmd(c, "rm", "-f", "test")
// NGoroutines is not updated right away, so we need to wait before failing
assert.Assert(c, waitForGoroutines(nroutines) == nil)
}
// Test for one character directory name case (#20122)
func (s *DockerSuite) TestRunVolumeWithOneCharacter(c *testing.T) {
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-v", "/tmp/q:/foo", "busybox", "sh", "-c", "find /foo")
assert.Equal(c, strings.TrimSpace(out), "/foo")
}
func (s *DockerSuite) TestRunVolumeCopyFlag(c *testing.T) {
testRequires(c, DaemonIsLinux) // Windows does not support copying data from image to the volume
buildImageSuccessfully(c, "volumecopy", build.WithDockerfile(`FROM busybox
RUN mkdir /foo && echo hello > /foo/bar
CMD cat /foo/bar`))
dockerCmd(c, "volume", "create", "test")
// test with the nocopy flag
out, _, err := dockerCmdWithError("run", "-v", "test:/foo:nocopy", "volumecopy")
assert.ErrorContains(c, err, "", out)
// test default behavior which is to copy for non-binds
out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy")
assert.Equal(c, strings.TrimSpace(out), "hello")
// error out when the volume is already populated
out, _, err = dockerCmdWithError("run", "-v", "test:/foo:copy", "volumecopy")
assert.ErrorContains(c, err, "", out)
// do not error out when copy isn't explicitly set even though it's already populated
out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy")
assert.Equal(c, strings.TrimSpace(out), "hello")
// do not allow copy modes on volumes-from
dockerCmd(c, "run", "--name=test", "-v", "/foo", "busybox", "true")
out, _, err = dockerCmdWithError("run", "--volumes-from=test:copy", "busybox", "true")
assert.ErrorContains(c, err, "", out)
out, _, err = dockerCmdWithError("run", "--volumes-from=test:nocopy", "busybox", "true")
assert.ErrorContains(c, err, "", out)
// do not allow copy modes on binds
out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:copy", "busybox", "true")
assert.ErrorContains(c, err, "", out)
out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:nocopy", "busybox", "true")
assert.ErrorContains(c, err, "", out)
}
// Test case for #21976
func (s *DockerSuite) TestRunDNSInHostMode(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace)
expectedOutput := "nameserver 127.0.0.1"
expectedWarning := "Localhost DNS setting"
cli.DockerCmd(c, "run", "--dns=127.0.0.1", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{
Out: expectedOutput,
Err: expectedWarning,
})
expectedOutput = "nameserver 1.2.3.4"
cli.DockerCmd(c, "run", "--dns=1.2.3.4", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{
Out: expectedOutput,
})
expectedOutput = "search example.com"
cli.DockerCmd(c, "run", "--dns-search=example.com", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{
Out: expectedOutput,
})
expectedOutput = "options timeout:3"
cli.DockerCmd(c, "run", "--dns-opt=timeout:3", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{
Out: expectedOutput,
})
expectedOutput1 := "nameserver 1.2.3.4"
expectedOutput2 := "search example.com"
expectedOutput3 := "options timeout:3"
out := cli.DockerCmd(c, "run", "--dns=1.2.3.4", "--dns-search=example.com", "--dns-opt=timeout:3", "--net=host", "busybox", "cat", "/etc/resolv.conf").Combined()
assert.Assert(c, strings.Contains(out, expectedOutput1), "Expected '%s', but got %q", expectedOutput1, out)
assert.Assert(c, strings.Contains(out, expectedOutput2), "Expected '%s', but got %q", expectedOutput2, out)
assert.Assert(c, strings.Contains(out, expectedOutput3), "Expected '%s', but got %q", expectedOutput3, out)
}
// Test case for #21976
func (s *DockerSuite) TestRunAddHostInHostMode(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace)
expectedOutput := "1.2.3.4\textra"
out, _ := dockerCmd(c, "run", "--add-host=extra:1.2.3.4", "--net=host", "busybox", "cat", "/etc/hosts")
assert.Assert(c, strings.Contains(out, expectedOutput), "Expected '%s', but got %q", expectedOutput, out)
}
func (s *DockerSuite) TestRunRmAndWait(c *testing.T) {
dockerCmd(c, "run", "--name=test", "--rm", "-d", "busybox", "sh", "-c", "sleep 3;exit 2")
out, code, err := dockerCmdWithError("wait", "test")
assert.Assert(c, err == nil, "out: %s; exit code: %d", out, code)
assert.Equal(c, out, "2\n", "exit code: %d", code)
assert.Equal(c, code, 0)
}
// Test that auto-remove is performed by the daemon (API 1.25 and above)
func (s *DockerSuite) TestRunRm(c *testing.T) {
name := "miss-me-when-im-gone"
cli.DockerCmd(c, "run", "--name="+name, "--rm", "busybox")
cli.Docker(cli.Inspect(name), cli.Format(".name")).Assert(c, icmd.Expected{
ExitCode: 1,
Err: "No such object: " + name,
})
}
// Test that auto-remove is performed by the client on API versions that do not support daemon-side api-remove (API < 1.25)
func (s *DockerSuite) TestRunRmPre125Api(c *testing.T) {
name := "miss-me-when-im-gone"
envs := appendBaseEnv(os.Getenv("DOCKER_TLS_VERIFY") != "", "DOCKER_API_VERSION=1.24")
cli.Docker(cli.Args("run", "--name="+name, "--rm", "busybox"), cli.WithEnvironmentVariables(envs...)).Assert(c, icmd.Success)
cli.Docker(cli.Inspect(name), cli.Format(".name")).Assert(c, icmd.Expected{
ExitCode: 1,
Err: "No such object: " + name,
})
}
// Test case for #23498
func (s *DockerSuite) TestRunUnsetEntrypoint(c *testing.T) {
testRequires(c, DaemonIsLinux)
name := "test-entrypoint"
dockerfile := `FROM busybox
ADD entrypoint.sh /entrypoint.sh
RUN chmod 755 /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD echo foobar`
ctx := fakecontext.New(c, "",
fakecontext.WithDockerfile(dockerfile),
fakecontext.WithFiles(map[string]string{
"entrypoint.sh": `#!/bin/sh
echo "I am an entrypoint"
exec "$@"`,
}))
defer ctx.Close()
cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
out := cli.DockerCmd(c, "run", "--entrypoint=", "-t", name, "echo", "foo").Combined()
assert.Equal(c, strings.TrimSpace(out), "foo")
// CMD will be reset as well (the same as setting a custom entrypoint)
cli.Docker(cli.Args("run", "--entrypoint=", "-t", name)).Assert(c, icmd.Expected{
ExitCode: 125,
Err: "No command specified",
})
}
func (s *DockerDaemonSuite) TestRunWithUlimitAndDaemonDefault(c *testing.T) {
s.d.StartWithBusybox(c, "--debug", "--default-ulimit=nofile=65535")
name := "test-A"
_, err := s.d.Cmd("run", "--name", name, "-d", "busybox", "top")
assert.NilError(c, err)
assert.NilError(c, s.d.WaitRun(name))
out, err := s.d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name)
assert.NilError(c, err)
assert.Assert(c, strings.Contains(out, "[nofile=65535:65535]"))
name = "test-B"
_, err = s.d.Cmd("run", "--name", name, "--ulimit=nofile=42", "-d", "busybox", "top")
assert.NilError(c, err)
assert.NilError(c, s.d.WaitRun(name))
out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name)
assert.NilError(c, err)
assert.Assert(c, strings.Contains(out, "[nofile=42:42]"))
}
func (s *DockerSuite) TestRunStoppedLoggingDriverNoLeak(c *testing.T) {
nroutines, err := getGoroutineNumber()
assert.NilError(c, err)
out, _, err := dockerCmdWithError("run", "--name=fail", "--log-driver=splunk", "busybox", "true")
assert.ErrorContains(c, err, "")
assert.Assert(c, strings.Contains(out, "failed to initialize logging driver"), "error should be about logging driver, got output %s", out)
// NGoroutines is not updated right away, so we need to wait before failing
assert.Assert(c, waitForGoroutines(nroutines) == nil)
}
// Handles error conditions for --credentialspec. Validating E2E success cases
// requires additional infrastructure (AD for example) on CI servers.
func (s *DockerSuite) TestRunCredentialSpecFailures(c *testing.T) {
testRequires(c, DaemonIsWindows)
attempts := []struct{ value, expectedError string }{
{"rubbish", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"},
{"rubbish://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"},
{"file://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"},
{"registry://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"},
{`file://c:\blah.txt`, "path cannot be absolute"},
{`file://doesnotexist.txt`, "The system cannot find the file specified"},
}
for _, attempt := range attempts {
_, _, err := dockerCmdWithError("run", "--security-opt=credentialspec="+attempt.value, "busybox", "true")
assert.Assert(c, err != nil, "%s expected non-nil err", attempt.value)
assert.Assert(c, strings.Contains(err.Error(), attempt.expectedError), "%s expected %s got %s", attempt.value, attempt.expectedError, err)
}
}
// Windows specific test to validate credential specs with a well-formed spec.
func (s *DockerSuite) TestRunCredentialSpecWellFormed(c *testing.T) {
testRequires(c, DaemonIsWindows, testEnv.IsLocalDaemon)
validCredSpecs := readFile(`fixtures\credentialspecs\valid.json`, c)
writeFile(filepath.Join(testEnv.DaemonInfo.DockerRootDir, `credentialspecs\valid.json`), validCredSpecs, c)
for _, value := range []string{"file://valid.json", "raw://" + validCredSpecs} {
// `nltest /PARENTDOMAIN` simply reads the local config, and does not require having an AD
// controller handy
out, _ := dockerCmd(c, "run", "--rm", "--security-opt=credentialspec="+value, minimalBaseImage(), "nltest", "/PARENTDOMAIN")
assert.Assert(c, strings.Contains(out, "hyperv.local."))
assert.Assert(c, strings.Contains(out, "The command completed successfully"))
}
}
func (s *DockerSuite) TestRunDuplicateMount(c *testing.T) {
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
tmpFile, err := os.CreateTemp("", "touch-me")
assert.NilError(c, err)
defer tmpFile.Close()
data := "touch-me-foo-bar\n"
if _, err := tmpFile.Write([]byte(data)); err != nil {
c.Fatal(err)
}
name := "test"
out, _ := dockerCmd(c, "run", "--name", name, "-v", "/tmp:/tmp", "-v", "/tmp:/tmp", "busybox", "sh", "-c", "cat "+tmpFile.Name()+" && ls /")
assert.Assert(c, !strings.Contains(out, "tmp:"))
assert.Assert(c, strings.Contains(out, data))
out = inspectFieldJSON(c, name, "Config.Volumes")
assert.Assert(c, strings.Contains(out, "null"))
}
func (s *DockerSuite) TestRunWindowsWithCPUCount(c *testing.T) {
testRequires(c, DaemonIsWindows)
out, _ := dockerCmd(c, "run", "--cpu-count=1", "--name", "test", "busybox", "echo", "testing")
assert.Equal(c, strings.TrimSpace(out), "testing")
out = inspectField(c, "test", "HostConfig.CPUCount")
assert.Equal(c, out, "1")
}
func (s *DockerSuite) TestRunWindowsWithCPUShares(c *testing.T) {
testRequires(c, DaemonIsWindows)
out, _ := dockerCmd(c, "run", "--cpu-shares=1000", "--name", "test", "busybox", "echo", "testing")
assert.Equal(c, strings.TrimSpace(out), "testing")
out = inspectField(c, "test", "HostConfig.CPUShares")
assert.Equal(c, out, "1000")
}
func (s *DockerSuite) TestRunWindowsWithCPUPercent(c *testing.T) {
testRequires(c, DaemonIsWindows)
out, _ := dockerCmd(c, "run", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing")
assert.Equal(c, strings.TrimSpace(out), "testing")
out = inspectField(c, "test", "HostConfig.CPUPercent")
assert.Equal(c, out, "80")
}
func (s *DockerSuite) TestRunProcessIsolationWithCPUCountCPUSharesAndCPUPercent(c *testing.T) {
testRequires(c, IsolationIsProcess)
out, _ := dockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing")
assert.Assert(c, strings.Contains(strings.TrimSpace(out), "WARNING: Conflicting options: CPU count takes priority over CPU shares on Windows Server Containers. CPU shares discarded"))
assert.Assert(c, strings.Contains(strings.TrimSpace(out), "WARNING: Conflicting options: CPU count takes priority over CPU percent on Windows Server Containers. CPU percent discarded"))
assert.Assert(c, strings.Contains(strings.TrimSpace(out), "testing"))
out = inspectField(c, "test", "HostConfig.CPUCount")
assert.Equal(c, out, "1")
out = inspectField(c, "test", "HostConfig.CPUShares")
assert.Equal(c, out, "0")
out = inspectField(c, "test", "HostConfig.CPUPercent")
assert.Equal(c, out, "0")
}
func (s *DockerSuite) TestRunHypervIsolationWithCPUCountCPUSharesAndCPUPercent(c *testing.T) {
testRequires(c, IsolationIsHyperv)
out, _ := dockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing")
assert.Assert(c, strings.Contains(strings.TrimSpace(out), "testing"))
out = inspectField(c, "test", "HostConfig.CPUCount")
assert.Equal(c, out, "1")
out = inspectField(c, "test", "HostConfig.CPUShares")
assert.Equal(c, out, "1000")
out = inspectField(c, "test", "HostConfig.CPUPercent")
assert.Equal(c, out, "80")
}
// Test for #25099
func (s *DockerSuite) TestRunEmptyEnv(c *testing.T) {
testRequires(c, DaemonIsLinux)
expectedOutput := "invalid environment variable:"
out, _, err := dockerCmdWithError("run", "-e", "", "busybox", "true")
assert.ErrorContains(c, err, "")
assert.Assert(c, strings.Contains(out, expectedOutput))
out, _, err = dockerCmdWithError("run", "-e", "=", "busybox", "true")
assert.ErrorContains(c, err, "")
assert.Assert(c, strings.Contains(out, expectedOutput))
out, _, err = dockerCmdWithError("run", "-e", "=foo", "busybox", "true")
assert.ErrorContains(c, err, "")
assert.Assert(c, strings.Contains(out, expectedOutput))
}
// #28658
func (s *DockerSuite) TestSlowStdinClosing(c *testing.T) {
name := "testslowstdinclosing"
repeat := 3 // regression happened 50% of the time
for i := 0; i < repeat; i++ {
cmd := icmd.Cmd{
Command: []string{dockerBinary, "run", "--rm", "--name", name, "-i", "busybox", "cat"},
Stdin: &delayedReader{},
}
done := make(chan error, 1)
go func() {
err := icmd.RunCmd(cmd).Error
done <- err
}()
select {
case <-time.After(30 * time.Second):
c.Fatal("running container timed out") // cleanup in teardown
case err := <-done:
assert.NilError(c, err)
}
}
}
type delayedReader struct{}
func (s *delayedReader) Read([]byte) (int, error) {
time.Sleep(500 * time.Millisecond)
return 0, io.EOF
}
// #28823 (originally #28639)
func (s *DockerSuite) TestRunMountReadOnlyDevShm(c *testing.T) {
testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
emptyDir, err := os.MkdirTemp("", "test-read-only-dev-shm")
assert.NilError(c, err)
defer os.RemoveAll(emptyDir)
out, _, err := dockerCmdWithError("run", "--rm", "--read-only",
"-v", fmt.Sprintf("%s:/dev/shm:ro", emptyDir),
"busybox", "touch", "/dev/shm/foo")
assert.ErrorContains(c, err, "", out)
assert.Assert(c, strings.Contains(out, "Read-only file system"))
}
func (s *DockerSuite) TestRunMount(c *testing.T) {
testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace)
// mnt1, mnt2, and testCatFooBar are commonly used in multiple test cases
tmpDir, err := os.MkdirTemp("", "mount")
if err != nil {
c.Fatal(err)
}
defer os.RemoveAll(tmpDir)
mnt1, mnt2 := path.Join(tmpDir, "mnt1"), path.Join(tmpDir, "mnt2")
if err := os.Mkdir(mnt1, 0755); err != nil {
c.Fatal(err)
}
if err := os.Mkdir(mnt2, 0755); err != nil {
c.Fatal(err)
}
if err := os.WriteFile(path.Join(mnt1, "test1"), []byte("test1"), 0644); err != nil {
c.Fatal(err)
}
if err := os.WriteFile(path.Join(mnt2, "test2"), []byte("test2"), 0644); err != nil {
c.Fatal(err)
}
testCatFooBar := func(cName string) error {
out, _ := dockerCmd(c, "exec", cName, "cat", "/foo/test1")
if out != "test1" {
return fmt.Errorf("%s not mounted on /foo", mnt1)
}
out, _ = dockerCmd(c, "exec", cName, "cat", "/bar/test2")
if out != "test2" {
return fmt.Errorf("%s not mounted on /bar", mnt2)
}
return nil
}
type testCase struct {
equivalents [][]string
valid bool
// fn should be nil if valid==false
fn func(cName string) error
}
cases := []testCase{
{
equivalents: [][]string{
{
"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
"--mount", fmt.Sprintf("type=bind,src=%s,dst=/bar", mnt2),
},
{
"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
"--mount", fmt.Sprintf("type=bind,src=%s,target=/bar", mnt2),
},
{
"--volume", mnt1 + ":/foo",
"--mount", fmt.Sprintf("type=bind,src=%s,target=/bar", mnt2),
},
},
valid: true,
fn: testCatFooBar,
},
{
equivalents: [][]string{
{
"--mount", fmt.Sprintf("type=volume,src=%s,dst=/foo", mnt1),
"--mount", fmt.Sprintf("type=volume,src=%s,dst=/bar", mnt2),
},
{
"--mount", fmt.Sprintf("type=volume,src=%s,dst=/foo", mnt1),
"--mount", fmt.Sprintf("type=volume,src=%s,target=/bar", mnt2),
},
},
valid: false,
},
{
equivalents: [][]string{
{
"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
"--mount", fmt.Sprintf("type=volume,src=%s,dst=/bar", mnt2),
},
{
"--volume", mnt1 + ":/foo",
"--mount", fmt.Sprintf("type=volume,src=%s,target=/bar", mnt2),
},
},
valid: false,
fn: testCatFooBar,
},
{
equivalents: [][]string{
{
"--read-only",
"--mount", "type=volume,dst=/bar",
},
},
valid: true,
fn: func(cName string) error {
_, _, err := dockerCmdWithError("exec", cName, "touch", "/bar/icanwritehere")
return err
},
},
{
equivalents: [][]string{
{
"--read-only",
"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
"--mount", "type=volume,dst=/bar",
},
{
"--read-only",
"--volume", fmt.Sprintf("%s:/foo", mnt1),
"--mount", "type=volume,dst=/bar",
},
},
valid: true,
fn: func(cName string) error {
out, _ := dockerCmd(c, "exec", cName, "cat", "/foo/test1")
if out != "test1" {
return fmt.Errorf("%s not mounted on /foo", mnt1)
}
_, _, err := dockerCmdWithError("exec", cName, "touch", "/bar/icanwritehere")
return err
},
},
{
equivalents: [][]string{
{
"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt2),
},
{
"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
"--mount", fmt.Sprintf("type=bind,src=%s,target=/foo", mnt2),
},
{
"--volume", fmt.Sprintf("%s:/foo", mnt1),
"--mount", fmt.Sprintf("type=bind,src=%s,target=/foo", mnt2),
},
},
valid: false,
},
{
equivalents: [][]string{
{
"--volume", fmt.Sprintf("%s:/foo", mnt1),
"--mount", fmt.Sprintf("type=volume,src=%s,target=/foo", mnt2),
},
},
valid: false,
},
{
equivalents: [][]string{
{
"--mount", "type=volume,target=/foo",
"--mount", "type=volume,target=/foo",
},
},
valid: false,
},
}
for i, testCase := range cases {
for j, opts := range testCase.equivalents {
cName := fmt.Sprintf("mount-%d-%d", i, j)
_, _, err := dockerCmdWithError(append([]string{"run", "-i", "-d", "--name", cName},
append(opts, []string{"busybox", "top"}...)...)...)
if testCase.valid {
assert.Assert(c, err == nil, "got error while creating a container with %v (%s)", opts, cName)
assert.Assert(c, testCase.fn(cName) == nil, "got error while executing test for %v (%s)", opts, cName)
dockerCmd(c, "rm", "-f", cName)
} else {
assert.Assert(c, err != nil, "got nil while creating a container with %v (%s)", opts, cName)
}
}
}
}
// Test that passing a FQDN as hostname properly sets hostname, and
// /etc/hostname. Test case for 29100
func (s *DockerSuite) TestRunHostnameFQDN(c *testing.T) {
testRequires(c, DaemonIsLinux)
expectedOutput := "foobar.example.com\nfoobar.example.com\nfoobar\nexample.com\nfoobar.example.com"
out, _ := dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hostname && hostname && hostname -s && hostname -d && hostname -f`)
assert.Equal(c, strings.TrimSpace(out), expectedOutput)
out, _ = dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hosts`)
expectedOutput = "foobar.example.com foobar"
assert.Assert(c, strings.Contains(strings.TrimSpace(out), expectedOutput))
}
// Test case for 29129
func (s *DockerSuite) TestRunHostnameInHostMode(c *testing.T) {
testRequires(c, DaemonIsLinux, NotUserNamespace)
expectedOutput := "foobar\nfoobar"
out, _ := dockerCmd(c, "run", "--net=host", "--hostname=foobar", "busybox", "sh", "-c", `echo $HOSTNAME && hostname`)
assert.Equal(c, strings.TrimSpace(out), expectedOutput)
}
func (s *DockerSuite) TestRunAddDeviceCgroupRule(c *testing.T) {
testRequires(c, DaemonIsLinux)
deviceRule := "c 7:128 rwm"
out, _ := dockerCmd(c, "run", "--rm", "busybox", "cat", "/sys/fs/cgroup/devices/devices.list")
if strings.Contains(out, deviceRule) {
c.Fatalf("%s shouldn't been in the device.list", deviceRule)
}
out, _ = dockerCmd(c, "run", "--rm", fmt.Sprintf("--device-cgroup-rule=%s", deviceRule), "busybox", "grep", deviceRule, "/sys/fs/cgroup/devices/devices.list")
assert.Equal(c, strings.TrimSpace(out), deviceRule)
}
// Verifies that running as local system is operating correctly on Windows
func (s *DockerSuite) TestWindowsRunAsSystem(c *testing.T) {
testRequires(c, DaemonIsWindowsAtLeastBuild(osversion.RS3))
out, _ := dockerCmd(c, "run", "--net=none", `--user=nt authority\system`, "--hostname=XYZZY", minimalBaseImage(), "cmd", "/c", `@echo %USERNAME%`)
assert.Equal(c, strings.TrimSpace(out), "XYZZY$")
}
|
[
"\"DOCKER_REMAP_ROOT\"",
"\"DOCKER_TLS_VERIFY\""
] |
[] |
[
"DOCKER_TLS_VERIFY",
"DOCKER_REMAP_ROOT"
] |
[]
|
["DOCKER_TLS_VERIFY", "DOCKER_REMAP_ROOT"]
|
go
| 2 | 0 | |
backend/api/user/serializers.py
|
from rest_framework import serializers
from .models import UserProfile, Character
from .models import Bounty, UserRelationship
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
exclude = ["is_active", "is_staff", "is_superuser", "password", "user_permissions", "date_joined", "groups", "last_login"]
account_age = serializers.ReadOnlyField(source="get_account_age")
character_class = serializers.ReadOnlyField(source="get_character_class")
rank = serializers.ReadOnlyField(source="get_rank")
income_accumulated = serializers.ReadOnlyField(source="get_income_accumulated")
net_worth = serializers.ReadOnlyField(source="get_net_worth")
last_collected = serializers.ReadOnlyField(source="get_last_collected")
exp_required = serializers.ReadOnlyField(source="get_exp_required")
class CharacterSerializer(serializers.ModelSerializer):
class Meta:
model = Character
fields = "__all__"
class UserRelationshipSerializer(serializers.ModelSerializer):
class Meta:
model = UserRelationship
fields = "__all__"
class BountySerializer(serializers.ModelSerializer):
class Meta:
model = Bounty
fields = "__all__"
target_health = serializers.ReadOnlyField(source="get_target_health")
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
browser.go
|
// Copyright 2020 The browser Authors. All rights reserved.
// Copyright 2016 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 browser provides utilities for interacting with users' browsers.
package browser
import (
"bytes"
"io/ioutil"
"os"
"os/exec"
"runtime"
"strings"
"time"
)
// Commands returns a list of possible commands to use to open a url.
func Commands() [][]string {
var cmds [][]string
if exe := os.Getenv("BROWSER"); exe != "" {
for _, e := range strings.Split(exe, ":") {
cmds = append(cmds, strings.Split(e, " "))
}
}
switch runtime.GOOS {
case "darwin":
cmds = append(cmds, []string{"/usr/bin/open"})
case "windows":
cmds = append(cmds, []string{"cmd.exe", "/c", "start"})
default:
if os.Getenv("DISPLAY") != "" {
// xdg-open is only for use in a desktop environment.
cmds = append(cmds, []string{"xdg-open"})
} else if _, err := os.Stat("/proc/version"); err != nil {
// WSL reports to be linux and if there's no X server available, fallback to Windows.
if v, err := ioutil.ReadFile("/proc/version"); err != nil && bytes.Contains(bytes.ToLower(v), []byte("microsoft")) {
cmds = append(cmds, []string{"cmd.exe", "/c", "start"})
}
}
}
cmds = append(cmds,
[]string{"chrome"},
[]string{"google-chrome"},
[]string{"chromium"},
[]string{"firefox"},
)
return cmds
}
// Open tries to open url in a browser and reports whether it succeeded.
func Open(url string) bool {
return OpenCmd(url, func(cmd *exec.Cmd) *exec.Cmd { return cmd })
}
// OpenCmd tries to open url in a browser using customized Cmds and reports whether it succeeded.
// If cust returns nil, the Cmd is skipped.
func OpenCmd(url string, cust func(cmd *exec.Cmd) *exec.Cmd) bool {
for _, args := range Commands() {
cmd := exec.Command(args[0], append(args[1:], url)...)
if cmd = cust(cmd); cmd == nil {
continue
}
if cmd.Start() == nil && appearsSuccessful(cmd, 3*time.Second) {
return true
}
}
return false
}
// appearsSuccessful reports whether the command appears to have run successfully.
// If the command runs longer than the timeout, it's deemed successful.
// If the command runs within the timeout, it's deemed successful if it exited cleanly.
func appearsSuccessful(cmd *exec.Cmd, timeout time.Duration) bool {
errc := make(chan error, 1)
go func() {
errc <- cmd.Wait()
}()
select {
case <-time.After(timeout):
return true
case err := <-errc:
return err == nil
}
}
|
[
"\"BROWSER\"",
"\"DISPLAY\""
] |
[] |
[
"BROWSER",
"DISPLAY"
] |
[]
|
["BROWSER", "DISPLAY"]
|
go
| 2 | 0 | |
lib/utils/docker/main.go
|
// The .github/workflows/docker.yml will use it as an github action
// Then run this:
// DOCKER_TOKEN=your_token go run ./lib/utils/docker refs/heads/master
package main
import (
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"github.com/7nikhilkamboj/rod/lib/utils"
)
const registry = "ghcr.io"
const image = registry + "/go-rod/rod"
var token = os.Getenv("DOCKER_TOKEN")
func main() {
event := os.Args[1]
fmt.Println("Event:", event)
master := regexp.MustCompile(`^refs/heads/master$`).MatchString(event)
m := regexp.MustCompile(`^refs/tags/(v[0-9]+\.[0-9]+\.[0-9]+)$`).FindStringSubmatch(event)
ver := ""
if len(m) > 1 {
ver = m[1]
}
if master {
releaseLatest()
} else if ver != "" {
releaseWithVer(ver)
} else {
test()
}
}
func releaseLatest() {
login()
test()
utils.Exec("docker", "push", image)
}
func releaseWithVer(ver string) {
login()
utils.Exec("docker", "pull", image)
utils.Exec("docker", "tag", image, image+":"+ver)
utils.Exec("docker", "push", image+":"+ver)
}
func test() {
utils.Exec("docker", "build", "-t", image, description(), "-f=lib/docker/Dockerfile", ".")
utils.Exec("docker", "build", "-t=dev", "-f=lib/docker/dev.Dockerfile", ".")
wd, err := os.Getwd()
utils.E(err)
utils.Exec("docker", "run", image, "rod-manager", "-h")
utils.Exec("docker", "run", "-v", fmt.Sprintf("%s:/t", wd), "-w=/t", "dev", "go", "test")
}
func login() {
utils.Exec("docker", "login", registry, "-u=rod-robot", "-p="+token)
}
func description() string {
b, err := exec.Command("git", "rev-parse", "HEAD").CombinedOutput()
utils.E(err)
sha := strings.TrimSpace(string(b))
return `--label=org.opencontainers.image.description=https://github.com/7nikhilkamboj/rod/blob/` + sha + "/lib/docker/Dockerfile"
}
|
[
"\"DOCKER_TOKEN\""
] |
[] |
[
"DOCKER_TOKEN"
] |
[]
|
["DOCKER_TOKEN"]
|
go
| 1 | 0 | |
pkg/diskmaker/discovery/discovery.go
|
package discovery
import (
"fmt"
"os"
"os/signal"
"reflect"
"strconv"
"syscall"
"time"
"github.com/openshift/local-storage-operator/pkg/apis"
"github.com/openshift/local-storage-operator/pkg/apis/local/v1alpha1"
"github.com/openshift/local-storage-operator/pkg/diskmaker"
"github.com/openshift/local-storage-operator/pkg/diskmaker/controllers/lvset"
"github.com/openshift/local-storage-operator/pkg/internal"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/klog"
)
const (
localVolumeDiscoveryComponent = "auto-discover-devices"
udevEventPeriod = 5 * time.Second
probeInterval = 5 * time.Minute
resultCRName = "discovery-result-%s"
resultCRLabel = "discovery-result-node"
)
var supportedDeviceTypes = sets.NewString("disk", "part", "lvm")
// DeviceDiscovery instance
type DeviceDiscovery struct {
apiClient diskmaker.ApiUpdater
eventSync *diskmaker.EventReporter
disks []v1alpha1.DiscoveredDevice
localVolumeDiscovery *v1alpha1.LocalVolumeDiscovery
}
// NewDeviceDiscovery returns a new DeviceDiscovery instance
func NewDeviceDiscovery() (*DeviceDiscovery, error) {
scheme := scheme.Scheme
apis.AddToScheme(scheme)
apiUpdater, err := diskmaker.NewAPIUpdater(scheme)
if err != nil {
klog.Error(err, "failed to create new APIUpdater")
return &DeviceDiscovery{}, err
}
dd := &DeviceDiscovery{}
dd.apiClient = apiUpdater
dd.eventSync = diskmaker.NewEventReporter(dd.apiClient)
lvd, err := dd.apiClient.GetLocalVolumeDiscovery(localVolumeDiscoveryComponent, os.Getenv("WATCH_NAMESPACE"))
if err != nil {
klog.Error(err, "failed to get LocalVolumeDiscovery object")
return &DeviceDiscovery{}, err
}
dd.localVolumeDiscovery = lvd
return dd, nil
}
// Start the device discovery process
func (discovery *DeviceDiscovery) Start() error {
klog.Info("starting device discovery")
err := discovery.ensureDiscoveryResultCR()
if err != nil {
message := "failed to start device discovery"
e := diskmaker.NewEvent(diskmaker.ErrorCreatingDiscoveryResultObject, fmt.Sprintf("%s. Error: %+v", message, err), "")
discovery.eventSync.Report(e, discovery.localVolumeDiscovery)
return errors.Wrapf(err, message)
}
err = discovery.discoverDevices()
if err != nil {
errors.Wrapf(err, "failed to discover devices")
}
// Watch udev events for continuous discovery of devices
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGTERM)
udevEvents := make(chan string)
go udevBlockMonitor(udevEvents, udevEventPeriod)
for {
select {
case <-sigc:
klog.Info("shutdown signal received, exiting...")
return nil
case <-time.After(probeInterval):
if err := discovery.discoverDevices(); err != nil {
klog.Errorf("failed to discover devices during probe interval. %v", err)
}
case _, ok := <-udevEvents:
if ok {
klog.Info("trigger probe from udev event")
if err := discovery.discoverDevices(); err != nil {
klog.Errorf("failed to discover devices triggered from udev event. %v", err)
}
} else {
klog.Warningf("disabling udev monitoring")
udevEvents = nil
}
}
}
}
// discoverDevices identifies the list of usable disks on the current node
func (discovery *DeviceDiscovery) discoverDevices() error {
// List all the valid block devices on the node
validDevices, err := getValidBlockDevices()
if err != nil {
message := "failed to discover devices"
e := diskmaker.NewEvent(diskmaker.ErrorListingBlockDevices, fmt.Sprintf("%s. Error: %+v", message, err), "")
discovery.eventSync.Report(e, discovery.localVolumeDiscovery)
return errors.Wrapf(err, message)
}
klog.Infof("valid block devices: %+v", validDevices)
discoveredDisks := getDiscoverdDevices(validDevices)
klog.Infof("discovered devices: %+v", discoveredDisks)
// Update discovered devices in the LocalVolumeDiscoveryResult resource
if !reflect.DeepEqual(discovery.disks, discoveredDisks) {
klog.Info("device list updated. Updating LocalVolumeDiscoveryResult status...")
discovery.disks = discoveredDisks
err = discovery.updateStatus()
if err != nil {
message := "failed to update LocalVolumeDiscoveryResult status"
e := diskmaker.NewEvent(diskmaker.ErrorUpdatingDiscoveryResultObject, fmt.Sprintf("%s. Error: %+v", message, err), "")
discovery.eventSync.Report(e, discovery.localVolumeDiscovery)
return errors.Wrapf(err, message)
}
message := "successfully updated discovered device details in the LocalVolumeDiscoveryResult resource"
e := diskmaker.NewSuccessEvent(diskmaker.UpdatedDiscoveredDeviceList, message, "")
discovery.eventSync.Report(e, discovery.localVolumeDiscovery)
}
return nil
}
// getValidBlockDevices fetchs all the block devices sutitable for discovery
func getValidBlockDevices() ([]internal.BlockDevice, error) {
blockDevices, badRows, err := internal.ListBlockDevices()
if err != nil {
return blockDevices, errors.Wrapf(err, "failed to list all the block devices in the node.")
} else if len(badRows) > 0 {
klog.Warningf("failed to parse all the lsblk rows. Bad rows: %+v", badRows)
}
// Get valid list of devices
validDevices := make([]internal.BlockDevice, 0)
for _, blockDevice := range blockDevices {
if ignoreDevices(blockDevice) {
continue
}
validDevices = append(validDevices, blockDevice)
}
return validDevices, nil
}
// getDiscoverdDevices creates v1alpha1.DiscoveredDevice from internal.BlockDevices
func getDiscoverdDevices(blockDevices []internal.BlockDevice) []v1alpha1.DiscoveredDevice {
discoveredDevices := make([]v1alpha1.DiscoveredDevice, 0)
for _, blockDevice := range blockDevices {
deviceID, err := blockDevice.GetPathByID()
if err != nil {
klog.Warningf("failed to get persisent ID for the device %q. Error %v", blockDevice.Name, err)
deviceID = ""
}
size, err := strconv.ParseInt(blockDevice.Size, 10, 64)
if err != nil {
klog.Warningf("failed to parse size for the device %q. Error %v", blockDevice.Name, err)
}
discoveredDevice := v1alpha1.DiscoveredDevice{
Path: fmt.Sprintf("/dev/%s", blockDevice.Name),
Model: blockDevice.Model,
Vendor: blockDevice.Vendor,
FSType: blockDevice.FSType,
Serial: blockDevice.Serial,
Type: parseDeviceType(blockDevice.Type),
DeviceID: deviceID,
Size: size,
Property: parseDeviceProperty(blockDevice.Rotational),
Status: getDeviceStatus(blockDevice),
}
discoveredDevices = append(discoveredDevices, discoveredDevice)
}
return discoveredDevices
}
// ignoreDevices checks if a device should be ignored during discovery
func ignoreDevices(dev internal.BlockDevice) bool {
if readOnly, err := dev.GetReadOnly(); err != nil || readOnly {
klog.Infof("ignoring read only device %q", dev.Name)
return true
}
if hasChildren, err := dev.HasChildren(); err != nil || hasChildren {
klog.Infof("ignoring root device %q", dev.Name)
return true
}
if dev.State == internal.StateSuspended {
klog.Infof("ignoring device %q with invalid state %q", dev.Name, dev.State)
return true
}
if !supportedDeviceTypes.Has(dev.Type) {
klog.Infof("ignoring device %q with invalid type %q", dev.Name, dev.Type)
return true
}
return false
}
// getDeviceStatus returns device status as "Available", "NotAvailable" or "Unkown"
func getDeviceStatus(dev internal.BlockDevice) v1alpha1.DeviceStatus {
status := v1alpha1.DeviceStatus{}
if dev.FSType != "" {
klog.Infof("device %q with filesystem %q is not available", dev.Name, dev.FSType)
status.State = v1alpha1.NotAvailable
return status
}
noBiosInPartLabel, err := lvset.FilterMap["noBiosInPartLabel"](dev, nil)
if err != nil {
status.State = v1alpha1.Unknown
return status
}
if !noBiosInPartLabel {
klog.Infof("device %q with part label %q is not available", dev.Name, dev.PartLabel)
status.State = v1alpha1.NotAvailable
return status
}
canOpen, err := lvset.FilterMap["canOpenExclusively"](dev, nil)
if err != nil {
status.State = v1alpha1.Unknown
return status
}
if !canOpen {
klog.Infof("device %q is not available as it can't be opened exclusively", dev.Name)
status.State = v1alpha1.NotAvailable
return status
}
hasBindMounts, mountPoint, err := dev.HasBindMounts()
if err != nil {
status.State = v1alpha1.Unknown
return status
}
if hasBindMounts {
klog.Infof("device %q with mount point %q is not available", dev.Name, mountPoint)
status.State = v1alpha1.NotAvailable
return status
}
klog.Infof("device %q is available", dev.Name)
status.State = v1alpha1.Available
return status
}
func parseDeviceProperty(property string) v1alpha1.DeviceMechanicalProperty {
switch {
case property == "1":
return v1alpha1.Rotational
case property == "0":
return v1alpha1.NonRotational
}
return ""
}
func parseDeviceType(deviceType string) v1alpha1.DiscoveredDeviceType {
switch {
case deviceType == "disk":
return v1alpha1.DiskType
case deviceType == "part":
return v1alpha1.PartType
case deviceType == "lvm":
return v1alpha1.LVMType
}
return ""
}
|
[
"\"WATCH_NAMESPACE\""
] |
[] |
[
"WATCH_NAMESPACE"
] |
[]
|
["WATCH_NAMESPACE"]
|
go
| 1 | 0 | |
internal/cmd/list_test.go
|
package cmd_test
import (
"bytes"
"os"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/spf13/viper"
"github.com/toolctl/toolctl/internal/cmd"
)
func TestListCmd(t *testing.T) {
usage := `Usage:
toolctl list [flags]
Aliases:
list, ls
Examples:
# List all installed tools
toolctl list
toolctl ls
# List all supported tools, including those not installed
toolctl list --all
toolctl ls -a
Flags:
-a, --all list all supported tools, including those not installed
-h, --help help for list
Global Flags:
--config string path of the config file (default is $HOME/.config/toolctl/config.yaml)
`
tests := []test{
{
name: "help flag",
cliArgs: []string{"--help"},
wantOut: `List the tools
` + usage,
},
{
name: "no tools installed",
wantOut: `No tools installed
`,
},
{
name: "toolctl-test-tool installed",
supportedTools: []supportedTool{
{
name: "toolctl-test-tool",
tarGz: true,
},
{
name: "toolctl-another-test-tool",
tarGz: true,
},
},
preinstalledTools: []preinstalledTool{
{
name: "toolctl-test-tool",
fileContents: `#!/bin/bash
echo v0.1.0
`},
{
name: "toolctl-another-test-tool",
fileContents: `#!/bin/bash
echo v0.1.0
`},
},
wantOut: `toolctl-test-tool
toolctl-another-test-tool
`,
},
}
originalPathEnv := os.Getenv("PATH")
for _, tt := range tests {
toolctlAPI, apiServer, downloadServer, err := setupRemoteAPI(tt.supportedTools)
if err != nil {
t.Fatalf("%s: SetupRemoteAPI() failed: %v", tt.name, err)
}
var preinstallTempDir string
if !cmp.Equal(tt.preinstalledTools, []preinstalledTool{}) {
preinstallTempDir = setupPreinstallTempDir(
t, tt, toolctlAPI, originalPathEnv,
)
}
t.Run(tt.name, func(t *testing.T) {
buf := new(bytes.Buffer)
command := cmd.NewRootCmd(buf, toolctlAPI.LocalAPIFS())
command.SetArgs(append([]string{"list"}, tt.cliArgs...))
viper.Set("RemoteAPIBaseURL", apiServer.URL)
// Redirect Cobra output
command.SetOut(buf)
command.SetErr(buf)
err := command.Execute()
if (err != nil) != tt.wantErr {
t.Errorf("%s: Execute() error = %v, wantErr %v", tt.name, err, tt.wantErr)
}
checkWantOut(t, tt, buf)
})
os.Setenv("PATH", originalPathEnv)
if !cmp.Equal(tt.preinstalledTools, []preinstalledTool{}) {
err = os.RemoveAll(preinstallTempDir)
if err != nil {
t.Fatal(err)
}
}
apiServer.Close()
downloadServer.Close()
}
}
|
[
"\"PATH\""
] |
[] |
[
"PATH"
] |
[]
|
["PATH"]
|
go
| 1 | 0 | |
tests/integration_test.go
|
package tests
import (
"bytes"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"testing"
"time"
"github.com/anatol/vmtest"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/ssh"
"gopkg.in/yaml.v3"
)
const kernelsDir = "/usr/lib/modules"
var (
binariesDir string
kernelVersions map[string]string
)
func detectKernelVersion() (map[string]string, error) {
files, err := os.ReadDir(kernelsDir)
if err != nil {
return nil, err
}
kernels := make(map[string]string)
for _, f := range files {
ver := f.Name()
vmlinux := filepath.Join(kernelsDir, ver, "vmlinuz")
if _, err := os.Stat(vmlinux); err != nil {
continue
}
pkgbase, err := os.ReadFile(filepath.Join(kernelsDir, ver, "pkgbase"))
if err != nil {
return nil, err
}
pkgbase = bytes.TrimSpace(pkgbase)
kernels[string(pkgbase)] = ver
}
return kernels, nil
}
func generateInitRamfs(opts Opts) (string, error) {
file, err := os.CreateTemp("", "booster.img")
if err != nil {
return "", err
}
output := file.Name()
if err := file.Close(); err != nil {
return "", err
}
config, err := generateBoosterConfig(opts)
if err != nil {
return "", err
}
defer os.Remove(config)
cmd := exec.Command(binariesDir+"/generator", "-force", "-initBinary", binariesDir+"/init", "-kernelVersion", opts.kernelVersion, "-output", output, "-config", config)
if testing.Verbose() {
log.Print("Create booster.img")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("Cannot generate booster.img: %v", err)
}
// check generated image integrity
var verifyCmd *exec.Cmd
switch opts.compression {
case "none":
verifyCmd = exec.Command("cpio", "-i", "--only-verify-crc", "--file", output)
case "zstd", "":
verifyCmd = exec.Command("zstd", "--test", output)
case "gzip":
verifyCmd = exec.Command("gzip", "--test", output)
case "xz":
verifyCmd = exec.Command("xz", "--test", output)
case "lz4":
verifyCmd = exec.Command("lz4", "--test", output)
default:
return "", fmt.Errorf("Unknown compression: %s", opts.compression)
}
if testing.Verbose() {
verifyCmd.Stdout = os.Stdout
verifyCmd.Stderr = os.Stderr
}
if err := verifyCmd.Run(); err != nil {
return "", fmt.Errorf("unable to verify integrity of the output image %s: %v", output, err)
}
return output, nil
}
type NetworkConfig struct {
Interfaces string `yaml:",omitempty"` // comma-separaed list of interfaces to initialize at early-userspace
Dhcp bool `yaml:",omitempty"`
IP string `yaml:",omitempty"` // e.g. 10.0.2.15/24
Gateway string `yaml:",omitempty"` // e.g. 10.0.2.255
DNSServers string `yaml:"dns_servers,omitempty"`
}
type GeneratorConfig struct {
Network *NetworkConfig `yaml:",omitempty"`
Universal bool `yaml:",omitempty"`
Modules string `yaml:",omitempty"`
ModulesForceLoad string `yaml:"modules_force_load,omitempty"` // comma separated list of extra modules to load at the boot time
Compression string `yaml:",omitempty"`
MountTimeout string `yaml:"mount_timeout,omitempty"`
ExtraFiles string `yaml:"extra_files,omitempty"`
StripBinaries bool `yaml:"strip,omitempty"` // strip symbols from the binaries, shared libraries and kernel modules
EnableVirtualConsole bool `yaml:"vconsole,omitempty"`
EnableLVM bool `yaml:"enable_lvm"`
EnableMdraid bool `yaml:"enable_mdraid"`
MdraidConfigPath string `yaml:"mdraid_config_path"`
}
func generateBoosterConfig(opts Opts) (string, error) {
file, err := os.CreateTemp("", "booster.yaml")
if err != nil {
return "", err
}
var conf GeneratorConfig
if opts.enableTangd { // tang requires network enabled
net := &NetworkConfig{}
conf.Network = net
if opts.useDhcp {
net.Dhcp = true
} else {
net.IP = "10.0.2.15/24"
}
net.Interfaces = opts.activeNetIfaces
}
conf.Universal = true
conf.Compression = opts.compression
conf.MountTimeout = strconv.Itoa(opts.mountTimeout) + "s"
conf.ExtraFiles = opts.extraFiles
conf.StripBinaries = opts.stripBinaries
conf.EnableVirtualConsole = opts.enableVirtualConsole
conf.EnableLVM = opts.enableLVM
conf.EnableMdraid = opts.enableMdraid
conf.MdraidConfigPath = opts.mdraidConf
conf.ModulesForceLoad = opts.modulesForceLoad
data, err := yaml.Marshal(&conf)
if err != nil {
return "", err
}
if _, err = file.Write(data); err != nil {
return "", err
}
if err := file.Close(); err != nil {
return "", err
}
return file.Name(), nil
}
type Opts struct {
params []string
compression string
prompt string
password string
modulesForceLoad string
enableTangd bool
useDhcp bool
activeNetIfaces string
enableTpm2 bool
kernelVersion string // kernel version
kernelArgs []string
disk string
disks []vmtest.QemuDisk
mountTimeout int // in seconds
extraFiles string
checkVMState func(vm *vmtest.Qemu, t *testing.T)
forceKill bool // if true then kill VM rather than do a graceful shutdown
stripBinaries bool
enableVirtualConsole bool
enableLVM bool
enableMdraid bool
mdraidConf string
}
func boosterTest(opts Opts) func(*testing.T) {
if opts.checkVMState == nil {
// default simple check
opts.checkVMState = func(vm *vmtest.Qemu, t *testing.T) {
require.NoError(t, vm.ConsoleExpect("Hello, booster!"))
}
}
const defaultLuksPassword = "1234"
if opts.prompt != "" && opts.password == "" {
opts.password = defaultLuksPassword
}
return func(t *testing.T) {
// TODO: make this test run in parallel
if opts.disk != "" {
require.NoError(t, checkAsset(opts.disk))
} else {
for _, disk := range opts.disks {
require.NoError(t, checkAsset(disk.Path))
}
}
if kernel, ok := kernelVersions["linux"]; ok {
opts.kernelVersion = kernel
} else {
require.Fail(t, "System does not have 'linux' package installed needed for the integration tests")
}
initRamfs, err := generateInitRamfs(opts)
require.NoError(t, err)
defer os.Remove(initRamfs)
params := []string{"-m", "8G", "-smp", strconv.Itoa(runtime.NumCPU())}
if os.Getenv("TEST_DISABLE_KVM") != "1" {
params = append(params, "-enable-kvm", "-cpu", "host")
}
kernelArgs := append(opts.kernelArgs, "booster.debug")
require.True(t, opts.disk == "" || len(opts.disks) == 0, "Opts.disk and Opts.disks cannot be specified together")
var disks []vmtest.QemuDisk
if opts.disk != "" {
disks = []vmtest.QemuDisk{{Path: opts.disk, Format: "raw"}}
} else {
disks = opts.disks
}
for _, d := range disks {
require.NoError(t, checkAsset(d.Path))
}
if opts.enableTangd {
tangd, err := NewTangServer("assets/tang")
require.NoError(t, err)
defer tangd.Stop()
// using command directly like one below does not work as extra info is printed to stderr and QEMU incorrectly
// assumes it is a part of HTTP reply
// guestfwd=tcp:10.0.2.100:5697-cmd:/usr/lib/tangd ./assets/tang 2>/dev/null
params = append(params, "-nic", fmt.Sprintf("user,id=n1,restrict=on,guestfwd=tcp:10.0.2.100:5697-tcp:localhost:%d", tangd.port))
}
if opts.enableTpm2 {
cmd := exec.Command("swtpm", "socket", "--tpmstate", "dir=assets/tpm2", "--tpm2", "--ctrl", "type=unixio,path=assets/swtpm-sock", "--flags", "not-need-init")
if testing.Verbose() {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
require.NoError(t, cmd.Start())
defer cmd.Process.Kill()
defer os.Remove("assets/swtpm-sock") // sometimes process crash leaves this file
// wait till swtpm really starts
require.NoError(t, waitForFile("assets/swtpm-sock", 5*time.Second))
params = append(params, "-chardev", "socket,id=chrtpm,path=assets/swtpm-sock", "-tpmdev", "emulator,id=tpm0,chardev=chrtpm", "-device", "tpm-tis,tpmdev=tpm0")
}
// to enable network dump
// params = append(params, "-object", "filter-dump,id=f1,netdev=n1,file=network.dat")
params = append(params, opts.params...)
options := vmtest.QemuOptions{
OperatingSystem: vmtest.OS_LINUX,
Kernel: filepath.Join(kernelsDir, opts.kernelVersion, "vmlinuz"),
InitRamFs: initRamfs,
Params: params,
Append: kernelArgs,
Disks: disks,
Verbose: testing.Verbose(),
Timeout: 40 * time.Second,
}
vm, err := vmtest.NewQemu(&options)
require.NoError(t, err)
if opts.forceKill {
defer vm.Kill()
} else {
defer vm.Shutdown()
}
if opts.prompt != "" {
require.NoError(t, vm.ConsoleExpect(opts.prompt))
require.NoError(t, vm.ConsoleWrite(opts.password+"\n"))
}
opts.checkVMState(vm, t)
}
}
func waitForFile(filename string, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for {
_, err := os.Stat(filename)
if err == nil {
return nil
}
if !os.IsNotExist(err) {
return fmt.Errorf("waitForFile: %v", err)
}
if time.Now().After(deadline) {
return fmt.Errorf("timeout waiting for %v", filename)
}
time.Sleep(10 * time.Millisecond)
}
}
func compileBinaries(dir string) error {
cwd, err := os.Getwd()
if err != nil {
return err
}
// Build init binary
if err := os.Chdir("../init"); err != nil {
return err
}
cmd := exec.Command("go", "build", "-o", dir+"/init")
cmd.Env = append(os.Environ(), "CGO_ENABLED=0")
if testing.Verbose() {
log.Print("Call 'go build' for init")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
if err := cmd.Run(); err != nil {
return fmt.Errorf("Cannot build init binary: %v", err)
}
// Generate initramfs
if err := os.Chdir("../generator"); err != nil {
return err
}
cmd = exec.Command("go", "build", "-o", dir+"/generator")
if testing.Verbose() {
log.Print("Call 'go build' for generator")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
if err := cmd.Run(); err != nil {
return fmt.Errorf("Cannot build generator binary: %v", err)
}
return os.Chdir(cwd)
}
func runSSHCommand(t *testing.T, conn *ssh.Client, command string) string {
sessAnalyze, err := conn.NewSession()
require.NoError(t, err)
defer sessAnalyze.Close()
out, err := sessAnalyze.CombinedOutput(command)
require.NoError(t, err)
return string(out)
}
type assetGenerator struct {
script string
env []string
}
var assetGenerators = make(map[string]assetGenerator)
func initAssetsGenerators() error {
_ = os.Mkdir("assets", 0755)
if exists := fileExists("assets/init"); !exists {
if err := exec.Command("gcc", "-static", "-o", "assets/init", "init/init.c").Run(); err != nil {
return err
}
}
if exists := fileExists("assets/tang/adv.jwk"); !exists {
if err := shell("generate_asset_tang.sh"); err != nil {
return err
}
}
if exists := fileExists("assets/tpm2/tpm2-00.permall"); !exists {
if err := shell("generate_asset_swtpm.sh"); err != nil {
return err
}
}
assetGenerators["assets/ext4.img"] = assetGenerator{"generate_asset_ext4.sh", []string{"OUTPUT=assets/ext4.img", "FS_UUID=5c92fc66-7315-408b-b652-176dc554d370", "FS_LABEL=atestlabel12"}}
assetGenerators["assets/luks1.img"] = assetGenerator{"generate_asset_luks.sh", []string{"OUTPUT=assets/luks1.img", "LUKS_VERSION=1", "LUKS_PASSWORD=1234", "LUKS_UUID=f0c89fd5-7e1e-4ecc-b310-8cd650bd5415", "FS_UUID=ec09a1ea-d43c-4262-b701-bf2577a9ab27"}}
assetGenerators["assets/luks2.img"] = assetGenerator{"generate_asset_luks.sh", []string{"OUTPUT=assets/luks2.img", "LUKS_VERSION=2", "LUKS_PASSWORD=1234", "LUKS_UUID=639b8fdd-36ba-443e-be3e-e5b335935502", "FS_UUID=7bbf9363-eb42-4476-8c1c-9f1f4d091385"}}
assetGenerators["assets/luks1.clevis.tpm2.img"] = assetGenerator{"generate_asset_luks.sh", []string{"OUTPUT=assets/luks1.clevis.tpm2.img", "LUKS_VERSION=1", "LUKS_PASSWORD=1234", "LUKS_UUID=28c2e412-ab72-4416-b224-8abd116d6f2f", "FS_UUID=2996cec0-16fd-4f1d-8bf3-6606afa77043", "CLEVIS_PIN=tpm2", "CLEVIS_CONFIG={}"}}
assetGenerators["assets/luks1.clevis.tang.img"] = assetGenerator{"generate_asset_luks.sh", []string{"OUTPUT=assets/luks1.clevis.tang.img", "LUKS_VERSION=1", "LUKS_PASSWORD=1234", "LUKS_UUID=4cdaa447-ef43-42a6-bfef-89ebb0c61b05", "FS_UUID=c23aacf4-9e7e-4206-ba6c-af017934e6fa", "CLEVIS_PIN=tang", `CLEVIS_CONFIG={"url":"http://10.0.2.100:5697", "adv":"assets/tang/adv.jwk"}`}}
assetGenerators["assets/luks2.clevis.tpm2.img"] = assetGenerator{"generate_asset_luks.sh", []string{"OUTPUT=assets/luks2.clevis.tpm2.img", "LUKS_VERSION=2", "LUKS_PASSWORD=1234", "LUKS_UUID=3756ba2c-1505-4283-8f0b-b1d1bd7b844f", "FS_UUID=c3cc0321-fba8-42c3-ad73-d13f8826d8d7", "CLEVIS_PIN=tpm2", "CLEVIS_CONFIG={}"}}
assetGenerators["assets/luks2.clevis.tang.img"] = assetGenerator{"generate_asset_luks.sh", []string{"OUTPUT=assets/luks2.clevis.tang.img", "LUKS_VERSION=2", "LUKS_PASSWORD=1234", "LUKS_UUID=f2473f71-9a68-4b16-ae54-8f942b2daf50", "FS_UUID=7acb3a9e-9b50-4aa2-9965-e41ae8467d8a", "CLEVIS_PIN=tang", `CLEVIS_CONFIG={"url":"http://10.0.2.100:5697", "adv":"assets/tang/adv.jwk"}`}}
assetGenerators["assets/luks2.clevis.yubikey.img"] = assetGenerator{"generate_asset_luks.sh", []string{"OUTPUT=assets/luks2.clevis.yubikey.img", "LUKS_VERSION=2", "LUKS_PASSWORD=1234", "LUKS_UUID=f2473f71-9a61-4b16-ae54-8f942b2daf52", "FS_UUID=7acb3a9e-9b50-4aa2-9965-e41ae8467d8a", "CLEVIS_PIN=yubikey", `CLEVIS_CONFIG={"slot":2}`}}
assetGenerators["assets/gpt.img"] = assetGenerator{"generate_asset_gpt.sh", []string{"OUTPUT=assets/gpt.img", "FS_UUID=e5404205-ac6a-4e94-bb3b-14433d0af7d1", "FS_LABEL=newpart"}}
assetGenerators["assets/lvm.img"] = assetGenerator{"generate_asset_lvm.sh", []string{"OUTPUT=assets/lvm.img", "FS_UUID=74c9e30c-506f-4106-9f61-a608466ef29c", "FS_LABEL=lvmr00t"}}
assetGenerators["assets/mdraid_raid1.img"] = assetGenerator{"generate_asset_mdraid_raid1.sh", []string{"OUTPUT=assets/mdraid_raid1.img", "FS_UUID=98b1a905-3c72-42f0-957a-6c23b303b1fd", "FS_LABEL=boosmdraid"}}
assetGenerators["assets/mdraid_raid5.img"] = assetGenerator{"generate_asset_mdraid_raid5.sh", []string{"OUTPUT=assets/mdraid_raid5.img", "FS_UUID=e62c7dc0-5728-4571-b475-7745de2eef1e", "FS_LABEL=boosmdraid"}}
assetGenerators["assets/archlinux.ext4.raw"] = assetGenerator{"generate_asset_archlinux_ext4.sh", []string{"OUTPUT=assets/archlinux.ext4.raw"}}
assetGenerators["assets/archlinux.btrfs.raw"] = assetGenerator{"generate_asset_archlinux_btrfs.sh", []string{"OUTPUT=assets/archlinux.btrfs.raw", "LUKS_PASSWORD=hello"}}
assetGenerators["assets/voidlinux.img"] = assetGenerator{"generate_asset_voidlinux.sh", []string{"OUTPUT=assets/voidlinux.img"}}
return nil
}
func checkAsset(file string) error {
if !strings.HasPrefix(file, "assets/") {
return nil
}
gen, ok := assetGenerators[file]
if !ok {
return fmt.Errorf("no generator for asset %s", file)
}
if exists := fileExists(file); exists {
return nil
}
if testing.Verbose() {
fmt.Printf("Generating asset %s\n", file)
}
return shell(gen.script, gen.env...)
}
func shell(script string, env ...string) error {
sh := exec.Command("bash", "-o", "errexit", script)
sh.Env = append(os.Environ(), env...)
if testing.Verbose() {
sh.Stdout = os.Stdout
sh.Stderr = os.Stderr
}
return sh.Run()
}
func fileExists(file string) bool {
_, err := os.Stat(file)
return err == nil
}
type yubikey struct {
bus, device string
}
// detectYubikey checks if a yubikey is present and uses its slot #2 for tests
func detectYubikey() (*yubikey, error) {
out, err := exec.Command("lsusb").CombinedOutput()
if err != nil {
return nil, err
}
for _, l := range strings.Split(string(out), "\n") {
if !strings.Contains(l, "Yubikey") {
continue
}
re, err := regexp.Compile(`Bus 0*(\d+) Device 0*(\d+):`)
if err != nil {
return nil, err
}
m := re.FindAllStringSubmatch(l, -1)
if m == nil {
return nil, fmt.Errorf("lsusb does not match bus/device")
}
return &yubikey{m[0][1], m[0][2]}, nil
}
return nil, nil
}
func TestBooster(t *testing.T) {
var err error
kernelVersions, err = detectKernelVersion()
require.NoError(t, err, "unable to detect current Linux version")
binariesDir = t.TempDir()
require.NoError(t, compileBinaries(binariesDir))
require.NoError(t, initAssetsGenerators())
yubikey, err := detectYubikey()
require.NoError(t, err)
// TODO: add a test to verify the emergency shell functionality
// VmTest uses sockets for console and it seems does not like the shell we launch
// note that assets are generated using ./assets_generator tool
t.Run("Ext4.UUID", boosterTest(Opts{
compression: "zstd",
disk: "assets/ext4.img",
kernelArgs: []string{"root=UUID=5c92fc66-7315-408b-b652-176dc554d370", "rootflags=user_xattr,nobarrier"},
}))
t.Run("Ext4.MountFlags", boosterTest(Opts{
compression: "none",
disk: "assets/ext4.img",
kernelArgs: []string{"root=UUID=5c92fc66-7315-408b-b652-176dc554d370", "rootflags=user_xattr,noatime,nobarrier,nodev,dirsync,lazytime,nolazytime,dev,rw,ro", "rw"},
}))
t.Run("Ext4.Label", boosterTest(Opts{
compression: "gzip",
disk: "assets/ext4.img",
kernelArgs: []string{"root=LABEL=atestlabel12"},
}))
t.Run("DisableConcurrentModuleLoading", boosterTest(Opts{
disk: "assets/luks2.img",
prompt: "Enter passphrase for luks-639b8fdd-36ba-443e-be3e-e5b335935502:",
kernelArgs: []string{"rd.luks.uuid=639b8fdd-36ba-443e-be3e-e5b335935502", "root=UUID=7bbf9363-eb42-4476-8c1c-9f1f4d091385", "booster.disable_concurrent_module_loading"},
}))
// verifies module force loading + modprobe command-line parameters
t.Run("Vfio", boosterTest(Opts{
modulesForceLoad: "vfio_pci,vfio,vfio_iommu_type1,vfio_virqfd",
params: []string{"-net", "user,hostfwd=tcp::10022-:22", "-net", "nic"},
disks: []vmtest.QemuDisk{{Path: "assets/archlinux.ext4.raw", Format: "raw"}},
kernelArgs: []string{"root=/dev/sda", "rw", "vfio-pci.ids=1002:67df,1002:aaf0"},
checkVMState: func(vm *vmtest.Qemu, t *testing.T) {
config := &ssh.ClientConfig{
User: "root",
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
conn, err := ssh.Dial("tcp", ":10022", config)
require.NoError(t, err)
defer conn.Close()
dmesg := runSSHCommand(t, conn, "dmesg")
require.Contains(t, dmesg, "loading module vfio_pci params=\"ids=1002:67df,1002:aaf0\"", "expecting vfio_pci module loading")
require.Contains(t, dmesg, "vfio_pci: add [1002:67df[ffffffff:ffffffff]] class 0x000000/00000000", "expecting vfio_pci 1002:67df device")
require.Contains(t, dmesg, "vfio_pci: add [1002:aaf0[ffffffff:ffffffff]] class 0x000000/00000000", "expecting vfio_pci 1002:aaf0 device")
re := regexp.MustCompile(`booster: udev event {Header:add@/bus/pci/drivers/vfio-pci Action:add Devpath:/bus/pci/drivers/vfio-pci Subsystem:drivers Seqnum:\d+ Vars:map\[ACTION:add DEVPATH:/bus/pci/drivers/vfio-pci SEQNUM:\d+ SUBSYSTEM:drivers]}`)
require.Regexp(t, re, dmesg, "expecting vfio_pci module loading udev event")
},
}))
t.Run("NonFormattedDrive", boosterTest(Opts{
compression: "none",
disks: []vmtest.QemuDisk{
{ /* represents non-formatted drive */ Path: "integration_test.go", Format: "raw"},
{Path: "assets/ext4.img", Format: "raw"},
},
kernelArgs: []string{"root=UUID=5c92fc66-7315-408b-b652-176dc554d370"},
}))
t.Run("XZImageCompression", boosterTest(Opts{
compression: "xz",
disk: "assets/ext4.img",
kernelArgs: []string{"root=UUID=5c92fc66-7315-408b-b652-176dc554d370"},
}))
t.Run("GzipImageCompression", boosterTest(Opts{
compression: "gzip",
disk: "assets/ext4.img",
kernelArgs: []string{"root=UUID=5c92fc66-7315-408b-b652-176dc554d370"},
}))
t.Run("Lz4ImageCompression", boosterTest(Opts{
compression: "lz4",
disk: "assets/ext4.img",
kernelArgs: []string{"root=UUID=5c92fc66-7315-408b-b652-176dc554d370"},
}))
t.Run("MountTimeout", boosterTest(Opts{
compression: "xz",
mountTimeout: 1,
forceKill: true,
checkVMState: func(vm *vmtest.Qemu, t *testing.T) {
require.NoError(t, vm.ConsoleExpect("Timeout waiting for root filesystem"))
},
}))
t.Run("Fsck", boosterTest(Opts{
compression: "none",
disk: "assets/ext4.img",
kernelArgs: []string{"root=LABEL=atestlabel12"},
extraFiles: "fsck,fsck.ext4",
}))
t.Run("VirtualConsole", boosterTest(Opts{
compression: "none",
disk: "assets/ext4.img",
kernelArgs: []string{"root=LABEL=atestlabel12"},
enableVirtualConsole: true,
}))
t.Run("StripBinaries", boosterTest(Opts{
disk: "assets/luks2.clevis.tpm2.img",
enableTpm2: true,
stripBinaries: true,
kernelArgs: []string{"rd.luks.uuid=3756ba2c-1505-4283-8f0b-b1d1bd7b844f", "root=UUID=c3cc0321-fba8-42c3-ad73-d13f8826d8d7"},
}))
t.Run("LUKS1.WithName", boosterTest(Opts{
disk: "assets/luks1.img",
prompt: "Enter passphrase for cryptroot:",
kernelArgs: []string{"rd.luks.name=f0c89fd5-7e1e-4ecc-b310-8cd650bd5415=cryptroot", "root=/dev/mapper/cryptroot", "rd.luks.options=discard"},
}))
t.Run("LUKS1.WithUUID", boosterTest(Opts{
disk: "assets/luks1.img",
prompt: "Enter passphrase for luks-f0c89fd5-7e1e-4ecc-b310-8cd650bd5415:",
kernelArgs: []string{"rd.luks.uuid=f0c89fd5-7e1e-4ecc-b310-8cd650bd5415", "root=UUID=ec09a1ea-d43c-4262-b701-bf2577a9ab27"},
}))
t.Run("LUKS2.WithName", boosterTest(Opts{
disk: "assets/luks2.img",
prompt: "Enter passphrase for cryptroot:",
kernelArgs: []string{"rd.luks.name=639b8fdd-36ba-443e-be3e-e5b335935502=cryptroot", "root=/dev/mapper/cryptroot"},
}))
t.Run("LUKS2.WithUUID", boosterTest(Opts{
disk: "assets/luks2.img",
prompt: "Enter passphrase for luks-639b8fdd-36ba-443e-be3e-e5b335935502:",
kernelArgs: []string{"rd.luks.uuid=639b8fdd-36ba-443e-be3e-e5b335935502", "root=UUID=7bbf9363-eb42-4476-8c1c-9f1f4d091385"},
}))
t.Run("LUKS2.WithQuotesOverUUID", boosterTest(Opts{
disk: "assets/luks2.img",
prompt: "Enter passphrase for luks-639b8fdd-36ba-443e-be3e-e5b335935502:",
kernelArgs: []string{"rd.luks.uuid=\"639b8fdd-36ba-443e-be3e-e5b335935502\"", "root=UUID=\"7bbf9363-eb42-4476-8c1c-9f1f4d091385\""},
}))
if yubikey != nil {
t.Run("LUKS2.Clevis.Yubikey", boosterTest(Opts{
disk: "assets/luks2.clevis.yubikey.img",
kernelArgs: []string{"rd.luks.uuid=f2473f71-9a61-4b16-ae54-8f942b2daf52", "root=UUID=7acb3a9e-9b50-4aa2-9965-e41ae8467d8a"},
extraFiles: "ykchalresp",
params: []string{"-usb", "-device", "usb-host,hostbus=" + yubikey.bus + ",hostaddr=" + yubikey.device},
}))
}
t.Run("LUKS1.Clevis.Tang", boosterTest(Opts{
disk: "assets/luks1.clevis.tang.img",
enableTangd: true,
kernelArgs: []string{"rd.luks.uuid=4cdaa447-ef43-42a6-bfef-89ebb0c61b05", "root=UUID=c23aacf4-9e7e-4206-ba6c-af017934e6fa"},
}))
t.Run("LUKS2.Clevis.Tang", boosterTest(Opts{
disk: "assets/luks2.clevis.tang.img",
enableTangd: true,
kernelArgs: []string{"rd.luks.uuid=f2473f71-9a68-4b16-ae54-8f942b2daf50", "root=UUID=7acb3a9e-9b50-4aa2-9965-e41ae8467d8a"},
}))
t.Run("LUKS2.Clevis.Tang.DHCP", boosterTest(Opts{
disk: "assets/luks2.clevis.tang.img",
enableTangd: true,
useDhcp: true,
activeNetIfaces: "52-54-00-12-34-53,52:54:00:12:34:56,52:54:00:12:34:57", // 52:54:00:12:34:56 is QEMU's NIC address
kernelArgs: []string{"rd.luks.uuid=f2473f71-9a68-4b16-ae54-8f942b2daf50", "root=UUID=7acb3a9e-9b50-4aa2-9965-e41ae8467d8a"},
}))
t.Run("InactiveNetwork", boosterTest(Opts{
disk: "assets/luks2.clevis.tang.img",
enableTangd: true,
useDhcp: true,
activeNetIfaces: "52:54:00:12:34:57", // 52:54:00:12:34:56 is QEMU's NIC address
kernelArgs: []string{"rd.luks.uuid=f2473f71-9a68-4b16-ae54-8f942b2daf50", "root=UUID=7acb3a9e-9b50-4aa2-9965-e41ae8467d8a"},
mountTimeout: 10,
forceKill: true,
checkVMState: func(vm *vmtest.Qemu, t *testing.T) {
require.NoError(t, vm.ConsoleExpect("Timeout waiting for root filesystem"))
},
}))
t.Run("LUKS1.Clevis.Tpm2", boosterTest(Opts{
disk: "assets/luks1.clevis.tpm2.img",
enableTpm2: true,
kernelArgs: []string{"rd.luks.uuid=28c2e412-ab72-4416-b224-8abd116d6f2f", "root=UUID=2996cec0-16fd-4f1d-8bf3-6606afa77043"},
}))
t.Run("LUKS2.Clevis.Tpm2", boosterTest(Opts{
disk: "assets/luks2.clevis.tpm2.img",
enableTpm2: true,
kernelArgs: []string{"rd.luks.uuid=3756ba2c-1505-4283-8f0b-b1d1bd7b844f", "root=UUID=c3cc0321-fba8-42c3-ad73-d13f8826d8d7"},
}))
t.Run("LVM.Path", boosterTest(Opts{
enableLVM: true,
disk: "assets/lvm.img",
kernelArgs: []string{"root=/dev/booster_test_vg/booster_test_lv"},
}))
t.Run("LVM.UUID", boosterTest(Opts{
enableLVM: true,
disk: "assets/lvm.img",
kernelArgs: []string{"root=UUID=74c9e30c-506f-4106-9f61-a608466ef29c"},
}))
t.Run("MdRaid1.Path", boosterTest(Opts{
enableMdraid: true,
mdraidConf: "assets/mdraid_raid1.img.array",
disk: "assets/mdraid_raid1.img",
kernelArgs: []string{"root=/dev/md/BoosterTestArray1"},
}))
t.Run("MdRaid1.UUID", boosterTest(Opts{
enableMdraid: true,
mdraidConf: "assets/mdraid_raid1.img.array",
disk: "assets/mdraid_raid1.img",
kernelArgs: []string{"root=UUID=98b1a905-3c72-42f0-957a-6c23b303b1fd"},
}))
t.Run("MdRaid5.Path", boosterTest(Opts{
enableMdraid: true,
mdraidConf: "assets/mdraid_raid5.img.array",
disk: "assets/mdraid_raid5.img",
kernelArgs: []string{"root=/dev/md/BoosterTestArray5"},
}))
t.Run("MdRaid5.UUID", boosterTest(Opts{
enableMdraid: true,
mdraidConf: "assets/mdraid_raid5.img.array",
disk: "assets/mdraid_raid5.img",
kernelArgs: []string{"root=UUID=e62c7dc0-5728-4571-b475-7745de2eef1e"},
}))
t.Run("Gpt.Path", boosterTest(Opts{
disk: "assets/gpt.img",
kernelArgs: []string{"root=/dev/sda3"},
}))
t.Run("Gpt.UUID", boosterTest(Opts{
disk: "assets/gpt.img",
kernelArgs: []string{"root=UUID=e5404205-ac6a-4e94-bb3b-14433d0af7d1"},
}))
t.Run("Gpt.LABEL", boosterTest(Opts{
disk: "assets/gpt.img",
kernelArgs: []string{"root=LABEL=newpart"},
}))
t.Run("Gpt.PARTUUID", boosterTest(Opts{
disk: "assets/gpt.img",
kernelArgs: []string{"root=PARTUUID=1b8e9701-59a6-49f4-8c31-b97c99cd52cf"},
}))
t.Run("Gpt.PARTLABEL", boosterTest(Opts{
disk: "assets/gpt.img",
kernelArgs: []string{"root=PARTLABEL=раздел3"},
}))
t.Run("Gpt.PARTNROFF", boosterTest(Opts{
disk: "assets/gpt.img",
kernelArgs: []string{"root=PARTUUID=78073a8b-bdf6-48cc-918e-edb926b25f64/PARTNROFF=2"},
}))
t.Run("Gpt.ByUUID", boosterTest(Opts{
disk: "assets/gpt.img",
kernelArgs: []string{"root=/dev/disk/by-uuid/e5404205-ac6a-4e94-bb3b-14433d0af7d1"},
}))
t.Run("Gpt.ByLABEL", boosterTest(Opts{
disk: "assets/gpt.img",
kernelArgs: []string{"root=/dev/disk/by-label/newpart"},
}))
t.Run("Gpt.ByPARTUUID", boosterTest(Opts{
disk: "assets/gpt.img",
kernelArgs: []string{"root=/dev/disk/by-partuuid/1b8e9701-59a6-49f4-8c31-b97c99cd52cf"},
}))
t.Run("Gpt.ByPARTLABEL", boosterTest(Opts{
disk: "assets/gpt.img",
kernelArgs: []string{"root=/dev/disk/by-partlabel/раздел3"},
}))
t.Run("Gpt.Autodiscovery", boosterTest(Opts{
disk: "assets/gpt.img",
}))
t.Run("VoidLinux", boosterTest(Opts{
disk: "assets/voidlinux.img",
kernelArgs: []string{"root=/dev/sda"},
forceKill: true,
checkVMState: func(vm *vmtest.Qemu, t *testing.T) {
require.NoError(t, vm.ConsoleExpect("runsvchdir: default: current."))
},
}))
// boot Arch userspace (with systemd) against all installed linux packages
for pkg, ver := range kernelVersions {
compression := "zstd"
if pkg == "linux-lts" {
compression = "gzip"
}
checkVMState := func(vm *vmtest.Qemu, t *testing.T) {
config := &ssh.ClientConfig{
User: "root",
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
conn, err := ssh.Dial("tcp", ":10022", config)
require.NoError(t, err)
defer conn.Close()
sess, err := conn.NewSession()
require.NoError(t, err)
defer sess.Close()
out, err := sess.CombinedOutput("systemd-analyze")
require.NoError(t, err)
require.Contains(t, string(out), "(initrd)", "expect initrd time stats in systemd-analyze")
// check writing to kmesg works
sess3, err := conn.NewSession()
require.NoError(t, err)
defer sess3.Close()
out, err = sess3.CombinedOutput("dmesg | grep -i booster")
require.NoError(t, err)
require.Contains(t, string(out), "Switching to the new userspace now", "expected to see debug output from booster")
sessShutdown, err := conn.NewSession()
require.NoError(t, err)
defer sessShutdown.Close()
// Arch Linux 5.4 does not shutdown with QEMU's 'shutdown' event for some reason. Force shutdown from ssh session.
_, _ = sessShutdown.CombinedOutput("shutdown now")
}
// simple ext4 image
t.Run("ArchLinux.ext4."+pkg, boosterTest(Opts{
kernelVersion: ver,
compression: compression,
params: []string{"-net", "user,hostfwd=tcp::10022-:22", "-net", "nic"},
disks: []vmtest.QemuDisk{{Path: "assets/archlinux.ext4.raw", Format: "raw"}},
// If you need more debug logs append kernel args: "systemd.log_level=debug", "udev.log-priority=debug", "systemd.log_target=console", "log_buf_len=8M"
kernelArgs: []string{"root=/dev/sda", "rw"},
checkVMState: checkVMState,
}))
// more complex setup with LUKS and btrfs subvolumes
t.Run("ArchLinux.btrfs."+pkg, boosterTest(Opts{
kernelVersion: ver,
compression: compression,
params: []string{"-net", "user,hostfwd=tcp::10022-:22", "-net", "nic"},
disks: []vmtest.QemuDisk{{Path: "assets/archlinux.btrfs.raw", Format: "raw"}},
kernelArgs: []string{"rd.luks.uuid=724151bb-84be-493c-8e32-53e123c8351b", "root=UUID=15700169-8c12-409d-8781-37afa98442a8", "rootflags=subvol=@", "rw", "quiet", "nmi_watchdog=0", "kernel.unprivileged_userns_clone=0", "net.core.bpf_jit_harden=2", "apparmor=1", "lsm=lockdown,yama,apparmor", "systemd.unified_cgroup_hierarchy=1", "add_efi_memmap"},
prompt: "Enter passphrase for luks-724151bb-84be-493c-8e32-53e123c8351b:",
password: "hello",
checkVMState: checkVMState,
}))
}
}
|
[
"\"TEST_DISABLE_KVM\""
] |
[] |
[
"TEST_DISABLE_KVM"
] |
[]
|
["TEST_DISABLE_KVM"]
|
go
| 1 | 0 | |
src/functions/testfunc2/testfunc2.go
|
package main
import (
"log"
"net/http"
"os"
"github.com/apex/gateway"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func main() {
// Take advantage of features built in to third party routers like method filtering, param parsing, etc.
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/.netlify/functions/testfunc2", lambdaHandler)
if os.Getenv("AWS_LAMBDA_FUNCTION_NAME") == "" {
log.Fatal(http.ListenAndServe(":3000", r))
} else {
log.Fatal(gateway.ListenAndServe(":3000", r))
}
}
func lambdaHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Looks like you made it to testfunc2!"))
}
|
[
"\"AWS_LAMBDA_FUNCTION_NAME\""
] |
[] |
[
"AWS_LAMBDA_FUNCTION_NAME"
] |
[]
|
["AWS_LAMBDA_FUNCTION_NAME"]
|
go
| 1 | 0 | |
ib_insync/ibcontroller.py
|
import os
import asyncio
import logging
import configparser
from contextlib import suppress
from eventkit import Event
from ib_insync.objects import Object
from ib_insync.contract import Forex
from ib_insync.ib import IB
import ib_insync.util as util
__all__ = ['IBC', 'IBController', 'Watchdog']
class IBC(Object):
"""
Programmatic control over starting and stopping TWS/Gateway
using IBC (https://github.com/IbcAlpha/IBC).
Args:
twsVersion (int): (required) The major version number for
TWS or gateway.
gateway (bool):
* True = gateway
* False = TWS
tradingMode (str): 'live' or 'paper'.
userid (str): IB account username. It is recommended to set the real
username/password in a secured IBC config file.
password (str): IB account password.
twsPath (str): Path to the TWS installation folder.
Defaults:
* Linux: ~/Jts
* OS X: ~/Applications
* Windows: C:\\\\Jts
twsSettingsPath (str): Path to the TWS settings folder.
Defaults:
* Linux: ~/Jts
* OS X: ~/Jts
* Windows: Not available
ibcPath (str): Path to the IBC installation folder.
Defaults:
* Linux: /opt/ibc
* OS X: /opt/ibc
* Windows: C:\\\\IBC
ibcIni (str): Path to the IBC configuration file.
Defaults:
* Linux: ~/ibc/config.ini
* OS X: ~/ibc/config.ini
* Windows: %%HOMEPATH%%\\\\Documents\\\\IBC\\\\config.ini
javaPath (str): Path to Java executable.
Default is to use the Java VM included with TWS/gateway.
fixuserid (str): FIX account user id (gateway only).
fixpassword (str): FIX account password (gateway only).
This is not intended to be run in a notebook.
To use IBC on Windows, the proactor (or quamash) event loop
must have been set:
.. code-block:: python
import asyncio
asyncio.set_event_loop(asyncio.ProactorEventLoop())
Example usage:
.. code-block:: python
ibc = IBC(974, gateway=True, tradingMode='live',
userid='edemo', password='demouser')
ibc.start()
IB.run()
"""
IbcLogLevel = logging.DEBUG
_Args = dict(
# key=(Default, UnixArg, WindowsArg)
twsVersion=(None, '', ''),
gateway=(None, '--gateway', '/Gateway'),
tradingMode=(None, '--mode=', '/Mode:'),
twsPath=(None, '--tws-path=', '/TwsPath:'),
twsSettingsPath=(None, '--tws-settings-path=', ''),
ibcPath=(None, '--ibc-path=', '/IbcPath:'),
ibcIni=(None, '--ibc-ini=', '/Config:'),
javaPath=(None, '--java-path=', '/JavaPath:'),
userid=(None, '--user=', '/User:'),
password=(None, '--pw=', '/PW:'),
fixuserid=(None, '--fix-user=', '/FIXUser:'),
fixpassword=(None, '--fix-pw=', '/FIXPW:'))
defaults = {k: v[0] for k, v in _Args.items()}
__slots__ = list(defaults) + ['_proc', '_logger', '_monitor']
def __init__(self, *args, **kwargs):
Object.__init__(self, *args, **kwargs)
if not self.ibcPath:
self.ibcPath = '/opt/ibc' if os.sys.platform != 'win32' \
else 'C:\\IBC'
self._proc = None
self._monitor = None
self._logger = logging.getLogger('ib_insync.IBC')
def __enter__(self):
self.start()
return self
def __exit__(self, *_exc):
self.terminate()
def start(self):
"""
Launch TWS/IBG.
"""
util.run(self.startAsync())
def terminate(self):
"""
Terminate TWS/IBG.
"""
util.run(self.terminateAsync())
async def startAsync(self):
if self._proc:
return
self._logger.info('Starting')
# create shell command
win32 = os.sys.platform == 'win32'
cmd = [
f'{self.ibcPath}\\scripts\\StartIBC.bat' if win32 else
#TODO: add 'runIncontainer' option to class
f'/usr/bin/xvfb-run', f'-a', f'{self.ibcPath}/scripts/ibcstart.sh']
for k, v in self.dict().items():
arg = IBC._Args[k][2 if win32 else 1]
if v:
if arg.endswith('=') or arg.endswith(':'):
cmd.append(f'{arg}{v}')
elif arg:
cmd.append(arg)
else:
cmd.append(str(v))
# run shell command
self._proc = await asyncio.create_subprocess_exec(
*cmd, stdout=asyncio.subprocess.PIPE)
self._monitor = asyncio.ensure_future(self.monitorAsync())
async def terminateAsync(self):
if not self._proc:
return
self._logger.info('Terminating')
if self._monitor:
self._monitor.cancel()
self._monitor = None
if os.sys.platform == 'win32':
import subprocess
subprocess.call(
['taskkill', '/F', '/T', '/PID', str(self._proc.pid)])
else:
with suppress(ProcessLookupError):
self._proc.terminate()
await self._proc.wait()
self._proc = None
async def monitorAsync(self):
while self._proc:
line = await self._proc.stdout.readline()
if not line:
break
self._logger.log(IBC.IbcLogLevel, line.strip().decode())
class IBController(Object):
"""
For new installations it is recommended to use IBC instead.
Programmatic control over starting and stopping TWS/Gateway
using IBController (https://github.com/ib-controller/ib-controller).
On Windows the the proactor (or quamash) event loop must have been set:
.. code-block:: python
import asyncio
asyncio.set_event_loop(asyncio.ProactorEventLoop())
This is not intended to be run in a notebook.
"""
defaults = dict(
APP='TWS', # 'TWS' or 'GATEWAY'
TWS_MAJOR_VRSN='969',
TRADING_MODE='live', # 'live' or 'paper'
IBC_INI='~/IBController/IBController.ini',
IBC_PATH='~/IBController',
TWS_PATH='~/Jts',
LOG_PATH='~/IBController/Logs',
TWSUSERID='',
TWSPASSWORD='',
JAVA_PATH='',
TWS_CONFIG_PATH='')
__slots__ = list(defaults) + ['_proc', '_logger', '_monitor']
def __init__(self, *args, **kwargs):
Object.__init__(self, *args, **kwargs)
self._proc = None
self._monitor = None
self._logger = logging.getLogger('ib_insync.IBController')
def __enter__(self):
self.start()
return self
def __exit__(self, *_exc):
self.terminate()
def start(self):
"""
Launch TWS/IBG.
"""
util.run(self.startAsync())
def stop(self):
"""
Cleanly shutdown TWS/IBG.
"""
util.run(self.stopAsync())
def terminate(self):
"""
Terminate TWS/IBG.
"""
util.run(self.terminateAsync())
async def startAsync(self):
if self._proc:
return
self._logger.info('Starting')
# expand paths
d = self.dict()
for k, v in d.items():
if k.endswith('_PATH') or k.endswith('_INI'):
d[k] = os.path.expanduser(v)
if not d['TWS_CONFIG_PATH']:
d['TWS_CONFIG_PATH'] = d['TWS_PATH']
self.update(**d)
# run shell command
ext = 'bat' if os.sys.platform == 'win32' else 'sh'
cmd = f'{d["IBC_PATH"]}/Scripts/DisplayBannerAndLaunch.{ext}'
env = {**os.environ, **d}
self._proc = await asyncio.create_subprocess_exec(
cmd, env=env, stdout=asyncio.subprocess.PIPE)
self._monitor = asyncio.ensure_future(self.monitorAsync())
async def stopAsync(self):
if not self._proc:
return
self._logger.info('Stopping')
# read ibcontroller ini file to get controller port
txt = '[section]' + open(self.IBC_INI).read()
config = configparser.ConfigParser()
config.read_string(txt)
contrPort = config.getint('section', 'IbControllerPort')
_reader, writer = await asyncio.open_connection('127.0.0.1', contrPort)
writer.write(b'STOP')
await writer.drain()
writer.close()
await self._proc.wait()
self._proc = None
self._monitor.cancel()
self._monitor = None
async def terminateAsync(self):
if not self._proc:
return
self._logger.info('Terminating')
self._monitor.cancel()
self._monitor = None
with suppress(ProcessLookupError):
self._proc.terminate()
await self._proc.wait()
self._proc = None
async def monitorAsync(self):
while self._proc:
line = await self._proc.stdout.readline()
if not line:
break
self._logger.info(line.strip().decode())
class Watchdog(Object):
"""
Start, connect and watch over the TWS or gateway app and try to keep it
up and running. It is intended to be used in an event-driven
application that properly initializes itself upon (re-)connect.
It is not intended to be used in a notebook or in imperative-style code.
Do not expect Watchdog to magically shield you from reality. Do not use
Watchdog unless you understand what it does and doesn't do.
Args:
controller (Union[IBC, IBController]): (required) IBC or IBController
instance.
ib (IB): (required) IB instance to be used. Do no connect this
instance as Watchdog takes care of that.
host (str): Used for connecting IB instance.
port (int): Used for connecting IB instance.
clientId (int): Used for connecting IB instance.
connectTimeout (float): Used for connecting IB instance.
appStartupTime (float): Time (in seconds) that the app is given
to start up. Make sure that it is given ample time.
appTimeout (float): Timeout (in seconds) for network traffic idle time.
retryDelay (float): Time (in seconds) to restart app after a
previous failure.
The idea is to wait until there is no traffic coming from the app for
a certain amount of time (the ``appTimeout`` parameter). This triggers
a historical request to be placed just to see if the app is still alive
and well. If yes, then continue, if no then restart the whole app
and reconnect. Restarting will also occur directly on error 1100.
Example usage:
.. code-block:: python
def onConnected():
print(ib.accountValues())
ibc = IBC(974, gateway=True, tradingMode='paper')
ib = IB()
ib.connectedEvent += onConnected
watchdog = Watchdog(ibc, ib, port=4002)
watchdog.start()
IB.run()
Events:
* ``startingEvent`` (watchdog: :class:`.Watchdog`)
* ``startedEvent`` (watchdog: :class:`.Watchdog`)
* ``stoppingEvent`` (watchdog: :class:`.Watchdog`)
* ``stoppedEvent`` (watchdog: :class:`.Watchdog`)
* ``softTimeoutEvent`` (watchdog: :class:`.Watchdog`)
* ``hardTimeoutEvent`` (watchdog: :class:`.Watchdog`)
"""
events = [
'startingEvent', 'startedEvent', 'stoppingEvent', 'stoppedEvent',
'softTimeoutEvent', 'hardTimeoutEvent']
defaults = dict(
controller=None,
ib=None,
host='127.0.0.1',
port='7497',
clientId=1,
connectTimeout=2,
appStartupTime=30,
appTimeout=20,
retryDelay=2)
__slots__ = list(defaults.keys()) + events + ['_runner', '_logger']
def __init__(self, *args, **kwargs):
Object.__init__(self, *args, **kwargs)
Event.init(self, Watchdog.events)
if not self.controller:
raise ValueError('No controller supplied')
if not self.ib:
raise ValueError('No IB instance supplied')
if self.ib.isConnected():
raise ValueError('IB instance must not be connected')
assert 0 < self.appTimeout < 60
assert self.retryDelay > 0
self._runner = None
self._logger = logging.getLogger('ib_insync.Watchdog')
def start(self):
self._logger.info('Starting')
self.startingEvent.emit(self)
self._runner = asyncio.ensure_future(self.runAsync())
def stop(self):
self._logger.info('Stopping')
self.stoppingEvent.emit(self)
self.ib.disconnect()
self._runner = None
async def runAsync(self):
def onTimeout(idlePeriod):
if not waiter.done():
waiter.set_result(None)
def onError(reqId, errorCode, errorString, contract):
if errorCode == 1100 and not waiter.done():
waiter.set_exception(Warning('Error 1100'))
def onDisconnected():
if not waiter.done():
waiter.set_exception(Warning('Disconnected'))
while self._runner:
try:
await self.controller.startAsync()
await asyncio.sleep(self.appStartupTime)
await self.ib.connectAsync(
self.host, self.port, self.clientId, self.connectTimeout)
self.startedEvent.emit(self)
self.ib.setTimeout(self.appTimeout)
self.ib.timeoutEvent += onTimeout
self.ib.errorEvent += onError
self.ib.disconnectedEvent += onDisconnected
while self._runner:
waiter = asyncio.Future()
await waiter
# soft timeout, probe the app with a historical request
self._logger.debug('Soft timeout')
self.softTimeoutEvent.emit(self)
probe = self.ib.reqHistoricalDataAsync(
Forex('EURUSD'), '', '30 S', '5 secs',
'MIDPOINT', False)
bars = None
with suppress(asyncio.TimeoutError):
bars = await asyncio.wait_for(probe, 4)
if not bars:
self.hardTimeoutEvent.emit(self)
raise Warning('Hard timeout')
self.ib.setTimeout(self.appTimeout)
except ConnectionRefusedError:
pass
except Warning as w:
self._logger.warning(w)
except Exception as e:
self._logger.exception(e)
finally:
self.ib.timeoutEvent -= onTimeout
self.ib.errorEvent -= onError
self.ib.disconnectedEvent -= onDisconnected
await self.controller.terminateAsync()
self.stoppedEvent.emit(self)
if self._runner:
await asyncio.sleep(self.retryDelay)
if __name__ == '__main__':
asyncio.get_event_loop().set_debug(True)
util.logToConsole(logging.DEBUG)
ibc = IBC(974, gateway=True, tradingMode='paper')
# userid='edemo', password='demouser')
ib = IB()
app = Watchdog(ibc, ib, port=4002, appStartupTime=15, appTimeout=10)
app.start()
IB.run()
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
soracom/generated/cmd/roles_list_users.go
|
// Code generated by soracom-cli generate-cmd. DO NOT EDIT.
package cmd
import (
"net/url"
"os"
"github.com/spf13/cobra"
)
// RolesListUsersCmdOperatorId holds value of 'operator_id' option
var RolesListUsersCmdOperatorId string
// RolesListUsersCmdRoleId holds value of 'role_id' option
var RolesListUsersCmdRoleId string
func init() {
RolesListUsersCmd.Flags().StringVar(&RolesListUsersCmdOperatorId, "operator-id", "", TRAPI("operator_id"))
RolesListUsersCmd.Flags().StringVar(&RolesListUsersCmdRoleId, "role-id", "", TRAPI("role_id"))
RolesCmd.AddCommand(RolesListUsersCmd)
}
// RolesListUsersCmd defines 'list-users' subcommand
var RolesListUsersCmd = &cobra.Command{
Use: "list-users",
Short: TRAPI("/operators/{operator_id}/roles/{role_id}/users:get:summary"),
Long: TRAPI(`/operators/{operator_id}/roles/{role_id}/users:get:description`),
RunE: func(cmd *cobra.Command, args []string) error {
opt := &apiClientOptions{
BasePath: "/v1",
Language: getSelectedLanguage(),
}
ac := newAPIClient(opt)
if v := os.Getenv("SORACOM_VERBOSE"); v != "" {
ac.SetVerbose(true)
}
err := authHelper(ac, cmd, args)
if err != nil {
cmd.SilenceUsage = true
return err
}
param, err := collectRolesListUsersCmdParams(ac)
if err != nil {
return err
}
body, err := ac.callAPI(param)
if err != nil {
cmd.SilenceUsage = true
return err
}
if body == "" {
return nil
}
if rawOutput {
_, err = os.Stdout.Write([]byte(body))
} else {
return prettyPrintStringAsJSON(body)
}
return err
},
}
func collectRolesListUsersCmdParams(ac *apiClient) (*apiParams, error) {
var parsedBody interface{}
var err error
if RolesListUsersCmdOperatorId == "" {
RolesListUsersCmdOperatorId = ac.OperatorID
}
err = checkIfRequiredStringParameterIsSupplied("role_id", "role-id", "path", parsedBody, RolesListUsersCmdRoleId)
if err != nil {
return nil, err
}
return &apiParams{
method: "GET",
path: buildPathForRolesListUsersCmd("/operators/{operator_id}/roles/{role_id}/users"),
query: buildQueryForRolesListUsersCmd(),
noRetryOnError: noRetryOnError,
}, nil
}
func buildPathForRolesListUsersCmd(path string) string {
escapedOperatorId := url.PathEscape(RolesListUsersCmdOperatorId)
path = strReplace(path, "{"+"operator_id"+"}", escapedOperatorId, -1)
escapedRoleId := url.PathEscape(RolesListUsersCmdRoleId)
path = strReplace(path, "{"+"role_id"+"}", escapedRoleId, -1)
return path
}
func buildQueryForRolesListUsersCmd() url.Values {
result := url.Values{}
return result
}
|
[
"\"SORACOM_VERBOSE\""
] |
[] |
[
"SORACOM_VERBOSE"
] |
[]
|
["SORACOM_VERBOSE"]
|
go
| 1 | 0 | |
main.go
|
// CLI client for Shhh
// Shhh-cli source code: https://github.com/smallwat3r/shhh-cli
// Shhh source code: https://github.com/smallwat3r/shhh
// Author: Smallwat3r - Matthieu Petiteau <[email protected]>
// MIT License
//
// Copyright (c) 2020 Matthieu Petiteau
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"net/url"
"os"
"path"
"github.com/fatih/color"
)
var (
shhhVersion = "1.3.1"
)
// Create mode
const (
helpSecret = "Secret message to encrypt."
helpEncryptPassphrase = "Passphrase to encrypt secret."
helpExpire = "(opt) How long to keep the secret alive: 10m, 30m, 1h, 3h, 6h, 1d, 2d, 3d, 5d or 7d (default: 3d)."
helpTries = "(opt) Max nb of tries to open the secret: 3, 5 or 7 (default: 5)."
helpServer = "(opt) Shhh target server (ex: https://<server>.com)."
helpHaveibeenpwned = "(opt) Check passphrase against the haveibeenpwned API."
)
// Read mode
const (
helpLink = "URL link to access secret."
helpDecryptPassphrase = "Passphrase to decrypt secret."
)
func version() {
fmt.Printf("shhh-cli version %s\n\n", shhhVersion)
}
func usageCreate() string {
h := "Usage of create:"
h += "\n -h, --help Show create help message and exit."
h += "\n -m, --message <string> " + helpSecret
h += "\n -p, --passphrase <string> " + helpEncryptPassphrase
h += "\n -e, --expire <int> " + helpExpire
h += "\n -t, --tries <int> " + helpTries
h += "\n -h, --host <string> " + helpServer
h += "\n -s, --secure " + helpHaveibeenpwned
h += "\n\n example: shhh create -m [secret] -p [passphrase] -e 30m -t 3 -s\n\n"
return h
}
func usageRead() string {
h := "Usage of read:"
h += "\n -h, --help Show read help message and exit."
h += "\n -l, --link <string> " + helpLink
h += "\n -p, --passphrase <string> " + helpDecryptPassphrase
h += "\n\n example: shhh read -l [link] -p [passphrase]\n\n"
return h
}
func usage() {
h := "Create or read secrets from a Shhh server."
h += "\n\nFind more information at https://github.com/smallwat3r/shhh-cli/blob/master/README.md"
h += "\n\nUsage:"
h += "\n shhh [mode] [options]"
h += "\n\nOptions:"
h += "\n -h, --help Show help message and exit."
h += "\n -v, --version Show program version and exit."
h += "\n\nModes:"
h += "\n create Creates a secret message."
h += "\n read Read a secret message.\n\n"
h += usageCreate() + "\n"
h += usageRead()
fmt.Println(h)
}
func main() {
createCmd := flag.NewFlagSet("create", flag.ExitOnError)
createCmd.Usage = func() {
h := usageCreate()
fmt.Println(h)
os.Exit(0)
}
var secret string
createCmd.StringVar(&secret, "m", "", helpSecret)
createCmd.StringVar(&secret, "message", "", helpSecret)
var encryptPassphrase string
createCmd.StringVar(&encryptPassphrase, "p", "", helpEncryptPassphrase)
createCmd.StringVar(&encryptPassphrase, "passphrase", "", helpEncryptPassphrase)
var expire string
createCmd.StringVar(&expire, "e", "3d", helpExpire)
createCmd.StringVar(&expire, "expire", "3d", helpExpire)
var tries int
createCmd.IntVar(&tries, "t", 3, helpTries)
createCmd.IntVar(&tries, "tries", 3, helpTries)
var haveibeenpwned bool
createCmd.BoolVar(&haveibeenpwned, "s", false, helpHaveibeenpwned)
createCmd.BoolVar(&haveibeenpwned, "secure", false, helpHaveibeenpwned)
var server string
createCmd.StringVar(&server, "h", "", helpServer)
createCmd.StringVar(&server, "host", "", helpServer)
readCmd := flag.NewFlagSet("read", flag.ExitOnError)
readCmd.Usage = func() {
h := usageRead()
fmt.Println(h)
os.Exit(0)
}
var link string
readCmd.StringVar(&link, "l", "", helpLink)
readCmd.StringVar(&link, "link", "", helpLink)
var decryptPassphrase string
readCmd.StringVar(&decryptPassphrase, "p", "", helpDecryptPassphrase)
readCmd.StringVar(&decryptPassphrase, "passphrase", "", helpDecryptPassphrase)
if len(os.Args) == 1 {
version()
usage()
os.Exit(0)
}
switch os.Args[1] {
case "-h", "--help":
version()
usage()
os.Exit(0)
case "-v", "--version":
version()
os.Exit(0)
case "create":
createCmd.Parse(os.Args[2:])
case "read":
readCmd.Parse(os.Args[2:])
default:
fmt.Fprintf(os.Stderr, "%q is not valid command\n\n", os.Args[1])
os.Exit(127)
}
if createCmd.Parsed() {
if secret == "" {
fmt.Fprintf(
os.Stderr,
"Supply a message to encrypt using --message\n\n",
)
os.Exit(1)
}
if encryptPassphrase == "" {
fmt.Fprintf(
os.Stderr,
"Supply a passphrase using --passphrase\n\n",
)
os.Exit(1)
}
createSecret(
secret,
encryptPassphrase,
expire,
tries,
haveibeenpwned,
server,
)
}
if readCmd.Parsed() {
if link == "" {
fmt.Fprintf(os.Stderr, "Supply a link using --link\n\n")
os.Exit(1)
}
if decryptPassphrase == "" {
fmt.Fprintf(
os.Stderr,
"Supply a passphrase using --passphrase\n\n",
)
os.Exit(1)
}
readSecret(link, decryptPassphrase)
}
}
func createSecret(
secret string,
passphrase string,
expire string,
tries int,
haveibeenpwned bool,
server string,
) {
target := getTargetServer(server)
payload := map[string]interface{}{
"secret": secret,
"passphrase": passphrase,
"expire": expire,
"tries": tries,
"haveibeenpwned": haveibeenpwned,
}
bytesRepr, err := json.Marshal(payload)
if err != nil {
log.Fatalln(err)
}
resp, err := http.Post(target, "application/json", bytes.NewBuffer(bytesRepr))
if err != nil {
log.Fatalln(err)
}
expected := map[int]bool{200: true, 201: true, 422: true}
if !expected[resp.StatusCode] {
fmt.Fprintf(
os.Stderr,
"Failed to reach server: returned %d on %s\n\n",
resp.StatusCode,
target,
)
os.Exit(1)
}
var response map[string]interface{}
json.NewDecoder(resp.Body).Decode(&response)
result, ok := response["response"].(map[string]interface{})
if !ok {
fmt.Fprintf(os.Stderr, "Couldn't read response from server\n\n")
os.Exit(1)
}
switch result["status"] {
case "error":
color.Red("%s\n\n", result["details"].(string))
os.Exit(1)
case "created":
color.Green(separator(79))
color.Green("Secret link : %s", result["link"].(string))
color.Green("One time passphrase : %s", passphrase)
color.Green("Expires on : %s", result["expires_on"].(string))
color.Green("%s\n\n", separator(79))
os.Exit(0)
default:
fmt.Fprintf(os.Stderr, "Couldn't read response from server\n\n")
os.Exit(1)
}
}
func readSecret(link string, passphrase string) {
if !isUrl(link) {
fmt.Fprintf(os.Stderr, "Shhh server link URL invalid: %s\n\n", link)
os.Exit(1)
}
l, err := url.Parse(link)
if err != nil {
log.Fatalln(err)
}
host := l.Scheme + "://" + l.Host
p := l.Path
slug := path.Base(p)
apiUrl := host + "/api/secret"
u, err := url.Parse(apiUrl)
if err != nil {
log.Fatalln(err)
}
q, err := url.ParseQuery(u.RawQuery)
if err != nil {
log.Fatalln(err)
}
q.Add("slug", slug)
q.Add("passphrase", passphrase)
u.RawQuery = q.Encode()
readUrl := u.String()
resp, err := http.Get(readUrl)
if err != nil {
log.Fatalln(err)
}
expected := map[int]bool{200: true, 401: true, 404: true, 422: true}
if !expected[resp.StatusCode] {
fmt.Fprintf(
os.Stderr,
"Failed to reach server: returned %d on %s\n\n",
resp.StatusCode,
link,
)
os.Exit(1)
}
var response map[string]interface{}
json.NewDecoder(resp.Body).Decode(&response)
result, ok := response["response"].(map[string]interface{})
if !ok {
fmt.Fprintf(os.Stderr, "Couldn't read response from server\n\n")
os.Exit(1)
}
switch result["status"] {
case "error", "expired", "invalid":
color.Red("%s\n\n", result["msg"].(string))
os.Exit(1)
case "success":
color.Green(separator(79))
color.Green(result["msg"].(string))
color.Green("%s\n\n", separator(79))
os.Exit(0)
default:
fmt.Fprintf(os.Stderr, "Couldn't read response from server\n\n")
os.Exit(1)
}
}
func separator(length int) string {
sep := ""
for i := 0; i < length; i++ {
sep += "-"
}
return sep
}
func isUrl(str string) bool {
u, err := url.Parse(str)
return err == nil && u.Scheme != "" && u.Host != ""
}
// Get endpoint for the targeted server
func getTargetServer(server string) string {
target := os.Getenv("SHHH_SERVER")
if !(server == "") {
target = server
}
// Default Shhh server target if none specified nor in env or params
if target == "" {
return "https://shhh-encrypt.herokuapp.com/api/secret"
}
if !isUrl(target) {
fmt.Fprintf(
os.Stderr,
"Shhh server target URL invalid: %s\n\n",
target,
)
os.Exit(1)
}
return target + "/api/secret"
}
|
[
"\"SHHH_SERVER\""
] |
[] |
[
"SHHH_SERVER"
] |
[]
|
["SHHH_SERVER"]
|
go
| 1 | 0 | |
app/run.py
|
import os
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
def create_app():
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
from app.app import api_bp
app.register_blueprint(api_bp, url_prefix='/api')
from database.models import db, flask_bcrypt
db.init_app(app)
flask_bcrypt.init_app(app)
return app
if __name__ == "__main__":
app = create_app()
app.run(debug=True)
|
[] |
[] |
[
"APP_SETTINGS"
] |
[]
|
["APP_SETTINGS"]
|
python
| 1 | 0 | |
backend/manager/modules/builtin-extensions/src/main/java/org/ovirt/engine/extensions/aaa/builtin/kerberosldap/KerberosManager.java
|
package org.ovirt.engine.extensions.aaa.builtin.kerberosldap;
import java.io.File;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
/**
* Manage the container's Kerberos initialization.
*
*/
public class KerberosManager {
private static final Log log = LogFactory.getLog(KerberosManager.class);
private static volatile KerberosManager instance = null;
public static KerberosManager getInstance() {
if (instance == null) {
synchronized (KerberosManager.class) {
if (instance == null) {
instance = new KerberosManager();
}
}
}
return instance;
}
private KerberosManager() {
String engineEtc = System.getenv("ENGINE_ETC");
if (engineEtc == null) {
engineEtc = "/etc/ovirt-engine";
}
File krb5File = new File(engineEtc, "krb5.conf");
if (!krb5File.exists()) {
String msg = String.format("Failed loading kerberos settings from File %1$s.", krb5File.getAbsolutePath());
log.error(msg);
throw new RuntimeException(msg);
}
System.setProperty("java.security.krb5.conf", krb5File.getAbsolutePath());
System.setProperty("sun.security.krb5.msinterop.kstring", "true");
}
}
|
[
"\"ENGINE_ETC\""
] |
[] |
[
"ENGINE_ETC"
] |
[]
|
["ENGINE_ETC"]
|
java
| 1 | 0 | |
server.go
|
package main
import (
"net/http"
"os"
"github.com/byuoitav/av-api/base"
"github.com/byuoitav/av-api/handlers"
"github.com/byuoitav/av-api/health"
avapi "github.com/byuoitav/av-api/init"
hub "github.com/byuoitav/central-event-system/hub/base"
"github.com/byuoitav/central-event-system/messenger"
"github.com/byuoitav/common"
"github.com/byuoitav/common/log"
"github.com/byuoitav/common/nerr"
"github.com/byuoitav/common/status/databasestatus"
"github.com/byuoitav/common/v2/auth"
"github.com/byuoitav/common/v2/events"
)
func main() {
var nerr *nerr.E
base.Messenger, nerr = messenger.BuildMessenger(os.Getenv("HUB_ADDRESS"), hub.Messenger, 1000)
if nerr != nil {
log.L.Errorf("unable to connect to the hub: %s", nerr.String())
}
go func() {
err := avapi.CheckRoomInitialization()
if err != nil {
base.PublishError("Fail to run init script. Terminating. ERROR:"+err.Error(), events.Error, os.Getenv("SYSTEM_ID"))
log.L.Errorf("Could not initialize room. Error: %v\n", err.Error())
}
}()
port := ":8000"
router := common.NewRouter()
router.GET("/mstatus", databasestatus.Handler)
router.GET("/status", databasestatus.Handler)
// PUT requests
router.PUT("/buildings/:building/rooms/:room", handlers.SetRoomState, auth.AuthorizeRequest("write-state", "room", handlers.GetRoomResource))
// room status
router.GET("/buildings/:building/rooms/:room", handlers.GetRoomState, auth.AuthorizeRequest("read-state", "room", handlers.GetRoomResource))
router.GET("/buildings/:building/rooms/:room/configuration", handlers.GetRoomByNameAndBuilding, auth.AuthorizeRequest("read-config", "room", handlers.GetRoomResource))
router.PUT("/log-level/:level", log.SetLogLevel)
router.GET("/log-level", log.GetLogLevel)
server := http.Server{
Addr: port,
MaxHeaderBytes: 1024 * 10,
}
go health.StartupCheckAndReport()
router.StartServer(&server)
}
|
[
"\"HUB_ADDRESS\"",
"\"SYSTEM_ID\""
] |
[] |
[
"HUB_ADDRESS",
"SYSTEM_ID"
] |
[]
|
["HUB_ADDRESS", "SYSTEM_ID"]
|
go
| 2 | 0 | |
cmd/prometheus/main.go
|
// Copyright 2015 The Prometheus 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.
// The main package for the Prometheus server executable.
package main
import (
"context"
"crypto/md5"
"encoding/json"
"fmt"
"net"
"net/http"
_ "net/http/pprof" // Comment this line to disable pprof endpoint.
"net/url"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/oklog/oklog/pkg/group"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/common/version"
"gopkg.in/alecthomas/kingpin.v2"
k8s_runtime "k8s.io/apimachinery/pkg/util/runtime"
"github.com/mwitkow/go-conntrack"
"github.com/prometheus/common/promlog"
promlogflag "github.com/prometheus/common/promlog/flag"
"github.com/loggregator/prometheus/config"
"github.com/loggregator/prometheus/discovery"
sd_config "github.com/loggregator/prometheus/discovery/config"
"github.com/loggregator/prometheus/notifier"
"github.com/loggregator/prometheus/promql"
"github.com/loggregator/prometheus/retrieval"
"github.com/loggregator/prometheus/rules"
"github.com/loggregator/prometheus/storage"
"github.com/loggregator/prometheus/storage/remote"
"github.com/loggregator/prometheus/storage/tsdb"
"github.com/loggregator/prometheus/util/strutil"
"github.com/loggregator/prometheus/web"
)
var (
configSuccess = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "prometheus",
Name: "config_last_reload_successful",
Help: "Whether the last configuration reload attempt was successful.",
})
configSuccessTime = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "prometheus",
Name: "config_last_reload_success_timestamp_seconds",
Help: "Timestamp of the last successful configuration reload.",
})
)
func init() {
prometheus.MustRegister(version.NewCollector("prometheus"))
}
func main() {
if os.Getenv("DEBUG") != "" {
runtime.SetBlockProfileRate(20)
runtime.SetMutexProfileFraction(20)
}
cfg := struct {
configFile string
localStoragePath string
notifier notifier.Options
notifierTimeout model.Duration
queryEngine promql.EngineOptions
web web.Options
tsdb tsdb.Options
lookbackDelta model.Duration
webTimeout model.Duration
queryTimeout model.Duration
prometheusURL string
logLevel promlog.AllowedLevel
}{
notifier: notifier.Options{
Registerer: prometheus.DefaultRegisterer,
},
queryEngine: promql.EngineOptions{
Metrics: prometheus.DefaultRegisterer,
},
}
a := kingpin.New(filepath.Base(os.Args[0]), "The Prometheus monitoring server")
a.Version(version.Print("prometheus"))
a.HelpFlag.Short('h')
a.Flag("config.file", "Prometheus configuration file path.").
Default("prometheus.yml").StringVar(&cfg.configFile)
a.Flag("web.listen-address", "Address to listen on for UI, API, and telemetry.").
Default("0.0.0.0:9090").StringVar(&cfg.web.ListenAddress)
a.Flag("web.read-timeout",
"Maximum duration before timing out read of the request, and closing idle connections.").
Default("5m").SetValue(&cfg.webTimeout)
a.Flag("web.max-connections", "Maximum number of simultaneous connections.").
Default("512").IntVar(&cfg.web.MaxConnections)
a.Flag("web.external-url",
"The URL under which Prometheus is externally reachable (for example, if Prometheus is served via a reverse proxy). Used for generating relative and absolute links back to Prometheus itself. If the URL has a path portion, it will be used to prefix all HTTP endpoints served by Prometheus. If omitted, relevant URL components will be derived automatically.").
PlaceHolder("<URL>").StringVar(&cfg.prometheusURL)
a.Flag("web.route-prefix",
"Prefix for the internal routes of web endpoints. Defaults to path of --web.external-url.").
PlaceHolder("<path>").StringVar(&cfg.web.RoutePrefix)
a.Flag("web.user-assets", "Path to static asset directory, available at /user.").
PlaceHolder("<path>").StringVar(&cfg.web.UserAssetsPath)
a.Flag("web.enable-lifecycle", "Enable shutdown and reload via HTTP request.").
Default("false").BoolVar(&cfg.web.EnableLifecycle)
a.Flag("web.enable-admin-api", "Enables API endpoints for admin control actions.").
Default("false").BoolVar(&cfg.web.EnableAdminAPI)
a.Flag("web.console.templates", "Path to the console template directory, available at /consoles.").
Default("consoles").StringVar(&cfg.web.ConsoleTemplatesPath)
a.Flag("web.console.libraries", "Path to the console library directory.").
Default("console_libraries").StringVar(&cfg.web.ConsoleLibrariesPath)
a.Flag("storage.tsdb.path", "Base path for metrics storage.").
Default("data/").StringVar(&cfg.localStoragePath)
a.Flag("storage.tsdb.min-block-duration", "Minimum duration of a data block before being persisted. For use in testing.").
Hidden().Default("2h").SetValue(&cfg.tsdb.MinBlockDuration)
a.Flag("storage.tsdb.max-block-duration",
"Maximum duration compacted blocks may span. For use in testing. (Defaults to 10% of the retention period).").
Hidden().PlaceHolder("<duration>").SetValue(&cfg.tsdb.MaxBlockDuration)
a.Flag("storage.tsdb.retention", "How long to retain samples in the storage.").
Default("15d").SetValue(&cfg.tsdb.Retention)
a.Flag("storage.tsdb.no-lockfile", "Do not create lockfile in data directory.").
Default("false").BoolVar(&cfg.tsdb.NoLockfile)
a.Flag("alertmanager.notification-queue-capacity", "The capacity of the queue for pending alert manager notifications.").
Default("10000").IntVar(&cfg.notifier.QueueCapacity)
a.Flag("alertmanager.timeout", "Timeout for sending alerts to Alertmanager.").
Default("10s").SetValue(&cfg.notifierTimeout)
a.Flag("query.lookback-delta", "The delta difference allowed for retrieving metrics during expression evaluations.").
Default("5m").SetValue(&cfg.lookbackDelta)
a.Flag("query.timeout", "Maximum time a query may take before being aborted.").
Default("2m").SetValue(&cfg.queryTimeout)
a.Flag("query.max-concurrency", "Maximum number of queries executed concurrently.").
Default("20").IntVar(&cfg.queryEngine.MaxConcurrentQueries)
promlogflag.AddFlags(a, &cfg.logLevel)
_, err := a.Parse(os.Args[1:])
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "Error parsing commandline arguments"))
a.Usage(os.Args[1:])
os.Exit(2)
}
cfg.web.ExternalURL, err = computeExternalURL(cfg.prometheusURL, cfg.web.ListenAddress)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "parse external URL %q", cfg.prometheusURL))
os.Exit(2)
}
cfg.web.ReadTimeout = time.Duration(cfg.webTimeout)
// Default -web.route-prefix to path of -web.external-url.
if cfg.web.RoutePrefix == "" {
cfg.web.RoutePrefix = cfg.web.ExternalURL.Path
}
// RoutePrefix must always be at least '/'.
cfg.web.RoutePrefix = "/" + strings.Trim(cfg.web.RoutePrefix, "/")
if cfg.tsdb.MaxBlockDuration == 0 {
cfg.tsdb.MaxBlockDuration = cfg.tsdb.Retention / 10
}
promql.LookbackDelta = time.Duration(cfg.lookbackDelta)
cfg.queryEngine.Timeout = time.Duration(cfg.queryTimeout)
logger := promlog.New(cfg.logLevel)
// XXX(fabxc): Kubernetes does background logging which we can only customize by modifying
// a global variable.
// Ultimately, here is the best place to set it.
k8s_runtime.ErrorHandlers = []func(error){
func(err error) {
level.Error(log.With(logger, "component", "k8s_client_runtime")).Log("err", err)
},
}
level.Info(logger).Log("msg", "Starting Prometheus", "version", version.Info())
level.Info(logger).Log("build_context", version.BuildContext())
level.Info(logger).Log("host_details", Uname())
level.Info(logger).Log("fd_limits", FdLimits())
var (
localStorage = &tsdb.ReadyStorage{}
remoteStorage = remote.NewStorage(log.With(logger, "component", "remote"), localStorage.StartTime)
fanoutStorage = storage.NewFanout(logger, localStorage, remoteStorage)
)
cfg.queryEngine.Logger = log.With(logger, "component", "query engine")
var (
ctxWeb, cancelWeb = context.WithCancel(context.Background())
ctxRule = context.Background()
notifier = notifier.New(&cfg.notifier, log.With(logger, "component", "notifier"))
discoveryManagerScrape = discovery.NewManager(log.With(logger, "component", "discovery manager scrape"))
discoveryManagerNotify = discovery.NewManager(log.With(logger, "component", "discovery manager notify"))
scrapeManager = retrieval.NewScrapeManager(log.With(logger, "component", "scrape manager"), fanoutStorage)
queryEngine = promql.NewEngine(fanoutStorage, &cfg.queryEngine)
ruleManager = rules.NewManager(&rules.ManagerOptions{
Appendable: fanoutStorage,
QueryFunc: rules.EngineQueryFunc(queryEngine),
NotifyFunc: sendAlerts(notifier, cfg.web.ExternalURL.String()),
Context: ctxRule,
ExternalURL: cfg.web.ExternalURL,
Registerer: prometheus.DefaultRegisterer,
Logger: log.With(logger, "component", "rule manager"),
})
)
cfg.web.Context = ctxWeb
cfg.web.TSDB = localStorage.Get
cfg.web.Storage = fanoutStorage
cfg.web.QueryEngine = queryEngine
cfg.web.ScrapeManager = scrapeManager
cfg.web.RuleManager = ruleManager
cfg.web.Notifier = notifier
cfg.web.Version = &web.PrometheusVersion{
Version: version.Version,
Revision: version.Revision,
Branch: version.Branch,
BuildUser: version.BuildUser,
BuildDate: version.BuildDate,
GoVersion: version.GoVersion,
}
cfg.web.Flags = map[string]string{}
for _, f := range a.Model().Flags {
cfg.web.Flags[f.Name] = f.Value.String()
}
// Depends on cfg.web.ScrapeManager so needs to be after cfg.web.ScrapeManager = scrapeManager
webHandler := web.New(log.With(logger, "component", "web"), &cfg.web)
// Monitor outgoing connections on default transport with conntrack.
http.DefaultTransport.(*http.Transport).DialContext = conntrack.NewDialContextFunc(
conntrack.DialWithTracing(),
)
reloaders := []func(cfg *config.Config) error{
remoteStorage.ApplyConfig,
webHandler.ApplyConfig,
// The Scrape and notifier managers need to reload before the Discovery manager as
// they need to read the most updated config when receiving the new targets list.
notifier.ApplyConfig,
scrapeManager.ApplyConfig,
func(cfg *config.Config) error {
c := make(map[string]sd_config.ServiceDiscoveryConfig)
for _, v := range cfg.ScrapeConfigs {
c[v.JobName] = v.ServiceDiscoveryConfig
}
return discoveryManagerScrape.ApplyConfig(c)
},
func(cfg *config.Config) error {
c := make(map[string]sd_config.ServiceDiscoveryConfig)
for _, v := range cfg.AlertingConfig.AlertmanagerConfigs {
// AlertmanagerConfigs doesn't hold an unique identifier so we use the config hash as the identifier.
b, err := json.Marshal(v)
if err != nil {
return err
}
c[fmt.Sprintf("%x", md5.Sum(b))] = v.ServiceDiscoveryConfig
}
return discoveryManagerNotify.ApplyConfig(c)
},
func(cfg *config.Config) error {
// Get all rule files matching the configuration oaths.
var files []string
for _, pat := range cfg.RuleFiles {
fs, err := filepath.Glob(pat)
if err != nil {
// The only error can be a bad pattern.
return fmt.Errorf("error retrieving rule files for %s: %s", pat, err)
}
files = append(files, fs...)
}
return ruleManager.Update(time.Duration(cfg.GlobalConfig.EvaluationInterval), files)
},
}
prometheus.MustRegister(configSuccess)
prometheus.MustRegister(configSuccessTime)
// Start all components while we wait for TSDB to open but only load
// initial config and mark ourselves as ready after it completed.
dbOpen := make(chan struct{})
// sync.Once is used to make sure we can close the channel at different execution stages(SIGTERM or when the config is loaded).
type closeOnce struct {
C chan struct{}
once sync.Once
Close func()
}
// Wait until the server is ready to handle reloading.
reloadReady := &closeOnce{
C: make(chan struct{}),
}
reloadReady.Close = func() {
reloadReady.once.Do(func() {
close(reloadReady.C)
})
}
var g group.Group
{
term := make(chan os.Signal)
signal.Notify(term, os.Interrupt, syscall.SIGTERM)
cancel := make(chan struct{})
g.Add(
func() error {
// Don't forget to release the reloadReady channel so that waiting blocks can exit normally.
select {
case <-term:
level.Warn(logger).Log("msg", "Received SIGTERM, exiting gracefully...")
reloadReady.Close()
case <-webHandler.Quit():
level.Warn(logger).Log("msg", "Received termination request via web service, exiting gracefully...")
case <-cancel:
reloadReady.Close()
break
}
return nil
},
func(err error) {
close(cancel)
},
)
}
{
ctx, cancel := context.WithCancel(context.Background())
g.Add(
func() error {
err := discoveryManagerScrape.Run(ctx)
level.Info(logger).Log("msg", "Scrape discovery manager stopped")
return err
},
func(err error) {
level.Info(logger).Log("msg", "Stopping scrape discovery manager...")
cancel()
},
)
}
{
ctx, cancel := context.WithCancel(context.Background())
g.Add(
func() error {
err := discoveryManagerNotify.Run(ctx)
level.Info(logger).Log("msg", "Notify discovery manager stopped")
return err
},
func(err error) {
level.Info(logger).Log("msg", "Stopping notify discovery manager...")
cancel()
},
)
}
{
g.Add(
func() error {
// When the scrape manager receives a new targets list
// it needs to read a valid config for each job.
// It depends on the config being in sync with the discovery manager so
// we wait until the config is fully loaded.
select {
case <-reloadReady.C:
break
}
err := scrapeManager.Run(discoveryManagerScrape.SyncCh())
level.Info(logger).Log("msg", "Scrape manager stopped")
return err
},
func(err error) {
// Scrape manager needs to be stopped before closing the local TSDB
// so that it doesn't try to write samples to a closed storage.
level.Info(logger).Log("msg", "Stopping scrape manager...")
scrapeManager.Stop()
},
)
}
{
// Make sure that sighup handler is registered with a redirect to the channel before the potentially
// long and synchronous tsdb init.
hup := make(chan os.Signal)
signal.Notify(hup, syscall.SIGHUP)
cancel := make(chan struct{})
g.Add(
func() error {
select {
case <-reloadReady.C:
break
}
for {
select {
case <-hup:
if err := reloadConfig(cfg.configFile, logger, reloaders...); err != nil {
level.Error(logger).Log("msg", "Error reloading config", "err", err)
}
case rc := <-webHandler.Reload():
if err := reloadConfig(cfg.configFile, logger, reloaders...); err != nil {
level.Error(logger).Log("msg", "Error reloading config", "err", err)
rc <- err
} else {
rc <- nil
}
case <-cancel:
return nil
}
}
},
func(err error) {
close(cancel)
},
)
}
{
cancel := make(chan struct{})
g.Add(
func() error {
select {
case <-dbOpen:
break
// In case a shutdown is initiated before the dbOpen is released
case <-cancel:
reloadReady.Close()
return nil
}
if err := reloadConfig(cfg.configFile, logger, reloaders...); err != nil {
return fmt.Errorf("Error loading config %s", err)
}
reloadReady.Close()
webHandler.Ready()
level.Info(logger).Log("msg", "Server is ready to receive web requests.")
<-cancel
return nil
},
func(err error) {
close(cancel)
},
)
}
{
cancel := make(chan struct{})
g.Add(
func() error {
level.Info(logger).Log("msg", "Starting TSDB ...")
db, err := tsdb.Open(
cfg.localStoragePath,
log.With(logger, "component", "tsdb"),
prometheus.DefaultRegisterer,
&cfg.tsdb,
)
if err != nil {
return fmt.Errorf("Opening storage failed %s", err)
}
level.Info(logger).Log("msg", "TSDB started")
startTimeMargin := int64(2 * time.Duration(cfg.tsdb.MinBlockDuration).Seconds() * 1000)
localStorage.Set(db, startTimeMargin)
close(dbOpen)
<-cancel
return nil
},
func(err error) {
if err := fanoutStorage.Close(); err != nil {
level.Error(logger).Log("msg", "Error stopping storage", "err", err)
}
close(cancel)
},
)
}
{
g.Add(
func() error {
if err := webHandler.Run(ctxWeb); err != nil {
return fmt.Errorf("Error starting web server: %s", err)
}
return nil
},
func(err error) {
// Keep this interrupt before the ruleManager.Stop().
// Shutting down the query engine before the rule manager will cause pending queries
// to be canceled and ensures a quick shutdown of the rule manager.
cancelWeb()
},
)
}
{
// TODO(krasi) refactor ruleManager.Run() to be blocking to avoid using an extra blocking channel.
cancel := make(chan struct{})
g.Add(
func() error {
ruleManager.Run()
<-cancel
return nil
},
func(err error) {
ruleManager.Stop()
close(cancel)
},
)
}
{
// Calling notifier.Stop() before ruleManager.Stop() will cause a panic if the ruleManager isn't running,
// so keep this interrupt after the ruleManager.Stop().
g.Add(
func() error {
// When the notifier manager receives a new targets list
// it needs to read a valid config for each job.
// It depends on the config being in sync with the discovery manager
// so we wait until the config is fully loaded.
select {
case <-reloadReady.C:
break
}
notifier.Run(discoveryManagerNotify.SyncCh())
level.Info(logger).Log("msg", "Notifier manager stopped")
return nil
},
func(err error) {
notifier.Stop()
},
)
}
if err := g.Run(); err != nil {
level.Error(logger).Log("err", err)
}
level.Info(logger).Log("msg", "See you next time!")
}
func reloadConfig(filename string, logger log.Logger, rls ...func(*config.Config) error) (err error) {
level.Info(logger).Log("msg", "Loading configuration file", "filename", filename)
defer func() {
if err == nil {
configSuccess.Set(1)
configSuccessTime.Set(float64(time.Now().Unix()))
} else {
configSuccess.Set(0)
}
}()
conf, err := config.LoadFile(filename)
if err != nil {
return fmt.Errorf("couldn't load configuration (--config.file=%s): %v", filename, err)
}
failed := false
for _, rl := range rls {
if err := rl(conf); err != nil {
level.Error(logger).Log("msg", "Failed to apply configuration", "err", err)
failed = true
}
}
if failed {
return fmt.Errorf("one or more errors occurred while applying the new configuration (--config.file=%s)", filename)
}
return nil
}
func startsOrEndsWithQuote(s string) bool {
return strings.HasPrefix(s, "\"") || strings.HasPrefix(s, "'") ||
strings.HasSuffix(s, "\"") || strings.HasSuffix(s, "'")
}
// computeExternalURL computes a sanitized external URL from a raw input. It infers unset
// URL parts from the OS and the given listen address.
func computeExternalURL(u, listenAddr string) (*url.URL, error) {
if u == "" {
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
_, port, err := net.SplitHostPort(listenAddr)
if err != nil {
return nil, err
}
u = fmt.Sprintf("http://%s:%s/", hostname, port)
}
if startsOrEndsWithQuote(u) {
return nil, fmt.Errorf("URL must not begin or end with quotes")
}
eu, err := url.Parse(u)
if err != nil {
return nil, err
}
ppref := strings.TrimRight(eu.Path, "/")
if ppref != "" && !strings.HasPrefix(ppref, "/") {
ppref = "/" + ppref
}
eu.Path = ppref
return eu, nil
}
// sendAlerts implements a the rules.NotifyFunc for a Notifier.
// It filters any non-firing alerts from the input.
func sendAlerts(n *notifier.Notifier, externalURL string) rules.NotifyFunc {
return func(ctx context.Context, expr string, alerts ...*rules.Alert) error {
var res []*notifier.Alert
for _, alert := range alerts {
// Only send actually firing alerts.
if alert.State == rules.StatePending {
continue
}
a := ¬ifier.Alert{
StartsAt: alert.FiredAt,
Labels: alert.Labels,
Annotations: alert.Annotations,
GeneratorURL: externalURL + strutil.TableLinkForExpression(expr),
}
if !alert.ResolvedAt.IsZero() {
a.EndsAt = alert.ResolvedAt
}
res = append(res, a)
}
if len(alerts) > 0 {
n.Send(res...)
}
return nil
}
}
|
[
"\"DEBUG\""
] |
[] |
[
"DEBUG"
] |
[]
|
["DEBUG"]
|
go
| 1 | 0 | |
go.go
|
package common
import (
"os"
"path"
"path/filepath"
"runtime"
"sort"
"strings"
)
const (
pathSeparator = string(os.PathSeparator) // OS-specific path separator
pathListSeparator = string(os.PathListSeparator) // OS-specific path list separator
)
// GetAPIPath gets the Go source code path $GOROOT/src.
func (*DuduGo) GetApiPath() string {
return filepath.FromSlash(path.Clean(runtime.GOROOT() + "/src"))
}
// IsAPI determines whether the specified path belongs to Go API.
func (*DuduGo) IsAPI(path string) bool {
apiPath := Go.GetApiPath()
return strings.HasPrefix(filepath.FromSlash(path), apiPath)
}
// GetGoFormats gets Go format tools. It may return ["gofmt", "goimports"].
func (*DuduGo) GetGoFormats() []string {
ret := []string{"gofmt"}
p := Go.GetExecutableInGOBIN("goimports")
if File.IsExist(p) {
ret = append(ret, "goimports")
}
sort.Strings(ret)
return ret
}
// GetExecutableInGOBIN gets executable file under GOBIN path.
//
// The specified executable should not with extension, this function will append .exe if on Windows.
func (*DuduGo) GetExecutableInGOBIN(executable string) string {
if OS.IsWindows() {
executable += ".exe"
}
gopaths := filepath.SplitList(os.Getenv("GOPATH"))
for _, gopath := range gopaths {
// $GOPATH/bin/$GOOS_$GOARCH/executable
ret := gopath + pathSeparator + "bin" + pathSeparator +
os.Getenv("GOOS") + "_" + os.Getenv("GOARCH") + pathSeparator + executable
if File.IsExist(ret) {
return ret
}
// $GOPATH/bin/{runtime.GOOS}_{runtime.GOARCH}/executable
ret = gopath + pathSeparator + "bin" + pathSeparator +
runtime.GOOS + "_" + runtime.GOARCH + pathSeparator + executable
if File.IsExist(ret) {
return ret
}
// $GOPATH/bin/executable
ret = gopath + pathSeparator + "bin" + pathSeparator + executable
if File.IsExist(ret) {
return ret
}
}
// $GOBIN/executable
gobin := os.Getenv("GOBIN")
if "" != gobin {
ret := gobin + pathSeparator + executable
if File.IsExist(ret) {
return ret
}
}
return "./" + executable
}
|
[
"\"GOPATH\"",
"\"GOOS\"",
"\"GOARCH\"",
"\"GOBIN\""
] |
[] |
[
"GOPATH",
"GOARCH",
"GOOS",
"GOBIN"
] |
[]
|
["GOPATH", "GOARCH", "GOOS", "GOBIN"]
|
go
| 4 | 0 | |
django/utils/autoreload.py
|
# Autoreloading launcher.
# Borrowed from Peter Hunt and the CherryPy project (http://www.cherrypy.org).
# Some taken from Ian Bicking's Paste (http://pythonpaste.org/).
#
# Portions copyright (c) 2004, CherryPy Team ([email protected])
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the CherryPy Team nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os, sys, time, signal
try:
import thread
except ImportError:
import dummy_thread as thread
# This import does nothing, but it's necessary to avoid some race conditions
# in the threading module. See http://code.djangoproject.com/ticket/2330 .
try:
import threading
except ImportError:
pass
try:
import termios
except ImportError:
termios = None
RUN_RELOADER = True
_mtimes = {}
_win = (sys.platform == "win32")
def code_changed():
global _mtimes, _win
for filename in filter(lambda v: v, map(lambda m: getattr(m, "__file__", None), sys.modules.values())):
if filename.endswith(".pyc") or filename.endswith(".pyo"):
filename = filename[:-1]
if filename.endswith("$py.class"):
filename = filename[:-9] + ".py"
if not os.path.exists(filename):
continue # File might be in an egg, so it can't be reloaded.
stat = os.stat(filename)
mtime = stat.st_mtime
if _win:
mtime -= stat.st_ctime
if filename not in _mtimes:
_mtimes[filename] = mtime
continue
if mtime != _mtimes[filename]:
_mtimes = {}
return True
return False
def ensure_echo_on():
if termios:
fd = sys.stdin
if fd.isatty():
attr_list = termios.tcgetattr(fd)
if not attr_list[3] & termios.ECHO:
attr_list[3] |= termios.ECHO
if hasattr(signal, 'SIGTTOU'):
old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
else:
old_handler = None
termios.tcsetattr(fd, termios.TCSANOW, attr_list)
if old_handler is not None:
signal.signal(signal.SIGTTOU, old_handler)
def reloader_thread():
ensure_echo_on()
while RUN_RELOADER:
if code_changed():
sys.exit(3) # force reload
time.sleep(1)
def restart_with_reloader():
while True:
args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions] + sys.argv
if sys.platform == "win32":
args = ['"%s"' % arg for arg in args]
new_environ = os.environ.copy()
new_environ["RUN_MAIN"] = 'true'
exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ)
if exit_code != 3:
return exit_code
def python_reloader(main_func, args, kwargs):
if os.environ.get("RUN_MAIN") == "true":
thread.start_new_thread(main_func, args, kwargs)
try:
reloader_thread()
except KeyboardInterrupt:
pass
else:
try:
sys.exit(restart_with_reloader())
except KeyboardInterrupt:
pass
def jython_reloader(main_func, args, kwargs):
from _systemrestart import SystemRestart
thread.start_new_thread(main_func, args)
while True:
if code_changed():
raise SystemRestart
time.sleep(1)
def main(main_func, args=None, kwargs=None):
if args is None:
args = ()
if kwargs is None:
kwargs = {}
if sys.platform.startswith('java'):
reloader = jython_reloader
else:
reloader = python_reloader
reloader(main_func, args, kwargs)
|
[] |
[] |
[
"RUN_MAIN"
] |
[]
|
["RUN_MAIN"]
|
python
| 1 | 0 | |
utils/utils.go
|
// Copyright 2021 NetApp, Inc. All Rights Reserved.
package utils
import (
"context"
"fmt"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"regexp"
"sort"
"strconv"
"strings"
log "github.com/sirupsen/logrus"
"go.uber.org/multierr"
. "github.com/netapp/trident/logger"
)
const (
// Linux is a constant value for the runtime.GOOS that represents the Linux OS
Linux = "linux"
// Windows is a constant value for the runtime.GOOS that represents the Windows OS
Windows = "windows"
// Darwin is a constant value for the runtime.GOOS that represents Apple MacOS
Darwin = "darwin"
PrepPending NodePrepStatus = "pending"
PrepRunning NodePrepStatus = "running"
PrepCompleted NodePrepStatus = "completed"
PrepFailed NodePrepStatus = "failed"
PrepOutdated NodePrepStatus = "outdated"
PrepPreConfigured NodePrepStatus = "preconfigured"
Centos = "centos"
RHEL = "rhel"
Ubuntu = "ubuntu"
)
// ///////////////////////////////////////////////////////////////////////////
//
// Binary units
//
// ///////////////////////////////////////////////////////////////////////////
type sizeUnit2 []string
func (s sizeUnit2) Len() int {
return len(s)
}
func (s sizeUnit2) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sizeUnit2) Less(i, j int) bool {
return len(s[i]) > len(s[j])
}
var lookupTable2 = make(map[string]int)
var units2 = sizeUnit2{}
func init() {
// populate the lookup table for binary suffixes
lookupTable2["k"] = 1
lookupTable2["ki"] = 1
lookupTable2["kib"] = 1
lookupTable2["m"] = 2
lookupTable2["mi"] = 2
lookupTable2["mib"] = 2
lookupTable2["g"] = 3
lookupTable2["gi"] = 3
lookupTable2["gib"] = 3
lookupTable2["t"] = 4
lookupTable2["ti"] = 4
lookupTable2["tib"] = 4
lookupTable2["p"] = 5
lookupTable2["pi"] = 5
lookupTable2["pib"] = 5
lookupTable2["e"] = 6
lookupTable2["ei"] = 6
lookupTable2["eib"] = 6
lookupTable2["z"] = 7
lookupTable2["zi"] = 7
lookupTable2["zib"] = 7
lookupTable2["y"] = 8
lookupTable2["yi"] = 8
lookupTable2["yib"] = 8
// The slice of units is used to ensure that they are accessed by suffix from longest to
// shortest, i.e. match 'tib' before matching 'b'.
for unit := range lookupTable2 {
units2 = append(units2, unit)
}
sort.Sort(units2)
}
// ///////////////////////////////////////////////////////////////////////////
//
// SI units
//
// ///////////////////////////////////////////////////////////////////////////
type sizeUnit10 []string
func (s sizeUnit10) Len() int {
return len(s)
}
func (s sizeUnit10) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sizeUnit10) Less(i, j int) bool {
return len(s[i]) > len(s[j])
}
var lookupTable10 = make(map[string]int)
var units10 = sizeUnit10{}
func init() {
// populate the lookup table for SI suffixes
lookupTable10["b"] = 0
lookupTable10["bytes"] = 0
lookupTable10["kb"] = 1
lookupTable10["mb"] = 2
lookupTable10["gb"] = 3
lookupTable10["tb"] = 4
lookupTable10["pb"] = 5
lookupTable10["eb"] = 6
lookupTable10["zb"] = 7
lookupTable10["yb"] = 8
// The slice of units is used to ensure that they are accessed by suffix from longest to
// shortest, i.e. match 'tib' before matching 'b'.
for unit := range lookupTable10 {
units10 = append(units10, unit)
}
sort.Sort(units10)
}
// Pow is an integer version of exponentiation; existing builtin is float, we needed an int version.
func Pow(x int64, y int) int64 {
if y == 0 {
return 1
}
result := x
for n := 1; n < y; n++ {
result = result * x
}
return result
}
// ConvertSizeToBytes converts size to bytes; see also https://en.wikipedia.org/wiki/Kilobyte
func ConvertSizeToBytes(s string) (string, error) {
// make lowercase so units detection always works
s = strings.TrimSpace(strings.ToLower(s))
// first look for binary units
for _, unit := range units2 {
if strings.HasSuffix(s, unit) {
s = strings.TrimSuffix(s, unit)
if i, err := strconv.ParseInt(s, 10, 0); err != nil {
return "", fmt.Errorf("invalid size value '%s': %v", s, err)
} else {
i = i * Pow(1024, lookupTable2[unit])
s = strconv.FormatInt(i, 10)
return s, nil
}
}
}
// fall back to SI units
for _, unit := range units10 {
if strings.HasSuffix(s, unit) {
s = strings.TrimSuffix(s, unit)
if i, err := strconv.ParseInt(s, 10, 0); err != nil {
return "", fmt.Errorf("invalid size value '%s': %v", s, err)
} else {
i = i * Pow(1000, lookupTable10[unit])
s = strconv.FormatInt(i, 10)
return s, nil
}
}
}
// no valid units found, so ensure the value is a number
if _, err := strconv.ParseUint(s, 10, 64); err != nil {
return "", fmt.Errorf("invalid size value '%s': %v", s, err)
}
return s, nil
}
// GetVolumeSizeBytes determines the size, in bytes, of a volume from the "size" opt value. If "size" has a units
// suffix, that is handled here. If there are no units, the default is GiB. If size is not in opts, the specified
// default value is parsed identically and used instead.
func GetVolumeSizeBytes(ctx context.Context, opts map[string]string, defaultVolumeSize string) (uint64, error) {
usingDefaultSize := false
usingDefaultUnits := false
// Use the size if specified, else use the configured default size
size := GetV(opts, "size", "")
if size == "" {
size = defaultVolumeSize
usingDefaultSize = true
}
// Default to GiB if no units are present
if !sizeHasUnits(size) {
size += "G"
usingDefaultUnits = true
}
// Ensure the size is valid
sizeBytesStr, err := ConvertSizeToBytes(size)
if err != nil {
return 0, err
}
sizeBytes, _ := strconv.ParseUint(sizeBytesStr, 10, 64)
Logc(ctx).WithFields(log.Fields{
"sizeBytes": sizeBytes,
"size": size,
"usingDefaultSize": usingDefaultSize,
"usingDefaultUnits": usingDefaultUnits,
}).Debug("Determined volume size.")
return sizeBytes, nil
}
// sizeHasUnits checks whether a size string includes a units suffix.
func sizeHasUnits(size string) bool {
// make lowercase so units detection always works
size = strings.TrimSpace(strings.ToLower(size))
for _, unit := range units2 {
if strings.HasSuffix(size, unit) {
return true
}
}
for _, unit := range units10 {
if strings.HasSuffix(size, unit) {
return true
}
}
return false
}
// VolumeSizeWithinTolerance checks to see if requestedSize is within the delta of the currentSize.
// If within the delta true is returned. If not within the delta and requestedSize is less than the
// currentSize false is returned.
func VolumeSizeWithinTolerance(requestedSize int64, currentSize int64, delta int64) (bool, error) {
sizeDiff := requestedSize - currentSize
if sizeDiff < 0 {
sizeDiff = -sizeDiff
}
if sizeDiff <= delta {
return true, nil
}
return false, nil
}
// GetV takes a map, key(s), and a defaultValue; will return the value of the key or defaultValue if none is set.
// If keys is a string of key values separated by "|", then each key is tried in turn. This allows compatibility
// with deprecated values, i.e. "fstype|fileSystemType".
func GetV(opts map[string]string, keys string, defaultValue string) string {
for _, key := range strings.Split(keys, "|") {
// Try key first, then do a case-insensitive search
if value, ok := opts[key]; ok {
return value
} else {
for k, v := range opts {
if strings.EqualFold(k, key) {
return v
}
}
}
}
return defaultValue
}
// RandomString returns a string of the specified length consisting only of alphabetic characters.
func RandomString(strSize int) string {
chars := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var bytes = make([]byte, strSize)
rand.Read(bytes)
for i, b := range bytes {
bytes[i] = chars[b%byte(len(chars))]
}
return string(bytes)
}
// StringInSlice checks whether a string is in a list of strings
func StringInSlice(s string, list []string) bool {
for _, item := range list {
if item == s {
return true
}
}
return false
}
func LogHTTPRequest(request *http.Request, requestBody []byte) {
header := ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
footer := "--------------------------------------------------------------------------------"
requestURL, _ := url.Parse(request.URL.String())
requestURL.User = nil
ctx := request.Context()
headers := make(map[string][]string)
for k, v := range request.Header {
headers[k] = v
}
delete(headers, "Authorization")
delete(headers, "Api-Key")
delete(headers, "Secret-Key")
var body string
if requestBody == nil {
body = "<nil>"
} else {
body = string(requestBody)
}
Logc(ctx).Debugf("\n%s\n%s %s\nHeaders: %v\nBody: %s\n%s",
header, request.Method, requestURL, headers, body, footer)
}
func LogHTTPResponse(ctx context.Context, response *http.Response, responseBody []byte) {
header := "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
footer := "================================================================================"
headers := make(map[string][]string)
for k, v := range response.Header {
headers[k] = v
}
delete(headers, "Authorization")
delete(headers, "Api-Key")
delete(headers, "Secret-Key")
var body string
if responseBody == nil {
body = "<nil>"
} else {
body = string(responseBody)
}
Logc(ctx).Debugf("\n%s\nStatus: %s\nHeaders: %v\nBody: %s\n%s",
header, response.Status, headers, body, footer)
}
type HTTPError struct {
Status string
StatusCode int
}
func (e HTTPError) Error() string {
return fmt.Sprintf("HTTP error: %s", e.Status)
}
func NewHTTPError(response *http.Response) *HTTPError {
if response.StatusCode < 300 {
return nil
}
return &HTTPError{response.Status, response.StatusCode}
}
// SliceContainsString checks to see if a []string contains a string
func SliceContainsString(slice []string, s string) bool {
return SliceContainsStringConditionally(slice, s, func(val1, val2 string) bool { return val1 == val2 })
}
// SliceContainsStringCaseInsensitive is SliceContainsString but case insensitive
func SliceContainsStringCaseInsensitive(slice []string, s string) bool {
matchFunc := func(main, val string) bool {
return strings.EqualFold(main, val)
}
return SliceContainsStringConditionally(slice, s, matchFunc)
}
// SliceContainsStringConditionally checks to see if a []string contains a string based on certain criteria
func SliceContainsStringConditionally(slice []string, s string, fn func(string, string) bool) bool {
for _, item := range slice {
if fn(item, s) {
return true
}
}
return false
}
// RemoveStringFromSlice removes a string from a []string
func RemoveStringFromSlice(slice []string, s string) (result []string) {
return RemoveStringFromSliceConditionally(slice, s, func(val1, val2 string) bool { return val1 == val2 })
}
// RemoveStringFromSliceConditionally removes a string from a []string if it meets certain criteria
func RemoveStringFromSliceConditionally(slice []string, s string, fn func(string, string) bool) (result []string) {
for _, item := range slice {
if fn(s, item) {
continue
}
result = append(result, item)
}
return
}
// SplitImageDomain accepts a container image name and splits off the domain portion, if any.
func SplitImageDomain(name string) (domain, remainder string) {
i := strings.IndexRune(name, '/')
if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != "localhost") {
domain, remainder = "", name
} else {
domain, remainder = name[:i], name[i+1:]
}
return
}
// ReplaceImageRegistry accepts a container image name and a registry name (FQDN[:port]) and
// returns the same image name with the supplied registry.
func ReplaceImageRegistry(image, registry string) string {
_, remainder := SplitImageDomain(image)
if registry == "" {
return remainder
}
return registry + "/" + remainder
}
// ValidateCIDRs checks if a list of CIDR blocks are valid and returns a multi error containing all errors
// which may occur during the parsing process.
func ValidateCIDRs(ctx context.Context, cidrs []string) error {
var err error
// needed to capture all issues within the CIDR set
errors := make([]error, 0)
for _, cidr := range cidrs {
_, _, err := net.ParseCIDR(cidr)
if err != nil {
errors = append(errors, err)
Logc(ctx).WithError(err).Error("Found an invalid CIDR.")
}
}
if len(errors) != 0 {
err = multierr.Combine(errors...)
return err
}
return err
}
// FilterIPs takes a list of IPs and CIDRs and returns the sorted list of IPs that are contained by one or more of the
// CIDRs
func FilterIPs(ctx context.Context, ips, cidrs []string) ([]string, error) {
networks := make([]*net.IPNet, len(cidrs))
filteredIPs := make([]string, 0)
for i, cidr := range cidrs {
_, ipNet, err := net.ParseCIDR(cidr)
if err != nil {
err = fmt.Errorf("error parsing CIDR; %v", err)
Logc(ctx).WithField("CIDR", cidr).Error(err)
return nil, err
}
networks[i] = ipNet
}
for _, ip := range ips {
parsedIP := net.ParseIP(ip)
for _, network := range networks {
fields := log.Fields{
"IP": ip,
"Network": network.String(),
}
if network.Contains(parsedIP) {
Logc(ctx).WithFields(fields).Debug("IP found in network.")
filteredIPs = append(filteredIPs, ip)
break
} else {
Logc(ctx).WithFields(fields).Debug("IP not found in network.")
}
}
}
sort.Strings(filteredIPs)
return filteredIPs, nil
}
// GetYAMLTagWithSpaceCount returns the line that matches the pattern, tag name, and the spaces before the tag
func GetYAMLTagWithSpaceCount(text string) (string, string, int) {
// This matches pattern in a multiline string of type " {something}\n"
tagsWithIndentationRegex := regexp.MustCompile(`(?m)^[\t ]*{(?P<tagName>[\w-]+)}$\n`)
tag := tagsWithIndentationRegex.FindStringSubmatch(text)
// Since we have two of `()` in the pattern, we want to use the tag identified by the second `()`.
if len(tag) > 1 {
tagWithSpaces := tagsWithIndentationRegex.FindString(text)
indentation := CountSpacesBeforeText(tagWithSpaces)
return tagWithSpaces, tag[1], indentation
}
return "", "", 0
}
func CountSpacesBeforeText(text string) int {
return len(text) - len(strings.TrimLeft(text, " \t"))
}
// GetFindMultipathValue returns the value of find_multipaths
// Returned values:
// no (or off): Create a multipath device for every path that is not explicitly disabled
// yes (or on): Create a device if one of some conditions are met
// other possible values: smart, greedy, strict
func GetFindMultipathValue(text string) string {
// This matches pattern in a multiline string of type " find_multipaths: yes"
tagsWithIndentationRegex := regexp.MustCompile(`(?m)^[\t ]*find_multipaths[\t ]*["|']?(?P<tagName>[\w-_]+)["|']?[\t ]*$`)
tag := tagsWithIndentationRegex.FindStringSubmatch(text)
// Since we have two of `()` in the pattern, we want to use the tag identified by the second `()`.
if len(tag) > 1 {
if tag[1] == "off" {
return "no"
} else if tag[1] == "on" {
return "yes"
}
return tag[1]
}
return ""
}
// GetNFSVersionFromMountOptions accepts a set of mount options, a default NFS version, and a list of
// supported NFS versions, and it returns the NFS version specified by the mount options, or the default
// if none is found, plus an error (if any). If a set of supported versions is supplied, and the returned
// version isn't in it, this method returns an error; otherwise it returns nil.
func GetNFSVersionFromMountOptions(mountOptions, defaultVersion string, supportedVersions []string) (string, error) {
majorRegex := regexp.MustCompile(`^(nfsvers|vers)=(?P<major>\d)$`)
majorMinorRegex := regexp.MustCompile(`^(nfsvers|vers)=(?P<major>\d)\.(?P<minor>\d)$`)
minorRegex := regexp.MustCompile(`^minorversion=(?P<minor>\d)$`)
major := ""
minor := ""
// Strip off -o prefix if present
mountOptions = strings.TrimPrefix(mountOptions, "-o ")
// Check each mount option using the three mutually-exclusive regular expressions. Last option wins.
for _, mountOption := range strings.Split(mountOptions, ",") {
mountOption = strings.TrimSpace(mountOption)
if matchGroups := GetRegexSubmatches(majorMinorRegex, mountOption); matchGroups != nil {
major = matchGroups["major"]
minor = matchGroups["minor"]
continue
}
if matchGroups := GetRegexSubmatches(majorRegex, mountOption); matchGroups != nil {
major = matchGroups["major"]
continue
}
if matchGroups := GetRegexSubmatches(minorRegex, mountOption); matchGroups != nil {
minor = matchGroups["minor"]
continue
}
}
version := ""
// Assemble version string from major/minor values.
if major == "" {
// Minor doesn't matter if major isn't set.
version = ""
} else if minor == "" {
// Major works by itself if minor isn't set.
version = major
} else {
version = major + "." + minor
}
// Handle default & supported versions.
if version == "" {
return defaultVersion, nil
} else if supportedVersions == nil || SliceContainsString(supportedVersions, version) {
return version, nil
} else {
return version, fmt.Errorf("unsupported NFS version: %s", version)
}
}
// GetRegexSubmatches accepts a regular expression with one or more groups and returns a map
// of the group matches found in the supplied string.
func GetRegexSubmatches(r *regexp.Regexp, s string) map[string]string {
match := r.FindStringSubmatch(s)
if match == nil {
return nil
}
paramsMap := make(map[string]string)
for i, name := range r.SubexpNames() {
if i > 0 && i <= len(match) {
paramsMap[name] = match[i]
}
}
return paramsMap
}
// Detect if code is running in a container or not
func RunningInContainer() bool {
return os.Getenv("CSI_ENDPOINT") != ""
}
func Max(x, y int64) int64 {
if x > y {
return x
}
return y
}
// SplitString is same as strings.Split except it returns a nil ([]string(nil)) of size 0 instead of
// string slice with an empty string (size 1) when string to be split is empty.
func SplitString(_ context.Context, s, sep string) []string {
if s == "" {
return nil
}
return strings.Split(s, sep)
}
// MinInt64 returns the lower of the two integers specified
func MinInt64(a, b int64) int64 {
if a < b {
return a
}
return b
}
func ValidateOctalUnixPermissions(perms string) error {
permsRegex := regexp.MustCompile(`^[0-7]{4}$`)
if !permsRegex.MatchString(perms) {
return fmt.Errorf("%s is not a valid octal unix permissions value", perms)
}
return nil
}
func GenerateVolumePublishName(volumeID, nodeID string) string {
return fmt.Sprintf(volumeID + "." + nodeID)
}
|
[
"\"CSI_ENDPOINT\""
] |
[] |
[
"CSI_ENDPOINT"
] |
[]
|
["CSI_ENDPOINT"]
|
go
| 1 | 0 | |
airflow/operators/bash_operator.py
|
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import signal
from subprocess import Popen, STDOUT, PIPE
from tempfile import gettempdir, NamedTemporaryFile
from builtins import bytes
from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.utils.file import TemporaryDirectory
from airflow.utils.operator_helpers import context_to_airflow_vars
class BashOperator(BaseOperator):
"""
Execute a Bash script, command or set of commands.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BashOperator`
:param bash_command: The command, set of commands or reference to a
bash script (must be '.sh') to be executed. (templated)
:type bash_command: str
:param xcom_push: If xcom_push is True, the last line written to stdout
will also be pushed to an XCom when the bash command completes.
:type xcom_push: bool
:param env: If env is not None, it must be a mapping that defines the
environment variables for the new process; these are used instead
of inheriting the current process environment, which is the default
behavior. (templated)
:type env: dict
:param output_encoding: Output encoding of bash command
:type output_encoding: str
"""
template_fields = ('bash_command', 'env')
template_ext = ('.sh', '.bash',)
ui_color = '#f0ede4'
@apply_defaults
def __init__(
self,
bash_command,
xcom_push=False,
env=None,
output_encoding='utf-8',
*args, **kwargs):
super(BashOperator, self).__init__(*args, **kwargs)
self.bash_command = bash_command
self.env = env
self.xcom_push_flag = xcom_push
self.output_encoding = output_encoding
def execute(self, context):
"""
Execute the bash command in a temporary directory
which will be cleaned afterwards
"""
self.log.info("Tmp dir root location: \n %s", gettempdir())
# Prepare env for child process.
env = self.env
if env is None:
env = os.environ.copy()
airflow_context_vars = context_to_airflow_vars(context, in_env_var_format=True)
self.log.info('Exporting the following env vars:\n%s',
'\n'.join(["{}={}".format(k, v)
for k, v in
airflow_context_vars.items()]))
env.update(airflow_context_vars)
self.lineage_data = self.bash_command
with TemporaryDirectory(prefix='airflowtmp') as tmp_dir:
with NamedTemporaryFile(dir=tmp_dir, prefix=self.task_id) as f:
f.write(bytes(self.bash_command, 'utf_8'))
f.flush()
fname = f.name
script_location = os.path.abspath(fname)
self.log.info(
"Temporary script location: %s",
script_location
)
def pre_exec():
# Restore default signal disposition and invoke setsid
for sig in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ'):
if hasattr(signal, sig):
signal.signal(getattr(signal, sig), signal.SIG_DFL)
os.setsid()
self.log.info("Running command: %s", self.bash_command)
sp = Popen(
['bash', fname],
stdout=PIPE, stderr=STDOUT,
cwd=tmp_dir, env=env,
preexec_fn=pre_exec)
self.sp = sp
self.log.info("Output:")
line = ''
for line in iter(sp.stdout.readline, b''):
line = line.decode(self.output_encoding).rstrip()
self.log.info(line)
sp.wait()
self.log.info(
"Command exited with return code %s",
sp.returncode
)
if sp.returncode:
raise AirflowException("Bash command failed")
if self.xcom_push_flag:
return line
def on_kill(self):
self.log.info('Sending SIGTERM signal to bash process group')
os.killpg(os.getpgid(self.sp.pid), signal.SIGTERM)
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
tests/integration/test_process.py
|
import json
import os
import subprocess
import zipfile
import hashlib
import pytest
import py.path
import exifread
EXECUTABLE = os.getenv("MAPILLARY_TOOLS_EXECUTABLE", "python3 -m mapillary_tools")
IMPORT_PATH = "tests/integration/mapillary_tools_process_images_provider/data"
USERNAME = "test_username_MAKE_SURE_IT_IS_UNIQUE_AND_LONG_AND_BORING"
CONFIG_CONTENT = f"""
[{USERNAME}]
MAPSettingsUsername = {USERNAME}
MAPSettingsUserKey = test_user_key
user_upload_token = test_user_token
"""
@pytest.fixture
def setup_config(tmpdir: py.path.local):
config_path = tmpdir.mkdir("configs").join("CLIENT_ID")
with open(config_path, "w") as fp:
fp.write(CONFIG_CONTENT)
yield config_path
if tmpdir.check():
tmpdir.remove(ignore_errors=True)
@pytest.fixture
def setup_data(tmpdir: py.path.local):
data_path = tmpdir.mkdir("data")
source = py.path.local(IMPORT_PATH)
source.copy(data_path)
yield data_path
if tmpdir.check():
tmpdir.remove(ignore_errors=True)
def test_basic():
for option in ["--version", "--help"]:
x = subprocess.run(f"{EXECUTABLE} {option}", shell=True)
assert x.returncode == 0, x.stderr
def test_process(setup_data: py.path.local):
x = subprocess.run(
f"{EXECUTABLE} process {setup_data}",
shell=True,
)
assert x.returncode == 0, x.stderr
desc_path = os.path.join(setup_data, "mapillary_image_description.json")
with open(desc_path) as fp:
descs = json.load(fp)
for desc in descs:
assert "filename" in desc
assert os.path.isfile(os.path.join(setup_data, desc["filename"]))
def validate_and_extract_zip(filename: str):
basename = os.path.basename(filename)
assert basename.startswith("mly_tools_"), filename
assert basename.endswith(".zip"), filename
ret = {}
import tempfile
with zipfile.ZipFile(filename) as zipf:
with tempfile.TemporaryDirectory() as tempdir:
zipf.extractall(path=tempdir)
for name in os.listdir(tempdir):
with open(os.path.join(tempdir, name), "rb") as fp:
tags = exifread.process_file(fp)
desc_tag = tags.get("Image ImageDescription")
assert desc_tag is not None, tags
desc = json.loads(str(desc_tag.values))
assert isinstance(desc.get("MAPLatitude"), (float, int)), desc
assert isinstance(desc.get("MAPLongitude"), (float, int)), desc
assert isinstance(desc.get("MAPCaptureTime"), str), desc
assert isinstance(desc.get("MAPCompassHeading"), dict), desc
for key in desc.keys():
assert key.startswith("MAP"), key
ret[name] = desc
return ret
def test_zip(tmpdir: py.path.local, setup_data: py.path.local):
zip_dir = tmpdir.mkdir("zip_dir")
x = subprocess.run(
f"{EXECUTABLE} process {setup_data}",
shell=True,
)
assert x.returncode == 0, x.stderr
x = subprocess.run(
f"{EXECUTABLE} zip {setup_data} {zip_dir}",
shell=True,
)
assert x.returncode == 0, x.stderr
assert 0 < len(zip_dir.listdir())
for file in zip_dir.listdir():
validate_and_extract_zip(str(file))
def test_upload_image_dir(
tmpdir: py.path.local, setup_config: py.path.local, setup_data: py.path.local
):
os.environ["MAPILLARY_CONFIG_PATH"] = str(setup_config)
upload_dir = tmpdir.mkdir("mapillary_public_uploads")
os.environ["MAPILLARY_UPLOAD_PATH"] = str(upload_dir)
x = subprocess.run(
f"{EXECUTABLE} process {setup_data}",
shell=True,
)
assert x.returncode == 0, x.stderr
x = subprocess.run(
f"{EXECUTABLE} upload {setup_data} --dry_run --user_name={USERNAME}",
shell=True,
)
for file in upload_dir.listdir():
validate_and_extract_zip(str(file))
assert x.returncode == 0, x.stderr
def test_upload_image_dir_twice(
tmpdir: py.path.local, setup_config: py.path.local, setup_data: py.path.local
):
os.environ["MAPILLARY_CONFIG_PATH"] = str(setup_config)
upload_dir = tmpdir.mkdir("mapillary_public_uploads")
os.environ["MAPILLARY_UPLOAD_PATH"] = str(upload_dir)
x = subprocess.run(
f"{EXECUTABLE} process {setup_data}",
shell=True,
)
assert x.returncode == 0, x.stderr
md5sum_map = {}
# first upload
x = subprocess.run(
f"{EXECUTABLE} upload {setup_data} --dry_run --user_name={USERNAME}",
shell=True,
)
assert x.returncode == 0, x.stderr
for file in upload_dir.listdir():
validate_and_extract_zip(str(file))
md5sum_map[os.path.basename(file)] = file_md5sum(file)
# expect the second upload to not produce new uploads
x = subprocess.run(
f"{EXECUTABLE} upload {setup_data} --dry_run --user_name={USERNAME}",
shell=True,
)
assert x.returncode == 0, x.stderr
for file in upload_dir.listdir():
validate_and_extract_zip(str(file))
new_md5sum = file_md5sum(file)
assert md5sum_map[os.path.basename(file)] == new_md5sum
assert len(md5sum_map) == len(upload_dir.listdir())
def test_upload_zip(
tmpdir: py.path.local, setup_data: py.path.local, setup_config: py.path.local
):
os.environ["MAPILLARY_CONFIG_PATH"] = str(setup_config)
upload_dir = tmpdir.mkdir("mapillary_public_uploads")
os.environ["MAPILLARY_UPLOAD_PATH"] = str(upload_dir)
zip_dir = tmpdir.mkdir("zip_dir")
x = subprocess.run(
f"{EXECUTABLE} process {setup_data}",
shell=True,
)
assert x.returncode == 0, x.stderr
x = subprocess.run(
f"{EXECUTABLE} zip {setup_data} {zip_dir}",
shell=True,
)
assert x.returncode == 0, x.stderr
for zfile in zip_dir.listdir():
x = subprocess.run(
f"{EXECUTABLE} upload {zfile} --dry_run --user_name={USERNAME}",
shell=True,
)
assert x.returncode == 0, x.stderr
for file in upload_dir.listdir():
validate_and_extract_zip(str(file))
def test_process_and_upload(
tmpdir: py.path.local, setup_config: py.path.local, setup_data: py.path.local
):
os.environ["MAPILLARY_CONFIG_PATH"] = str(setup_config)
upload_dir = tmpdir.mkdir("mapillary_public_uploads")
os.environ["MAPILLARY_UPLOAD_PATH"] = str(upload_dir)
x = subprocess.run(
f"{EXECUTABLE} process_and_upload {setup_data} --dry_run --user_name={USERNAME}",
shell=True,
)
assert x.returncode == 0, x.stderr
for file in upload_dir.listdir():
validate_and_extract_zip(str(file))
def test_time(setup_data: py.path.local):
# before offset
x = subprocess.run(
f"{EXECUTABLE} process {setup_data}",
shell=True,
)
desc_path = setup_data.join("mapillary_image_description.json")
with open(desc_path) as fp:
descs = json.load(fp)
expected = {
"DSC00001.JPG": "2018_06_08_13_24_10_000",
"DSC00497.JPG": "2018_06_08_13_32_28_000",
"V0370574.JPG": "2018_07_27_11_32_14_000",
}
for desc in descs:
assert "filename" in desc
assert expected[desc["filename"]] == desc["MAPCaptureTime"]
# after offset
x = subprocess.run(
f"{EXECUTABLE} process {setup_data} --offset_time=2.5",
shell=True,
)
assert x.returncode == 0, x.stderr
desc_path = setup_data.join("mapillary_image_description.json")
with open(desc_path) as fp:
descs = json.load(fp)
expected = {
"DSC00001.JPG": "2018_06_08_13_24_12_500",
"DSC00497.JPG": "2018_06_08_13_32_30_500",
"V0370574.JPG": "2018_07_27_11_32_16_500",
}
for desc in descs:
assert "filename" in desc
assert expected[desc["filename"]] == desc["MAPCaptureTime"]
# after offset
x = subprocess.run(
f"{EXECUTABLE} process {setup_data} --offset_time=-1.0",
shell=True,
)
assert x.returncode == 0, x.stderr
desc_path = setup_data.join("mapillary_image_description.json")
with open(desc_path) as fp:
descs = json.load(fp)
expected = {
"DSC00001.JPG": "2018_06_08_13_24_09_000",
"DSC00497.JPG": "2018_06_08_13_32_27_000",
"V0370574.JPG": "2018_07_27_11_32_13_000",
}
for desc in descs:
assert "filename" in desc
assert expected[desc["filename"]] == desc["MAPCaptureTime"]
def test_angle(setup_data: py.path.local):
# before offset
x = subprocess.run(
f"{EXECUTABLE} process {setup_data}",
shell=True,
)
assert x.returncode == 0, x.stderr
desc_path = setup_data.join("mapillary_image_description.json")
with open(desc_path) as fp:
descs = json.load(fp)
expected = {
"DSC00001.JPG": 270.89,
"DSC00497.JPG": 271.27,
"V0370574.JPG": 359.0,
}
for desc in descs:
assert "filename" in desc
assert (
abs(expected[desc["filename"]] - desc["MAPCompassHeading"]["TrueHeading"])
< 0.00001
)
assert (
abs(
expected[desc["filename"]]
- desc["MAPCompassHeading"]["MagneticHeading"]
)
< 0.00001
)
# after offset
x = subprocess.run(
f"{EXECUTABLE} process {setup_data} --offset_angle=2.5",
shell=True,
)
assert x.returncode == 0, x.stderr
desc_path = setup_data.join("mapillary_image_description.json")
with open(desc_path) as fp:
descs = json.load(fp)
expected = {
"DSC00001.JPG": 270.89 + 2.5,
"DSC00497.JPG": 271.27 + 2.5,
"V0370574.JPG": 1.5,
}
for desc in descs:
assert "filename" in desc
assert (
abs(expected[desc["filename"]] - desc["MAPCompassHeading"]["TrueHeading"])
< 0.00001
)
assert (
abs(
expected[desc["filename"]]
- desc["MAPCompassHeading"]["MagneticHeading"]
)
< 0.00001
)
def test_process_boolean_options(
setup_config: py.path.local, setup_data: py.path.local
):
os.environ["MAPILLARY_CONFIG_PATH"] = str(setup_config)
boolean_options = [
"--add_file_name",
"--add_import_date",
"--exclude_import_path",
"--interpolate_directions",
"--overwrite_EXIF_direction_tag",
"--overwrite_EXIF_gps_tag",
"--overwrite_EXIF_orientation_tag",
"--overwrite_EXIF_time_tag",
"--overwrite_all_EXIF_tags",
"--skip_subfolders",
"--windows_path",
]
for option in boolean_options:
x = subprocess.run(
f"{EXECUTABLE} process {setup_data} {option}",
shell=True,
)
assert x.returncode == 0, x.stderr
all_options = " ".join(boolean_options)
x = subprocess.run(
f"{EXECUTABLE} process {setup_data} {all_options}",
shell=True,
)
assert x.returncode == 0, x.stderr
GPX_CONTENT = """
<gpx>
<trk>
<name>Mapillary GPX</name>
<trkseg>
<trkpt lat="0.02" lon="0.01">
<ele>1</ele>
<time>2018-06-08T13:23:34.805</time>
</trkpt>
<trkpt lat="2.02" lon="0.01">
<ele>2</ele>
<time>2018-06-08T13:24:35.809</time>
</trkpt>
<trkpt lat="2.02" lon="2.01">
<ele>4</ele>
<time>2018-06-08T13:33:36.813</time>
</trkpt>
<trkpt lat="4.02" lon="2.01">
<ele>9</ele>
<time>2018-06-08T13:58:37.812</time>
</trkpt>
</trkseg>
</trk>
</gpx>
"""
def find_desc_errors(descs):
return [desc for desc in descs if "error" in desc]
def filter_out_errors(descs):
return [desc for desc in descs if "error" not in desc]
def test_geotagging_from_gpx(setup_data: py.path.local):
gpx_file = setup_data.join("test.gpx")
desc_path = setup_data.join("mapillary_image_description.json")
with gpx_file.open("w") as fp:
fp.write(GPX_CONTENT)
x = subprocess.run(
f"{EXECUTABLE} process {setup_data} --geotag_source gpx --geotag_source_path {gpx_file} --skip_process_errors",
shell=True,
)
assert x.returncode == 0, x.stderr
expected_lonlat = {
# capture_time, lon, lat, elevation
"DSC00001.JPG": [
"2018_06_08_13_24_10_000",
0.01,
1.1738587633597797,
1.5769293816798897,
],
"DSC00497.JPG": [
"2018_06_08_13_32_28_000",
1.7556100139740183,
2.02,
3.7456100139740185,
],
}
with open(desc_path) as fp:
descs = json.load(fp)
assert {"V0370574.JPG"} == {d["filename"] for d in find_desc_errors(descs)}
for desc in find_desc_errors(descs):
assert desc.get("error").get("type") == "MapillaryOutsideGPXTrackError"
for desc in filter_out_errors(descs):
assert expected_lonlat[desc["filename"]][0] == desc["MAPCaptureTime"]
assert (
abs(expected_lonlat[desc["filename"]][1] - desc["MAPLongitude"]) < 0.00001
)
assert abs(expected_lonlat[desc["filename"]][2] - desc["MAPLatitude"]) < 0.00001
assert abs(expected_lonlat[desc["filename"]][3] - desc["MAPAltitude"]) < 0.00001
def test_geotagging_from_gpx_with_offset(setup_data: py.path.local):
gpx_file = setup_data.join("test.gpx")
desc_path = setup_data.join("mapillary_image_description.json")
with gpx_file.open("w") as fp:
fp.write(GPX_CONTENT)
x = subprocess.run(
f"{EXECUTABLE} process {setup_data} --geotag_source gpx --geotag_source_path {gpx_file} --interpolation_offset_time=-20 --skip_process_errors",
shell=True,
)
assert x.returncode == 0, x.stderr
expected_lonlat = {
# capture_time, lon, lat, elevation
"DSC00001.JPG": [
"2018_06_08_13_23_50_000",
0.01,
0.5181640548160776,
1.2490820274080388,
],
"DSC00497.JPG": [
"2018_06_08_13_32_08_000",
1.6816734072206487,
2.02,
3.671673407220649,
],
}
with open(desc_path) as fp:
descs = json.load(fp)
assert {"V0370574.JPG"} == {d["filename"] for d in find_desc_errors(descs)}
for desc in find_desc_errors(descs):
assert desc.get("error").get("type") == "MapillaryOutsideGPXTrackError"
for desc in filter_out_errors(descs):
assert expected_lonlat[desc["filename"]][0] == desc["MAPCaptureTime"]
assert (
abs(expected_lonlat[desc["filename"]][1] - desc["MAPLongitude"]) < 0.00001
)
assert abs(expected_lonlat[desc["filename"]][2] - desc["MAPLatitude"]) < 0.00001
assert abs(expected_lonlat[desc["filename"]][3] - desc["MAPAltitude"]) < 0.00001
def test_geotagging_from_gpx_use_gpx_start_time(setup_data: py.path.local):
gpx_file = setup_data.join("test.gpx")
with gpx_file.open("w") as fp:
fp.write(GPX_CONTENT)
x = subprocess.run(
f"{EXECUTABLE} process {setup_data} --geotag_source gpx --interpolation_use_gpx_start_time --geotag_source_path {gpx_file} --skip_process_errors",
shell=True,
)
assert x.returncode == 0, x.stderr
expected_lonlat = {
# capture_time, lon, lat, elevation
"DSC00001.JPG": ["2018_06_08_13_23_34_805", 0.01, 0.02, 1.0],
"DSC00497.JPG": [
"2018_06_08_13_31_52_805",
1.6255000702397762,
2.02,
3.6155000702397766,
],
}
desc_path = setup_data.join("mapillary_image_description.json")
with open(desc_path) as fp:
descs = json.load(fp)
assert {"V0370574.JPG"} == {d["filename"] for d in find_desc_errors(descs)}
for desc in find_desc_errors(descs):
assert desc.get("error").get("type") == "MapillaryOutsideGPXTrackError"
for desc in filter_out_errors(descs):
assert expected_lonlat[desc["filename"]][0] == desc["MAPCaptureTime"]
assert (
abs(expected_lonlat[desc["filename"]][1] - desc["MAPLongitude"]) < 0.00001
)
assert abs(expected_lonlat[desc["filename"]][2] - desc["MAPLatitude"]) < 0.00001
assert abs(expected_lonlat[desc["filename"]][3] - desc["MAPAltitude"]) < 0.00001
def test_geotagging_from_gpx_use_gpx_start_time_with_offset(setup_data: py.path.local):
gpx_file = setup_data.join("test.gpx")
with gpx_file.open("w") as fp:
fp.write(GPX_CONTENT)
x = subprocess.run(
f"{EXECUTABLE} process {setup_data} --geotag_source gpx --interpolation_use_gpx_start_time --geotag_source_path {gpx_file} --interpolation_offset_time=100 --skip_process_errors",
shell=True,
)
assert x.returncode == 0, x.stderr
expected_lonlat = {
# capture_time, lon, lat, elevation
"DSC00001.JPG": [
"2018_06_08_13_25_14_805",
0.15416159584772016,
2.02,
2.14416159584772,
],
"DSC00497.JPG": [
"2018_06_08_13_33_32_805",
1.9951831040066244,
2.02,
3.985183104006625,
],
}
desc_path = setup_data.join("mapillary_image_description.json")
with open(desc_path) as fp:
descs = json.load(fp)
assert {"V0370574.JPG"} == {d["filename"] for d in find_desc_errors(descs)}
for desc in find_desc_errors(descs):
assert desc.get("error").get("type") == "MapillaryOutsideGPXTrackError"
for desc in filter_out_errors(descs):
assert expected_lonlat[desc["filename"]][0] == desc["MAPCaptureTime"]
assert (
abs(expected_lonlat[desc["filename"]][1] - desc["MAPLongitude"]) < 0.00001
)
assert abs(expected_lonlat[desc["filename"]][2] - desc["MAPLatitude"]) < 0.00001
assert abs(expected_lonlat[desc["filename"]][3] - desc["MAPAltitude"]) < 0.00001
def ffmpeg_installed():
ffmpeg_path = os.getenv("MAPILLARY_FFMPEG_PATH", "ffmpeg")
try:
subprocess.run([ffmpeg_path, "-version"])
except FileNotFoundError:
return False
return True
is_ffmpeg_installed = ffmpeg_installed()
def test_sample_video(setup_data: py.path.local):
if not is_ffmpeg_installed:
pytest.skip("skip because ffmpeg not installed")
for input_path in [setup_data, setup_data.join("sample-5s.mp4")]:
x = subprocess.run(
f"{EXECUTABLE} sample_video --rerun {input_path}",
shell=True,
)
assert x.returncode != 0, x.stderr
assert len(setup_data.join("mapillary_sampled_video_frames").listdir()) == 0
x = subprocess.run(
f"{EXECUTABLE} sample_video --skip_sample_errors --rerun {input_path}",
shell=True,
)
assert x.returncode == 0, x.stderr
assert len(setup_data.join("mapillary_sampled_video_frames").listdir()) == 0
x = subprocess.run(
f"{EXECUTABLE} sample_video --video_start_time 2021_10_10_10_10_10_123 --rerun {input_path}",
shell=True,
)
assert x.returncode == 0, x.stderr
sample_path = setup_data.join("mapillary_sampled_video_frames")
assert len(sample_path.listdir()) == 1
samples = sample_path.join("sample-5s.mp4").listdir()
samples.sort()
times = []
for s in samples:
with s.open("rb") as fp:
tags = exifread.process_file(fp)
times.append(tags["EXIF DateTimeOriginal"].values)
assert (
"2021:10:10 10:10:10.123",
"2021:10:10 10:10:12.123",
"2021:10:10 10:10:14.123",
) == tuple(times)
def test_video_process(setup_data: py.path.local):
if not is_ffmpeg_installed:
pytest.skip("skip because ffmpeg not installed")
gpx_file = setup_data.join("test.gpx")
desc_path = setup_data.join("my_samples").join("mapillary_image_description.json")
with gpx_file.open("w") as fp:
fp.write(GPX_CONTENT)
x = subprocess.run(
f"{EXECUTABLE} video_process --video_start_time 2018_06_08_13_23_34_123 --geotag_source gpx --geotag_source_path {gpx_file} {setup_data} {setup_data.join('my_samples')}",
shell=True,
)
assert x.returncode != 0, x.stderr
with open(desc_path) as fp:
descs = json.load(fp)
assert 1 == len(find_desc_errors(descs))
assert 2 == len(filter_out_errors(descs))
def test_video_process_multiple_videos(setup_data: py.path.local):
if not is_ffmpeg_installed:
pytest.skip("skip because ffmpeg not installed")
gpx_file = setup_data.join("test.gpx")
desc_path = setup_data.join("my_samples").join("mapillary_image_description.json")
sub_folder = setup_data.join("video_sub_folder").mkdir()
video_path = setup_data.join("sample-5s.mp4")
video_path.copy(sub_folder)
with gpx_file.open("w") as fp:
fp.write(GPX_CONTENT)
x = subprocess.run(
f"{EXECUTABLE} video_process --video_start_time 2018_06_08_13_23_34_123 --geotag_source gpx --geotag_source_path {gpx_file} {video_path} {setup_data.join('my_samples')}",
shell=True,
)
assert x.returncode != 0, x.stderr
with open(desc_path) as fp:
descs = json.load(fp)
for d in descs:
assert d["filename"].startswith("sample-5s.mp4/")
assert 1 == len(find_desc_errors(descs))
assert 2 == len(filter_out_errors(descs))
def file_md5sum(path) -> str:
with open(path, "rb") as fp:
md5 = hashlib.md5()
while True:
buf = fp.read(1024 * 1024 * 32)
if not buf:
break
md5.update(buf)
return md5.hexdigest()
def test_upload_mp4(
tmpdir: py.path.local, setup_data: py.path.local, setup_config: py.path.local
):
os.environ["MAPILLARY_CONFIG_PATH"] = str(setup_config)
upload_dir = tmpdir.mkdir("mapillary_public_uploads")
os.environ["MAPILLARY_UPLOAD_PATH"] = str(upload_dir)
video_path = setup_data.join("sample-5s.mp4")
md5sum = file_md5sum(video_path)
x = subprocess.run(
f"{EXECUTABLE} upload {video_path} --dry_run --user_name={USERNAME}",
shell=True,
)
assert x.returncode == 0, x.stderr
assert 1 == len(upload_dir.listdir())
assert {"mly_tools_8cd0e9af15f4baaafe9dfe98ace8b886.mp4"} == {
os.path.basename(f) for f in upload_dir.listdir()
}
assert {md5sum} == {file_md5sum(f) for f in upload_dir.listdir()}
|
[] |
[] |
[
"MAPILLARY_CONFIG_PATH",
"MAPILLARY_UPLOAD_PATH",
"MAPILLARY_TOOLS_EXECUTABLE",
"MAPILLARY_FFMPEG_PATH"
] |
[]
|
["MAPILLARY_CONFIG_PATH", "MAPILLARY_UPLOAD_PATH", "MAPILLARY_TOOLS_EXECUTABLE", "MAPILLARY_FFMPEG_PATH"]
|
python
| 4 | 0 | |
tests/integration/devfile/cmd_devfile_push_test.go
|
package devfile
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/openshift/odo/pkg/util"
"github.com/openshift/odo/tests/helper"
"github.com/openshift/odo/tests/integration/devfile/utils"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("odo devfile push command tests", func() {
var cmpName string
var sourcePath = "/projects"
var commonVar helper.CommonVar
// This is run before every Spec (It)
var _ = BeforeEach(func() {
commonVar = helper.CommonBeforeEach()
cmpName = helper.RandString(6)
helper.Chdir(commonVar.Context)
})
// This is run after every Spec (It)
var _ = AfterEach(func() {
helper.CommonAfterEach(commonVar)
})
When("creating a nodejs component", func() {
output := ""
BeforeEach(func() {
helper.Cmd("odo", "create", "--project", commonVar.Project, cmpName, "--devfile", helper.GetExamplePath("source", "devfiles", "nodejs", "devfile-registry.yaml")).ShouldPass()
helper.CopyExample(filepath.Join("source", "devfiles", "nodejs", "project"), commonVar.Context)
})
When("setting git config and running odo push", func() {
remoteURL := "https://github.com/odo-devfiles/nodejs-ex"
BeforeEach(func() {
helper.Cmd("git", "init").ShouldPass()
remote := "origin"
helper.Cmd("git", "remote", "add", remote, remoteURL).ShouldPass()
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass().Out()
})
It("checks that odo push works with a devfile", func() {
Expect(output).To(ContainSubstring("Changes successfully pushed to component"))
})
It("check annotations from the deployment after odo push", func() {
annotations := commonVar.CliRunner.GetAnnotationsDeployment(cmpName, "app", commonVar.Project)
var valueFound bool
for key, value := range annotations {
if key == "app.openshift.io/vcs-uri" && value == remoteURL {
valueFound = true
}
}
Expect(valueFound).To(BeTrue())
})
When("updating a variable into devfile", func() {
BeforeEach(func() {
helper.ReplaceString("devfile.yaml", "name: FOO", "name: BAR")
})
It("should run odo push successfully", func() {
helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass()
})
})
})
When("odo push is executed with json output", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push", "-o", "json", "--project", commonVar.Project).ShouldPass().Out()
})
It("should display push output in JSON format", func() {
utils.AnalyzePushConsoleOutput(output)
})
When("update devfile and push again", func() {
BeforeEach(func() {
helper.ReplaceString("devfile.yaml", "name: FOO", "name: BAR")
output = helper.Cmd("odo", "push", "-o", "json", "--project", commonVar.Project).ShouldPass().Out()
})
It("should display push updated output in JSON format", func() {
utils.AnalyzePushConsoleOutput(output)
})
})
})
When("running odo push outside the context directory", func() {
newContext := ""
BeforeEach(func() {
newContext = helper.CreateNewContext()
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
helper.Chdir(newContext)
output = helper.Cmd("odo", "push", "--context", commonVar.Context).ShouldPass().Out()
})
AfterEach(func() {
helper.DeleteDir(newContext)
helper.Chdir(commonVar.Context)
})
It("should push correct component based on --context flag", func() {
Expect(output).To(ContainSubstring("Changes successfully pushed to component"))
})
})
When("Devfile 2.1.0 is used", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-variables.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
})
When("doing odo push", func() {
BeforeEach(func() {
output = helper.Cmd("odo", "push").ShouldPass().Out()
})
It("should pass", func() {
Expect(output).To(ContainSubstring("Changes successfully pushed to component"))
})
It("should check if the env variable has a correct value", func() {
envVars := commonVar.CliRunner.GetEnvsDevFileDeployment(cmpName, "app", commonVar.Project)
// check if the env variable has a correct value. This value was substituted from in devfile from variable
Expect(envVars["FOO"]).To(Equal("bar"))
})
})
})
When("doing odo push", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass()
})
When("doing odo push again", func() {
BeforeEach(func() {
output = helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass().Out()
})
It("should not build when no changes are detected in the directory", func() {
Expect(output).To(ContainSubstring("No file changes detected, skipping build"))
})
})
When("making changes in file and doing odo push again", func() {
BeforeEach(func() {
helper.ReplaceString(filepath.Join(commonVar.Context, "server.js"), "Hello from Node.js", "UPDATED!")
output = helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass().Out()
})
It("should build when a file change is detected", func() {
Expect(output).To(ContainSubstring("Syncing files to the component"))
})
})
When("doing odo push with -f flag", func() {
BeforeEach(func() {
output = helper.Cmd("odo", "push", "-f", "--project", commonVar.Project).ShouldPass().Out()
})
It("should build even when no changes are detected", func() {
Expect(output).To(Not(ContainSubstring("No file changes detected, skipping build")))
})
})
When("the pod is deleted and replaced", func() {
BeforeEach(func() {
oldPod := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
commonVar.CliRunner.DeletePod(oldPod, commonVar.Project)
Eventually(func() bool {
newPod := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
return newPod != "" && newPod != oldPod
}, 180, 10).Should(Equal(true))
newPod := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
commonVar.CliRunner.PodsShouldBeRunning(commonVar.Project, newPod)
})
It("should execute run command on odo push", func() {
output = helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass().Out()
Expect(output).To(ContainSubstring("Executing devrun command"))
})
})
})
When("creating local files and dir and doing odo push", func() {
var newDirPath, newFilePath, stdOut, podName string
BeforeEach(func() {
newFilePath = filepath.Join(commonVar.Context, "foobar.txt")
newDirPath = filepath.Join(commonVar.Context, "testdir")
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
// Create a new file that we plan on deleting later...
if err := helper.CreateFileWithContent(newFilePath, "hello world"); err != nil {
fmt.Printf("the foobar.txt file was not created, reason %v", err.Error())
}
// Create a new directory
helper.MakeDir(newDirPath)
helper.Cmd("odo", "push", "--project", commonVar.Project, "-v4").ShouldPass()
})
It("should correctly propagate changes to the container", func() {
// Check to see if it's been pushed (foobar.txt abd directory testdir)
podName = commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
stdOut = commonVar.CliRunner.ExecListDir(podName, commonVar.Project, sourcePath)
helper.MatchAllInOutput(stdOut, []string{"foobar.txt", "testdir"})
})
When("deleting local files and dir and doing odo push again", func() {
BeforeEach(func() {
// Now we delete the file and dir and push
helper.DeleteDir(newFilePath)
helper.DeleteDir(newDirPath)
helper.Cmd("odo", "push", "--project", commonVar.Project, "-v4").ShouldPass()
})
It("should not list deleted dir and file in container", func() {
podName = commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
// Then check to see if it's truly been deleted
stdOut = commonVar.CliRunner.ExecListDir(podName, commonVar.Project, sourcePath)
helper.DontMatchAllInOutput(stdOut, []string{"foobar.txt", "testdir"})
})
})
})
When("devfile has sourcemappings and doing odo push", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfileSourceMapping.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass().Out()
})
It("should sync files to the correct location", func() {
// Verify source code was synced to /test instead of /projects
var statErr error
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
commonVar.CliRunner.CheckCmdOpInRemoteDevfilePod(
podName,
"runtime",
commonVar.Project,
[]string{"stat", "/test/server.js"},
func(cmdOp string, err error) bool {
statErr = err
return err == nil
},
)
Expect(statErr).ToNot(HaveOccurred())
})
})
When("project and clonePath is present in devfile and doing odo push", func() {
BeforeEach(func() {
// devfile with clonePath set in project field
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-with-projects.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
helper.Cmd("odo", "push", "--v", "5").ShouldPass()
})
It("should sync to the correct dir in container", func() {
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
// source code is synced to $PROJECTS_ROOT/clonePath
// $PROJECTS_ROOT is /projects by default, if sourceMapping is set it is same as sourceMapping
// for devfile-with-projects.yaml, sourceMapping is apps and clonePath is webapp
// so source code would be synced to /apps/webapp
output = commonVar.CliRunner.ExecListDir(podName, commonVar.Project, "/apps/webapp")
helper.MatchAllInOutput(output, []string{"package.json"})
// Verify the sync env variables are correct
utils.VerifyContainerSyncEnv(podName, "runtime", commonVar.Project, "/apps/webapp", "/apps", commonVar.CliRunner)
})
})
When("devfile project field is present and doing odo push", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-with-projects.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
// reset clonePath and change the workdir accordingly, it should sync to project name
helper.ReplaceString(filepath.Join(commonVar.Context, "devfile.yaml"), "clonePath: webapp/", "# clonePath: webapp/")
helper.Cmd("odo", "push").ShouldPass()
})
It("should sync to the correct dir in container", func() {
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
output := commonVar.CliRunner.ExecListDir(podName, commonVar.Project, "/apps/nodeshift")
helper.MatchAllInOutput(output, []string{"package.json"})
// Verify the sync env variables are correct
utils.VerifyContainerSyncEnv(podName, "runtime", commonVar.Project, "/apps/nodeshift", "/apps", commonVar.CliRunner)
})
})
When("multiple project is present", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-with-multiple-projects.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
helper.Cmd("odo", "push").ShouldPass()
})
It("should sync to the correct dir in container", func() {
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
// for devfile-with-multiple-projects.yaml source mapping is not set so $PROJECTS_ROOT is /projects
// multiple projects, so source code would sync to the first project /projects/webapp
output := commonVar.CliRunner.ExecListDir(podName, commonVar.Project, "/projects/webapp")
helper.MatchAllInOutput(output, []string{"package.json"})
// Verify the sync env variables are correct
utils.VerifyContainerSyncEnv(podName, "runtime", commonVar.Project, "/projects/webapp", "/projects", commonVar.CliRunner)
})
})
When("no project is present", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
helper.Cmd("odo", "push").ShouldPass()
})
It("should sync to the correct dir in container", func() {
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
output := commonVar.CliRunner.ExecListDir(podName, commonVar.Project, "/projects")
helper.MatchAllInOutput(output, []string{"package.json"})
// Verify the sync env variables are correct
utils.VerifyContainerSyncEnv(podName, "runtime", commonVar.Project, "/projects", "/projects", commonVar.CliRunner)
})
})
When("doing odo push with devfile contain volume", func() {
var statErr error
var cmdOutput string
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-with-volumes.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass().Out()
})
It("should create pvc and reuse if it shares the same devfile volume name", func() {
helper.MatchAllInOutput(output, []string{
"Executing devbuild command",
"Executing devrun command",
})
// Check to see if it's been pushed (foobar.txt abd directory testdir)
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
commonVar.CliRunner.CheckCmdOpInRemoteDevfilePod(
podName,
"runtime2",
commonVar.Project,
[]string{"cat", "/myvol/myfile.log"},
func(cmdOp string, err error) bool {
cmdOutput = cmdOp
statErr = err
return err == nil
},
)
Expect(statErr).ToNot(HaveOccurred())
Expect(cmdOutput).To(ContainSubstring("hello"))
commonVar.CliRunner.CheckCmdOpInRemoteDevfilePod(
podName,
"runtime2",
commonVar.Project,
[]string{"stat", "/data2"},
func(cmdOp string, err error) bool {
statErr = err
return err == nil
},
)
Expect(statErr).ToNot(HaveOccurred())
})
It("check the volume name and mount paths for the containers", func() {
deploymentName, err := util.NamespaceKubernetesObject(cmpName, "app")
Expect(err).To(BeNil())
volumesMatched := false
// check the volume name and mount paths for the containers
volNamesAndPaths := commonVar.CliRunner.GetVolumeMountNamesandPathsFromContainer(deploymentName, "runtime", commonVar.Project)
volNamesAndPathsArr := strings.Fields(volNamesAndPaths)
for _, volNamesAndPath := range volNamesAndPathsArr {
volNamesAndPathArr := strings.Split(volNamesAndPath, ":")
if strings.Contains(volNamesAndPathArr[0], "myvol") && volNamesAndPathArr[1] == "/data" {
volumesMatched = true
}
}
Expect(volumesMatched).To(Equal(true))
})
})
When("doing odo push with devfile containing volume-component", func() {
BeforeEach(func() {
helper.RenameFile("devfile.yaml", "devfile-old.yaml")
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-with-volume-components.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass().Out()
})
It("should successfully use the volume components in container components", func() {
// Verify the pvc size for firstvol
storageSize := commonVar.CliRunner.GetPVCSize(cmpName, "firstvol", commonVar.Project)
// should be the default size
Expect(storageSize).To(ContainSubstring("1Gi"))
// Verify the pvc size for secondvol
storageSize = commonVar.CliRunner.GetPVCSize(cmpName, "secondvol", commonVar.Project)
// should be the specified size in the devfile volume component
Expect(storageSize).To(ContainSubstring("3Gi"))
})
})
When("doing odo push --debug and devfile contain debugrun", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-with-debugrun.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push", "--debug", "--project", commonVar.Project).ShouldPass().Out()
})
It("should execute debug commands", func() {
helper.MatchAllInOutput(output, []string{
"Executing devbuild command",
"Executing debugrun command",
})
})
When("doing odo push", func() {
BeforeEach(func() {
output = helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass().Out()
})
It("should execute dev commands", func() {
helper.MatchAllInOutput(output, []string{
"Executing devbuild command",
"Executing devrun command",
})
})
})
})
When("doing odo push and run command is not marked as hotReloadCapable", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push").ShouldPass().Out()
})
It("should restart the application", func() {
// TODO: this is almost the same test as one below
Expect(output).To(ContainSubstring("Executing devrun command \"npm start\""))
helper.Cmd("odo", "push", "-f").ShouldPass()
logs := helper.Cmd("odo", "log").ShouldPass().Out()
Expect(logs).To(ContainSubstring("stop the program"))
})
})
When("doing odo push and run command is marked as hotReloadCapable:true", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-with-hotReload.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push").ShouldPass().Out()
})
It("should not restart the application", func() {
Expect(output).To(ContainSubstring("Executing devrun command \"npm start\""))
helper.Cmd("odo", "push", "-f").ShouldPass()
logs := helper.Cmd("odo", "log").ShouldPass().Out()
Expect(logs).To(ContainSubstring("Don't start program again, program is already started"))
})
When("doing odo push --debug ", func() {
stdOut := ""
BeforeEach(func() {
stdOut = helper.Cmd("odo", "push", "--debug", "--project", commonVar.Project).ShouldPass().Out()
})
It("should restart the application regardless of hotReloadCapable value", func() {
Expect(stdOut).To(Not(ContainSubstring("No file changes detected, skipping build")))
logs := helper.Cmd("odo", "log").ShouldPass().Out()
helper.MatchAllInOutput(logs, []string{
"\"stop the program\" program=debugrun",
"\"stop the program\" program=devrun",
})
})
})
})
When("doing odo push and devfile with composite command", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfileCompositeCommands.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push").ShouldPass().Out()
})
It("should execute all commands in composite commmand", func() {
Expect(output).To(ContainSubstring("Executing mkdir command"))
// Verify the command executed successfully
var statErr error
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
commonVar.CliRunner.CheckCmdOpInRemoteDevfilePod(
podName,
"runtime",
commonVar.Project,
[]string{"stat", "/projects/testfolder"},
func(cmdOp string, err error) bool {
statErr = err
return err == nil
},
)
Expect(statErr).ToNot(HaveOccurred())
})
})
When("doing odo push and composite command is marked as paralell:true ", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfileCompositeCommandsParallel.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push", "--build-command", "buildandmkdir").ShouldPass().Out()
})
It("should execute all commands in composite commmand", func() {
Expect(output).To(ContainSubstring("Executing mkdir command"))
// Verify the command executed successfully
var statErr error
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
commonVar.CliRunner.CheckCmdOpInRemoteDevfilePod(
podName,
"runtime",
commonVar.Project,
[]string{"stat", "/projects/testfolder"},
func(cmdOp string, err error) bool {
statErr = err
return err == nil
},
)
Expect(statErr).ToNot(HaveOccurred())
})
})
When("doing odo push and composite command are nested", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfileNestedCompCommands.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push").ShouldPass().Out()
})
It("should execute all commands in composite commmand", func() {
// Verify nested command was executed
Expect(output).To(ContainSubstring("Executing mkdir command"))
// Verify the command executed successfully
var statErr error
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
commonVar.CliRunner.CheckCmdOpInRemoteDevfilePod(
podName,
"runtime",
commonVar.Project,
[]string{"stat", "/projects/testfolder"},
func(cmdOp string, err error) bool {
statErr = err
return err == nil
},
)
Expect(statErr).ToNot(HaveOccurred())
})
})
When("doing odo push and composite command is used as a run command", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfileCompositeRun.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push").ShouldFail().Err()
})
It("should throw a validation error for composite run commands", func() {
Expect(output).To(ContainSubstring("not supported currently"))
})
})
When("events are defined", func() {
It("should correctly execute PreStart commands", func() {
// expectedInitContainers := []string{"tools-myprestart-1", "tools-myprestart-2", "runtime-secondprestart-3"}
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-with-preStart.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output := helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldFail().Err()
// This is expected to fail for now.
// see https://github.com/openshift/odo/issues/4187 for more info
helper.MatchAllInOutput(output, []string{"myprestart should either map to an apply command or a composite command with apply commands\n"})
/*
helper.MatchAllInOutput(output, []string{"PreStart commands have been added to the component"})
firstPushPodName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
firstPushInitContainers := commonVar.CliRunner.GetPodInitContainers(cmpName, commonVar.Project)
// 3 preStart events + 1 supervisord init containers
Expect(len(firstPushInitContainers)).To(Equal(4))
helper.MatchAllInOutput(strings.Join(firstPushInitContainers, ","), expectedInitContainers)
// Need to force so build and run get triggered again with the component already created.
output = helper.Cmd("odo", "push", "--project", commonVar.Project, "-f").ShouldPass().Out()
helper.MatchAllInOutput(output, []string{"PreStart commands have been added to the component"})
secondPushPodName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
secondPushInitContainers := commonVar.CliRunner.GetPodInitContainers(cmpName, commonVar.Project)
Expect(len(secondPushInitContainers)).To(Equal(4))
helper.MatchAllInOutput(strings.Join(secondPushInitContainers, ","), expectedInitContainers)
Expect(firstPushPodName).To(Equal(secondPushPodName))
Expect(firstPushInitContainers).To(Equal(secondPushInitContainers))
var statErr error
commonVar.CliRunner.CheckCmdOpInRemoteDevfilePod(
firstPushPodName,
"runtime",
commonVar.Project,
[]string{"cat", "/projects/test.txt"},
func(cmdOp string, err error) bool {
if err != nil {
statErr = err
} else if cmdOp == "" {
statErr = fmt.Errorf("prestart event action error, expected: hello test2\nhello test2\nhello test\n, got empty string")
} else {
fileContents := strings.Split(cmdOp, "\n")
if len(fileContents)-1 != 3 {
statErr = fmt.Errorf("prestart event action count error, expected: 3 strings, got %d strings: %s", len(fileContents), strings.Join(fileContents, ","))
} else if cmdOp != "hello test2\nhello test2\nhello test\n" {
statErr = fmt.Errorf("prestart event action error, expected: hello test2\nhello test2\nhello test\n, got: %s", cmdOp)
}
}
return true
},
)
Expect(statErr).ToNot(HaveOccurred())
*/
})
It("should correctly execute PostStart commands", func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-with-valid-events.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output := helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass().Out()
helper.MatchAllInOutput(output, []string{"Executing mypoststart command \"echo I am a PostStart\"", "Executing secondpoststart command \"echo I am also a PostStart\""})
// Need to force so build and run get triggered again with the component already created.
output = helper.Cmd("odo", "push", "--project", commonVar.Project, "-f").ShouldPass().Out()
helper.DontMatchAllInOutput(output, []string{"Executing mypoststart command \"echo I am a PostStart\"", "Executing secondpoststart command \"echo I am also a PostStart\""})
helper.MatchAllInOutput(output, []string{
"Executing devbuild command",
"Executing devrun command",
})
})
})
When("doing odo push and using correct custom commands (specified by flags)", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push", "--build-command", "build", "--run-command", "run").ShouldPass().Out()
})
It("should push successfully", func() {
helper.MatchAllInOutput(output, []string{
"Executing build command \"npm install\"",
"Executing run command \"npm start\"",
})
})
})
When("doing odo push and using wrong custom commands (specified by flags)", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push", "--build-command", "buildgarbage").ShouldFail().Err()
})
It("should error out", func() {
Expect(output).NotTo(ContainSubstring("Executing buildgarbage command"))
Expect(output).To(ContainSubstring("the command \"%v\" is not found in the devfile", "buildgarbage"))
})
})
When("command has no group kind and doing odo push", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-with-no-group-kind.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push", "--build-command", "devbuild", "--run-command", "devrun").ShouldPass().Out()
})
It("should execute commands with flags", func() {
helper.MatchAllInOutput(output, []string{
"Executing devbuild command \"npm install\"",
"Executing devrun command \"npm start\"",
})
})
})
When("doing odo push and run command throws an error", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
helper.ReplaceString(filepath.Join(commonVar.Context, "devfile.yaml"), "npm start", "npm starts")
_, output = helper.Cmd("odo", "push").ShouldPass().OutAndErr()
})
It("should wait and error out with some log", func() {
helper.MatchAllInOutput(output, []string{
"exited with error status within 1 sec",
"Did you mean one of these?",
})
_, output = helper.Cmd("odo", "push", "-f", "--run-command", "run").ShouldPass().OutAndErr()
helper.MatchAllInOutput(output, []string{
"exited with error status within 1 sec",
"Did you mean one of these?",
})
})
})
When("commands specify have env variables", func() {
BeforeEach(func() {
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "nodejs", "devfile-with-command-envs.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
})
When("doing odo push and sigle env var is set", func() {
BeforeEach(func() {
output = helper.Cmd("odo", "push", "--build-command", "buildwithenv", "--run-command", "singleenv").ShouldPass().Out()
})
It("should be able to exec command", func() {
helper.MatchAllInOutput(output, []string{"mkdir $ENV1", "mkdir $BUILD_ENV1"})
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
output = commonVar.CliRunner.ExecListDir(podName, commonVar.Project, sourcePath)
helper.MatchAllInOutput(output, []string{"test_env_variable", "test_build_env_variable"})
})
})
When("doing odo push and multiple env variables are set", func() {
BeforeEach(func() {
output = helper.Cmd("odo", "push", "--build-command", "buildwithmultipleenv", "--run-command", "multipleenv").ShouldPass().Out()
})
It("should be able to exec command", func() {
helper.MatchAllInOutput(output, []string{"mkdir $ENV1 $ENV2", "mkdir $BUILD_ENV1 $BUILD_ENV2"})
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
output = commonVar.CliRunner.ExecListDir(podName, commonVar.Project, sourcePath)
helper.MatchAllInOutput(output, []string{"test_build_env_variable1", "test_build_env_variable2", "test_env_variable1", "test_env_variable2"})
})
})
When("doing odo push and there is a env variable with spaces", func() {
BeforeEach(func() {
output = helper.Cmd("odo", "push", "--build-command", "buildenvwithspace", "--run-command", "envwithspace").ShouldPass().Out()
})
It("should be able to exec command", func() {
helper.MatchAllInOutput(output, []string{"mkdir \\\"$ENV1\\\"", "mkdir \\\"$BUILD_ENV1\\\""})
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
output = commonVar.CliRunner.ExecListDir(podName, commonVar.Project, sourcePath)
helper.MatchAllInOutput(output, []string{"build env variable with space", "env with space"})
})
})
})
})
Context("pushing devfile without an .odo folder", func() {
output := ""
It("should error out on odo push and passing invalid devfile", func() {
helper.Cmd("odo", "push", "--project", commonVar.Project, "--devfile", "invalid.yaml").ShouldFail()
})
When("doing odo push", func() {
BeforeEach(func() {
helper.CopyExample(filepath.Join("source", "devfiles", "springboot", "project"), commonVar.Context)
helper.CopyExampleDevFile(filepath.Join("source", "devfiles", "springboot", "devfile.yaml"), filepath.Join(commonVar.Context, "devfile.yaml"))
output = helper.Cmd("odo", "push", "--project", commonVar.Project, "springboot").ShouldPass().Out()
})
It("should be able to push based on name passed", func() {
Expect(output).To(ContainSubstring("Executing devfile commands for component springboot"))
})
})
})
When("Create and push java-springboot component", func() {
var output string
BeforeEach(func() {
helper.Cmd("odo", "create", "--project", commonVar.Project, cmpName, "--devfile", helper.GetExamplePath("source", "devfiles", "springboot", "devfile.yaml")).ShouldPass()
helper.CopyExample(filepath.Join("source", "devfiles", "springboot", "project"), commonVar.Context)
output = helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass().Out()
})
It("should execute default build and run commands correctly", func() {
helper.MatchAllInOutput(output, []string{
"Executing defaultbuild command",
"mvn clean",
"Executing defaultrun command",
"spring-boot:run",
})
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
var statErr error
var cmdOutput string
commonVar.CliRunner.CheckCmdOpInRemoteDevfilePod(
podName,
"runtime",
commonVar.Project,
[]string{"ps", "-ef"},
func(cmdOp string, err error) bool {
cmdOutput = cmdOp
statErr = err
return err == nil
},
)
Expect(statErr).ToNot(HaveOccurred())
Expect(cmdOutput).To(ContainSubstring("spring-boot:run"))
})
})
Context("devfile is modified", func() {
// Tests https://github.com/openshift/odo/issues/3838
ensureFilesSyncedTest := func(namespace string, shouldForcePush bool) {
output := ""
When("java-springboot application is created and pushed", func() {
BeforeEach(func() {
helper.Cmd("odo", "create", "--project", commonVar.Project, cmpName, "--devfile", helper.GetExamplePath("source", "devfiles", "springboot", "devfile-registry.yaml")).ShouldPass()
helper.CopyExample(filepath.Join("source", "devfiles", "springboot", "project"), commonVar.Context)
fmt.Fprintf(GinkgoWriter, "Testing with force push %v", shouldForcePush)
output = helper.Cmd("odo", "push", "--project", commonVar.Project).ShouldPass().Out()
})
It("should push the component successfully", func() {
Expect(output).To(ContainSubstring("Changes successfully pushed to component"))
})
When("Update the devfile.yaml, do odo push", func() {
BeforeEach(func() {
helper.ReplaceString("devfile.yaml", "memoryLimit: 768Mi", "memoryLimit: 769Mi")
commands := []string{"push", "-v", "4", "--project", commonVar.Project}
if shouldForcePush {
commands = append(commands, "-f")
}
output = helper.Cmd("odo", commands...).ShouldPass().Out()
})
It("Ensure the build passes", func() {
Expect(output).To(ContainSubstring("BUILD SUCCESS"))
})
When("compare the local and remote files", func() {
remoteFiles := []string{}
localFiles := []string{}
BeforeEach(func() {
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, namespace)
output = commonVar.CliRunner.Exec(podName, namespace, "find", sourcePath)
outputArr := strings.Split(output, "\n")
for _, line := range outputArr {
if !strings.HasPrefix(line, sourcePath+"/") || strings.Contains(line, "lost+found") {
continue
}
newLine, err := filepath.Rel(sourcePath, line)
Expect(err).ToNot(HaveOccurred())
newLine = filepath.ToSlash(newLine)
if strings.HasPrefix(newLine, "target/") || newLine == "target" || strings.HasPrefix(newLine, ".") {
continue
}
remoteFiles = append(remoteFiles, newLine)
}
// 5) Acquire file from local context, filtering out .*
err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
newPath := filepath.ToSlash(path)
if strings.HasPrefix(newPath, ".") {
return nil
}
localFiles = append(localFiles, newPath)
return nil
})
Expect(err).ToNot(HaveOccurred())
})
It("localFiles and remoteFiles should match", func() {
sort.Strings(localFiles)
sort.Strings(remoteFiles)
Expect(localFiles).To(Equal(remoteFiles))
})
})
})
})
}
Context("odo push -f is executed", func() {
ensureFilesSyncedTest(commonVar.Project, true)
})
Context("odo push (without -f) is executed", func() {
ensureFilesSyncedTest(commonVar.Project, false)
})
})
When("creating nodejs component, doing odo push and run command has dev.odo.push.path attribute", func() {
BeforeEach(func() {
helper.Cmd("odo", "create", cmpName, "--context", commonVar.Context, "--project", commonVar.Project, "--devfile", helper.GetExamplePath("source", "devfiles", "nodejs", "devfile-with-remote-attributes.yaml")).ShouldPass()
helper.CopyExample(filepath.Join("source", "devfiles", "nodejs", "project"), commonVar.Context)
// create a folder and file which shouldn't be pushed
helper.MakeDir(filepath.Join(commonVar.Context, "views"))
_, _ = helper.CreateSimpleFile(filepath.Join(commonVar.Context, "views"), "view", ".html")
helper.ReplaceString("package.json", "node server.js", "node server/server.js")
helper.Cmd("odo", "push", "--context", commonVar.Context).ShouldPass()
})
It("should push only the mentioned files at the appropriate remote destination", func() {
podName := commonVar.CliRunner.GetRunningPodNameByComponent(cmpName, commonVar.Project)
stdOut := commonVar.CliRunner.ExecListDir(podName, commonVar.Project, sourcePath)
helper.MatchAllInOutput(stdOut, []string{"package.json", "server"})
helper.DontMatchAllInOutput(stdOut, []string{"test", "views", "devfile.yaml"})
stdOut = commonVar.CliRunner.ExecListDir(podName, commonVar.Project, sourcePath+"/server")
helper.MatchAllInOutput(stdOut, []string{"server.js", "test"})
stdOut = helper.Cmd("odo", "push", "--context", commonVar.Context).ShouldPass().Out()
Expect(stdOut).To(ContainSubstring("No file changes detected"))
})
})
Context("using OpenShift cluster", func() {
BeforeEach(func() {
if os.Getenv("KUBERNETES") == "true" {
Skip("This is a OpenShift specific scenario, skipping")
}
})
When("project with with 'default' name is used", func() {
It("should throw an error", func() {
componentName := helper.RandString(6)
helper.CopyExample(filepath.Join("source", "nodejs"), commonVar.Context)
helper.Cmd("odo", "create", "--project", "default", componentName, "--devfile", helper.GetExamplePath("source", "devfiles", "nodejs", "devfile.yaml")).ShouldPass()
helper.CopyExample(filepath.Join("source", "devfiles", "nodejs", "project"), commonVar.Context)
stdout := helper.Cmd("odo", "push").ShouldFail().Err()
helper.MatchAllInOutput(stdout, []string{"odo may not work as expected in the default project, please run the odo component in a non-default project"})
})
})
})
Context("using Kubernetes cluster", func() {
BeforeEach(func() {
if os.Getenv("KUBERNETES") != "true" {
Skip("This is a Kubernetes specific scenario, skipping")
}
})
When("project with with 'default' name is used", func() {
It("should push successfully", func() {
componentName := helper.RandString(6)
helper.CopyExample(filepath.Join("source", "nodejs"), commonVar.Context)
helper.Cmd("odo", "create", "--project", "default", componentName, "--devfile", helper.GetExamplePath("source", "devfiles", "nodejs", "devfile.yaml")).ShouldPass()
helper.CopyExample(filepath.Join("source", "devfiles", "nodejs", "project"), commonVar.Context)
stdout := helper.Cmd("odo", "push").ShouldPass().Out()
helper.DontMatchAllInOutput(stdout, []string{"odo may not work as expected in the default project"})
helper.Cmd("odo", "delete", "-f").ShouldPass()
})
})
})
})
|
[
"\"KUBERNETES\"",
"\"KUBERNETES\""
] |
[] |
[
"KUBERNETES"
] |
[]
|
["KUBERNETES"]
|
go
| 1 | 0 | |
elf_reader_test.go
|
package ebpf
import (
"bytes"
"encoding/binary"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"github.com/cilium/ebpf/internal"
"github.com/cilium/ebpf/internal/btf"
"github.com/cilium/ebpf/internal/testutils"
"github.com/cilium/ebpf/internal/unix"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
func TestLoadCollectionSpec(t *testing.T) {
cpus, err := internal.PossibleCPUs()
if err != nil {
t.Fatal(err)
}
coll := &CollectionSpec{
Maps: map[string]*MapSpec{
"hash_map": {
Name: "hash_map",
Type: Hash,
KeySize: 4,
ValueSize: 8,
MaxEntries: 1,
Flags: unix.BPF_F_NO_PREALLOC,
},
"hash_map2": {
Name: "hash_map2",
Type: Hash,
KeySize: 4,
ValueSize: 8,
MaxEntries: 2,
},
"array_of_hash_map": {
Name: "array_of_hash_map",
Type: ArrayOfMaps,
KeySize: 4,
MaxEntries: 2,
},
"perf_event_array": {
Name: "perf_event_array",
Type: PerfEventArray,
MaxEntries: uint32(cpus),
},
// Maps prefixed by btf_ are ignored when testing ELFs
// that don't have BTF info embedded. (clang<9)
"btf_pin": {
Name: "btf_pin",
Type: Hash,
KeySize: 4,
ValueSize: 8,
MaxEntries: 1,
Pinning: PinByName,
},
"btf_outer_map": {
Name: "btf_outer_map",
Type: ArrayOfMaps,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
InnerMap: &MapSpec{
Name: "btf_outer_map_inner",
Type: Hash,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
},
},
"btf_outer_map_anon": {
Name: "btf_outer_map_anon",
Type: ArrayOfMaps,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
InnerMap: &MapSpec{
Name: "btf_outer_map_anon_inner",
Type: Hash,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
},
},
},
Programs: map[string]*ProgramSpec{
"xdp_prog": {
Name: "xdp_prog",
Type: XDP,
SectionName: "xdp",
License: "MIT",
},
"no_relocation": {
Name: "no_relocation",
Type: SocketFilter,
SectionName: "socket",
License: "MIT",
},
"asm_relocation": {
Name: "asm_relocation",
Type: SocketFilter,
SectionName: "socket/2",
License: "MIT",
},
"data_sections": {
Name: "data_sections",
Type: SocketFilter,
SectionName: "socket/3",
License: "MIT",
},
"global_fn3": {
Name: "global_fn3",
Type: UnspecifiedProgram,
SectionName: "other",
License: "MIT",
},
"static_fn": {
Name: "static_fn",
Type: UnspecifiedProgram,
SectionName: "static",
License: "MIT",
},
},
}
defaultOpts := cmp.Options{
// Dummy Comparer that works with empty readers to support test cases.
cmp.Comparer(func(a, b bytes.Reader) bool {
if a.Len() == 0 && b.Len() == 0 {
return true
}
return false
}),
cmpopts.IgnoreTypes(new(btf.Map), new(btf.Program)),
cmpopts.IgnoreFields(CollectionSpec{}, "ByteOrder", "Types"),
cmpopts.IgnoreFields(ProgramSpec{}, "Instructions", "ByteOrder"),
cmpopts.IgnoreUnexported(ProgramSpec{}),
cmpopts.IgnoreMapEntries(func(key string, _ *MapSpec) bool {
switch key {
case ".bss", ".data", ".rodata":
return true
default:
return false
}
}),
}
ignoreBTFOpts := append(defaultOpts,
cmpopts.IgnoreMapEntries(func(key string, _ *MapSpec) bool {
return strings.HasPrefix(key, "btf_")
}),
)
testutils.Files(t, testutils.Glob(t, "testdata/loader-*.elf"), func(t *testing.T, file string) {
have, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal("Can't parse ELF:", err)
}
opts := defaultOpts
if have.Maps[".rodata"] != nil {
err := have.RewriteConstants(map[string]interface{}{
"arg": uint32(1),
})
if err != nil {
t.Fatal("Can't rewrite constant:", err)
}
err = have.RewriteConstants(map[string]interface{}{
"totallyBogus": uint32(1),
})
if err == nil {
t.Error("Rewriting a bogus constant doesn't fail")
}
} else {
opts = ignoreBTFOpts
}
if diff := cmp.Diff(coll, have, opts...); diff != "" {
t.Errorf("MapSpec mismatch (-want +got):\n%s", diff)
}
if have.ByteOrder != internal.NativeEndian {
return
}
have.Maps["array_of_hash_map"].InnerMap = have.Maps["hash_map"]
coll, err := NewCollectionWithOptions(have, CollectionOptions{
Maps: MapOptions{
PinPath: testutils.TempBPFFS(t),
},
Programs: ProgramOptions{
LogLevel: 1,
},
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer coll.Close()
ret, _, err := coll.Programs["xdp_prog"].Test(make([]byte, 14))
if err != nil {
t.Fatal("Can't run program:", err)
}
if ret != 5 {
t.Error("Expected return value to be 5, got", ret)
}
})
}
func BenchmarkELFLoader(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = LoadCollectionSpec("testdata/loader-el.elf")
}
}
func TestDataSections(t *testing.T) {
file := fmt.Sprintf("testdata/loader-%s.elf", internal.ClangEndian)
coll, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal(err)
}
t.Log(coll.Programs["data_sections"].Instructions)
var obj struct {
Program *Program `ebpf:"data_sections"`
}
err = coll.LoadAndAssign(&obj, nil)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer obj.Program.Close()
ret, _, err := obj.Program.Test(make([]byte, 14))
if err != nil {
t.Fatal(err)
}
if ret != 0 {
t.Error("BPF assertion failed on line", ret)
}
}
func TestInlineASMConstant(t *testing.T) {
file := fmt.Sprintf("testdata/loader-%s.elf", internal.ClangEndian)
coll, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal(err)
}
spec := coll.Programs["asm_relocation"]
if spec.Instructions[0].Reference() != "MY_CONST" {
t.Fatal("First instruction is not a reference to MY_CONST")
}
// -1 is used by the loader to find unrewritten maps.
spec.Instructions[0].Constant = -1
t.Log(spec.Instructions)
var obj struct {
Program *Program `ebpf:"asm_relocation"`
}
err = coll.LoadAndAssign(&obj, nil)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
obj.Program.Close()
}
func TestCollectionSpecDetach(t *testing.T) {
coll := Collection{
Maps: map[string]*Map{
"foo": new(Map),
},
Programs: map[string]*Program{
"bar": new(Program),
},
}
foo := coll.DetachMap("foo")
if foo == nil {
t.Error("Program not returned from DetachMap")
}
if _, ok := coll.Programs["foo"]; ok {
t.Error("DetachMap doesn't remove map from Maps")
}
bar := coll.DetachProgram("bar")
if bar == nil {
t.Fatal("Program not returned from DetachProgram")
}
if _, ok := coll.Programs["bar"]; ok {
t.Error("DetachProgram doesn't remove program from Programs")
}
}
func TestLoadInvalidMap(t *testing.T) {
testutils.Files(t, testutils.Glob(t, "testdata/invalid_map-*.elf"), func(t *testing.T, file string) {
cs, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal("Can't load CollectionSpec", err)
}
ms, ok := cs.Maps["invalid_map"]
if !ok {
t.Fatal("invalid_map not found in CollectionSpec")
}
m, err := NewMap(ms)
t.Log(err)
if err == nil {
m.Close()
t.Fatal("Creating a Map from a MapSpec with non-zero Extra is expected to fail.")
}
})
}
func TestLoadInvalidMapMissingSymbol(t *testing.T) {
testutils.Files(t, testutils.Glob(t, "testdata/invalid_map_static-el.elf"), func(t *testing.T, file string) {
_, err := LoadCollectionSpec(file)
t.Log(err)
if err == nil {
t.Fatal("Loading a map with static qualifier should fail")
}
})
}
func TestLoadInitializedBTFMap(t *testing.T) {
testutils.Files(t, testutils.Glob(t, "testdata/btf_map_init-*.elf"), func(t *testing.T, file string) {
coll, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal(err)
}
t.Run("prog_array", func(t *testing.T) {
m, ok := coll.Maps["prog_array_init"]
if !ok {
t.Fatal("map prog_array_init not found in program")
}
if len(m.Contents) != 1 {
t.Error("expecting exactly 1 item in MapSpec contents")
}
p := m.Contents[0]
if cmp.Equal(p.Key, 1) {
t.Errorf("expecting MapSpec entry Key to equal 1, got %v", p.Key)
}
if _, ok := p.Value.(string); !ok {
t.Errorf("expecting MapSpec entry Value to be a string, got %T", p.Value)
}
if p.Value != "tail_1" {
t.Errorf("expected MapSpec entry Value 'tail_1', got: %s", p.Value)
}
})
t.Run("array_of_maps", func(t *testing.T) {
m, ok := coll.Maps["outer_map_init"]
if !ok {
t.Fatal("map outer_map_init not found in program")
}
if len(m.Contents) != 1 {
t.Error("expecting exactly 1 item in MapSpec contents")
}
p := m.Contents[0]
if cmp.Equal(p.Key, 1) {
t.Errorf("expecting MapSpec entry Key to equal 1, got %v", p.Key)
}
if _, ok := p.Value.(string); !ok {
t.Errorf("expecting MapSpec entry Value to be a string, got %T", p.Value)
}
if p.Value != "inner_map" {
t.Errorf("expected MapSpec entry Value 'inner_map', got: %s", p.Value)
}
})
})
}
func TestLoadInvalidInitializedBTFMap(t *testing.T) {
testutils.Files(t, testutils.Glob(t, "testdata/invalid_btf_map_init-*.elf"), func(t *testing.T, file string) {
_, err := LoadCollectionSpec(file)
t.Log(err)
if !errors.Is(err, internal.ErrNotSupported) {
t.Fatal("Loading an initialized BTF map should be unsupported")
}
})
}
func TestStringSection(t *testing.T) {
testutils.Files(t, testutils.Glob(t, "testdata/strings-*.elf"), func(t *testing.T, file string) {
_, err := LoadCollectionSpec(file)
t.Log(err)
if !errors.Is(err, ErrNotSupported) {
t.Error("References to a string section should be unsupported")
}
})
}
func TestLoadRawTracepoint(t *testing.T) {
testutils.SkipOnOldKernel(t, "4.17", "BPF_RAW_TRACEPOINT API")
testutils.Files(t, testutils.Glob(t, "testdata/raw_tracepoint-*.elf"), func(t *testing.T, file string) {
spec, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal("Can't parse ELF:", err)
}
if spec.ByteOrder != internal.NativeEndian {
return
}
coll, err := NewCollectionWithOptions(spec, CollectionOptions{
Programs: ProgramOptions{
LogLevel: 1,
},
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("Can't create collection:", err)
}
coll.Close()
})
}
func TestTailCall(t *testing.T) {
testutils.Files(t, testutils.Glob(t, "testdata/btf_map_init-*.elf"), func(t *testing.T, file string) {
spec, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal(err)
}
if spec.ByteOrder != internal.NativeEndian {
return
}
var obj struct {
TailMain *Program `ebpf:"tail_main"`
ProgArray *Map `ebpf:"prog_array_init"`
}
err = spec.LoadAndAssign(&obj, nil)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer obj.TailMain.Close()
ret, _, err := obj.TailMain.Test(make([]byte, 14))
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
// Expect the tail_1 tail call to be taken, returning value 42.
if ret != 42 {
t.Fatalf("Expected tail call to return value 42, got %d", ret)
}
})
}
func TestSubprogRelocation(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.13", "bpf_for_each_map_elem")
testutils.Files(t, testutils.Glob(t, "testdata/subprog_reloc-*.elf"), func(t *testing.T, file string) {
spec, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal(err)
}
if spec.ByteOrder != internal.NativeEndian {
return
}
var obj struct {
Main *Program `ebpf:"fp_relocation"`
HashMap *Map `ebpf:"hash_map"`
}
err = spec.LoadAndAssign(&obj, nil)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer obj.Main.Close()
ret, _, err := obj.Main.Test(make([]byte, 14))
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
if ret != 42 {
t.Fatalf("Expected subprog reloc to return value 42, got %d", ret)
}
})
}
func TestUnassignedProgArray(t *testing.T) {
testutils.Files(t, testutils.Glob(t, "testdata/btf_map_init-*.elf"), func(t *testing.T, file string) {
spec, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal(err)
}
if spec.ByteOrder != internal.NativeEndian {
return
}
// tail_main references a ProgArray that is not being assigned
// to this struct. Normally, this would clear all its entries
// and make any tail calls into the ProgArray result in a miss.
// The library needs to explicitly refuse such operations.
var obj struct {
TailMain *Program `ebpf:"tail_main"`
// ProgArray *Map `ebpf:"prog_array_init"`
}
err = spec.LoadAndAssign(&obj, nil)
testutils.SkipIfNotSupported(t, err)
if err == nil {
obj.TailMain.Close()
t.Fatal("Expecting LoadAndAssign to return error")
}
})
}
func TestIPRoute2Compat(t *testing.T) {
testutils.Files(t, testutils.Glob(t, "testdata/iproute2_map_compat-*.elf"), func(t *testing.T, file string) {
spec, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal("Can't parse ELF:", err)
}
if spec.ByteOrder != internal.NativeEndian {
return
}
ms, ok := spec.Maps["hash_map"]
if !ok {
t.Fatal("Map hash_map not found")
}
var id, pinning, innerID, innerIndex uint32
if ms.Extra == nil {
t.Fatal("missing extra bytes")
}
switch {
case binary.Read(ms.Extra, spec.ByteOrder, &id) != nil:
t.Fatal("missing id")
case binary.Read(ms.Extra, spec.ByteOrder, &pinning) != nil:
t.Fatal("missing pinning")
case binary.Read(ms.Extra, spec.ByteOrder, &innerID) != nil:
t.Fatal("missing inner_id")
case binary.Read(ms.Extra, spec.ByteOrder, &innerIndex) != nil:
t.Fatal("missing inner_idx")
}
if id != 0 || innerID != 0 || innerIndex != 0 {
t.Fatal("expecting id, inner_id and inner_idx to be zero")
}
if pinning != 2 {
t.Fatal("expecting pinning field to be 2 (PIN_GLOBAL_NS)")
}
// iproute2 (tc) pins maps in /sys/fs/bpf/tc/globals with PIN_GLOBAL_NS,
// which needs to be be configured in this library using MapOptions.PinPath.
// For the sake of the test, we use a tempdir on bpffs below.
ms.Pinning = PinByName
coll, err := NewCollectionWithOptions(spec, CollectionOptions{
Maps: MapOptions{
PinPath: testutils.TempBPFFS(t),
},
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("Can't create collection:", err)
}
coll.Close()
})
}
var (
elfPath = flag.String("elfs", os.Getenv("KERNEL_SELFTESTS"), "`Path` containing libbpf-compatible ELFs (defaults to $KERNEL_SELFTESTS)")
elfPattern = flag.String("elf-pattern", "*.o", "Glob `pattern` for object files that should be tested")
)
func TestLibBPFCompat(t *testing.T) {
if *elfPath == "" {
// Specify the path to the directory containing the eBPF for
// the kernel's selftests if you want to run this test.
// As of 5.2 that is tools/testing/selftests/bpf/
t.Skip("No path specified")
}
load := func(t *testing.T, spec *CollectionSpec, opts CollectionOptions, valid bool) {
// Disable retrying a program load with the log enabled, it leads
// to OOM kills.
opts.Programs.LogSize = -1
for name, p := range spec.Programs {
if p.Type != Extension {
continue
}
targetProg, targetColl := loadTargetProgram(t, name, opts)
defer targetColl.Close()
p.AttachTarget = targetProg
}
coll, err := NewCollectionWithOptions(spec, opts)
testutils.SkipIfNotSupported(t, err)
var errno syscall.Errno
if errors.As(err, &errno) {
// This error is most likely from a syscall and caused by us not
// replicating some fixups done in the selftests or the test
// intentionally failing. This is expected, so skip the test
// instead of failing.
t.Skip("Skipping since the kernel rejected the program:", errno)
}
if err == nil {
coll.Close()
}
if !valid {
if err == nil {
t.Fatal("Expected an error during load")
}
} else if err != nil {
t.Fatal("Error during loading:", err)
}
}
files := testutils.Glob(t, filepath.Join(*elfPath, *elfPattern),
// These files are only used as a source of btf.
"btf__core_reloc_*",
)
testutils.Files(t, files, func(t *testing.T, path string) {
file := filepath.Base(path)
switch file {
case "test_map_in_map.o", "test_map_in_map.linked3.o",
"test_select_reuseport_kern.o", "test_select_reuseport_kern.linked3.o":
t.Skip("Skipping due to missing InnerMap in map definition")
case "test_core_autosize.o":
t.Skip("Skipping since the test generates dynamic BTF")
case "test_static_linked.linked3.o":
t.Skip("Skipping since .text contains 'subprog' twice")
case "linked_maps.linked3.o", "linked_funcs.linked3.o":
t.Skip("Skipping since weak relocations are not supported")
}
t.Parallel()
spec, err := LoadCollectionSpec(path)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatalf("Can't read %s: %s", file, err)
}
switch file {
case "test_sk_assign.o":
// Test contains a legacy iproute2 bpf_elf_map definition.
for _, m := range spec.Maps {
if m.Extra == nil || m.Extra.Len() == 0 {
t.Fatalf("Expected extra bytes in map %s", m.Name)
}
m.Extra = nil
}
}
var opts CollectionOptions
for _, mapSpec := range spec.Maps {
if mapSpec.Pinning != PinNone {
opts.Maps.PinPath = testutils.TempBPFFS(t)
break
}
}
coreFiles := sourceOfBTF(t, path)
if len(coreFiles) == 0 {
// NB: test_core_reloc_kernel.o doesn't have dedicated BTF and
// therefore goes via this code path.
load(t, spec, opts, true)
return
}
for _, coreFile := range coreFiles {
name := filepath.Base(coreFile)
t.Run(name, func(t *testing.T) {
// Some files like btf__core_reloc_arrays___err_too_small.o
// trigger an error on purpose. Use the name to infer whether
// the test should succeed.
var valid bool
switch name {
case "btf__core_reloc_existence___err_wrong_arr_kind.o",
"btf__core_reloc_existence___err_wrong_arr_value_type.o",
"btf__core_reloc_existence___err_wrong_int_kind.o",
"btf__core_reloc_existence___err_wrong_int_sz.o",
"btf__core_reloc_existence___err_wrong_int_type.o",
"btf__core_reloc_existence___err_wrong_struct_type.o":
// These tests are buggy upstream, see https://lore.kernel.org/bpf/[email protected]/
valid = true
case "btf__core_reloc_ints___err_wrong_sz_16.o",
"btf__core_reloc_ints___err_wrong_sz_32.o",
"btf__core_reloc_ints___err_wrong_sz_64.o",
"btf__core_reloc_ints___err_wrong_sz_8.o",
"btf__core_reloc_arrays___err_wrong_val_type1.o",
"btf__core_reloc_arrays___err_wrong_val_type2.o":
// These tests are valid according to current libbpf behaviour,
// see commit 42765ede5c54ca915de5bfeab83be97207e46f68.
valid = true
case "btf__core_reloc_type_id___missing_targets.o",
"btf__core_reloc_flavors__err_wrong_name.o":
valid = false
case "btf__core_reloc_ints___err_bitfield.o":
// Bitfields are now valid.
valid = true
default:
valid = !strings.Contains(name, "___err_")
}
fh, err := os.Open(coreFile)
if err != nil {
t.Fatal(err)
}
defer fh.Close()
opts := opts // copy
opts.Programs.TargetBTF = fh
load(t, spec, opts, valid)
})
}
})
}
func loadTargetProgram(tb testing.TB, name string, opts CollectionOptions) (*Program, *Collection) {
file := "test_pkt_access.o"
program := "test_pkt_access"
switch name {
case "new_connect_v4_prog":
file = "connect4_prog.o"
program = "connect_v4_prog"
case "new_do_bind":
file = "connect4_prog.o"
program = "connect_v4_prog"
case "freplace_cls_redirect_test":
file = "test_cls_redirect.o"
program = "cls_redirect"
case "new_handle_kprobe":
file = "test_attach_probe.o"
program = "handle_kprobe"
case "test_pkt_md_access_new":
file = "test_pkt_md_access.o"
program = "test_pkt_md_access"
default:
}
spec, err := LoadCollectionSpec(filepath.Join(*elfPath, file))
if err != nil {
tb.Fatalf("Can't read %s: %s", file, err)
}
coll, err := NewCollectionWithOptions(spec, opts)
if err != nil {
tb.Fatalf("Can't load target: %s", err)
}
return coll.Programs[program], coll
}
func sourceOfBTF(tb testing.TB, path string) []string {
const testPrefix = "test_core_reloc_"
const btfPrefix = "btf__core_reloc_"
dir, base := filepath.Split(path)
if !strings.HasPrefix(base, testPrefix) {
return nil
}
base = strings.TrimSuffix(base[len(testPrefix):], ".o")
switch base {
case "bitfields_direct", "bitfields_probed":
base = "bitfields"
}
return testutils.Glob(tb, filepath.Join(dir, btfPrefix+base+"*.o"))
}
func TestGetProgType(t *testing.T) {
type progTypeTestData struct {
Pt ProgramType
At AttachType
Fl uint32
To string
}
testcases := map[string]progTypeTestData{
"socket/garbage": {
Pt: SocketFilter,
At: AttachNone,
To: "",
},
"kprobe/func": {
Pt: Kprobe,
At: AttachNone,
To: "func",
},
"xdp/foo": {
Pt: XDP,
At: AttachNone,
To: "",
},
"xdp_devmap/foo": {
Pt: XDP,
At: AttachXDPDevMap,
To: "foo",
},
"cgroup_skb/ingress": {
Pt: CGroupSKB,
At: AttachCGroupInetIngress,
To: "",
},
"iter/bpf_map": {
Pt: Tracing,
At: AttachTraceIter,
To: "bpf_map",
},
"lsm.s/file_ioctl_sleepable": {
Pt: LSM,
At: AttachLSMMac,
To: "file_ioctl_sleepable",
Fl: unix.BPF_F_SLEEPABLE,
},
"lsm/file_ioctl": {
Pt: LSM,
At: AttachLSMMac,
To: "file_ioctl",
},
"sk_skb/stream_verdict/foo": {
Pt: SkSKB,
At: AttachSkSKBStreamVerdict,
To: "",
},
"sk_skb/bar": {
Pt: SkSKB,
At: AttachNone,
To: "",
},
}
for section, want := range testcases {
pt, at, fl, to := getProgType(section)
if diff := cmp.Diff(want, progTypeTestData{Pt: pt, At: at, Fl: fl, To: to}); diff != "" {
t.Errorf("getProgType mismatch (-want +got):\n%s", diff)
}
}
}
|
[
"\"KERNEL_SELFTESTS\""
] |
[] |
[
"KERNEL_SELFTESTS"
] |
[]
|
["KERNEL_SELFTESTS"]
|
go
| 1 | 0 | |
vendor/github.com/docker/libcompose/docker/client/client.go
|
package client
import (
"fmt"
"net/http"
"os"
"path/filepath"
"runtime"
"github.com/docker/docker/cliconfig"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/homedir"
"github.com/docker/go-connections/sockets"
"github.com/docker/go-connections/tlsconfig"
"github.com/docker/libcompose/version"
)
const (
// DefaultAPIVersion is the default docker API version set by libcompose
DefaultAPIVersion = "v1.20"
defaultTrustKeyFile = "key.json"
defaultCaFile = "ca.pem"
defaultKeyFile = "key.pem"
defaultCertFile = "cert.pem"
)
var (
dockerCertPath = os.Getenv("DOCKER_CERT_PATH")
)
func init() {
if dockerCertPath == "" {
dockerCertPath = cliconfig.ConfigDir()
}
}
// Options holds docker client options (host, tls, ..)
type Options struct {
TLS bool
TLSVerify bool
TLSOptions tlsconfig.Options
TrustKey string
Host string
APIVersion string
}
// Create creates a docker client based on the specified options.
func Create(c Options) (client.APIClient, error) {
if c.Host == "" {
if os.Getenv("DOCKER_API_VERSION") == "" {
os.Setenv("DOCKER_API_VERSION", DefaultAPIVersion)
}
client, err := client.NewEnvClient()
if err != nil {
return nil, err
}
return client, nil
}
apiVersion := c.APIVersion
if apiVersion == "" {
apiVersion = DefaultAPIVersion
}
if c.TLSOptions.CAFile == "" {
c.TLSOptions.CAFile = filepath.Join(dockerCertPath, defaultCaFile)
}
if c.TLSOptions.CertFile == "" {
c.TLSOptions.CertFile = filepath.Join(dockerCertPath, defaultCertFile)
}
if c.TLSOptions.KeyFile == "" {
c.TLSOptions.KeyFile = filepath.Join(dockerCertPath, defaultKeyFile)
}
if c.TrustKey == "" {
c.TrustKey = filepath.Join(homedir.Get(), ".docker", defaultTrustKeyFile)
}
if c.TLSVerify {
c.TLS = true
}
if c.TLS {
c.TLSOptions.InsecureSkipVerify = !c.TLSVerify
}
var httpClient *http.Client
if c.TLS {
config, err := tlsconfig.Client(c.TLSOptions)
if err != nil {
return nil, err
}
tr := &http.Transport{
TLSClientConfig: config,
}
proto, addr, _, err := client.ParseHost(c.Host)
if err != nil {
return nil, err
}
if err := sockets.ConfigureTransport(tr, proto, addr); err != nil {
return nil, err
}
httpClient = &http.Client{
Transport: tr,
}
}
customHeaders := map[string]string{}
customHeaders["User-Agent"] = fmt.Sprintf("Libcompose-Client/%s (%s)", version.VERSION, runtime.GOOS)
client, err := client.NewClient(c.Host, apiVersion, httpClient, customHeaders)
if err != nil {
return nil, err
}
return client, nil
}
|
[
"\"DOCKER_CERT_PATH\"",
"\"DOCKER_API_VERSION\""
] |
[] |
[
"DOCKER_API_VERSION",
"DOCKER_CERT_PATH"
] |
[]
|
["DOCKER_API_VERSION", "DOCKER_CERT_PATH"]
|
go
| 2 | 0 | |
copy_from_test.go
|
package pgx_test
import (
"context"
"fmt"
"os"
"reflect"
"testing"
"time"
"github.com/matthewpi/pgconn"
"github.com/matthewpi/pgx/v4"
"github.com/stretchr/testify/require"
)
func TestConnCopyFromSmall(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
mustExec(t, conn, `create temporary table foo(
a int2,
b int4,
c int8,
d varchar,
e text,
f date,
g timestamptz
)`)
tzedTime := time.Date(2010, 2, 3, 4, 5, 6, 0, time.Local)
inputRows := [][]interface{}{
{int16(0), int32(1), int64(2), "abc", "efg", time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), tzedTime},
{nil, nil, nil, nil, nil, nil, nil},
}
copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f", "g"}, pgx.CopyFromRows(inputRows))
if err != nil {
t.Errorf("Unexpected error for CopyFrom: %v", err)
}
if int(copyCount) != len(inputRows) {
t.Errorf("Expected CopyFrom to return %d copied rows, but got %d", len(inputRows), copyCount)
}
rows, err := conn.Query(context.Background(), "select * from foo")
if err != nil {
t.Errorf("Unexpected error for Query: %v", err)
}
var outputRows [][]interface{}
for rows.Next() {
row, err := rows.Values()
if err != nil {
t.Errorf("Unexpected error for rows.Values(): %v", err)
}
outputRows = append(outputRows, row)
}
if rows.Err() != nil {
t.Errorf("Unexpected error for rows.Err(): %v", rows.Err())
}
if !reflect.DeepEqual(inputRows, outputRows) {
t.Errorf("Input rows and output rows do not equal: %v -> %v", inputRows, outputRows)
}
ensureConnValid(t, conn)
}
func TestConnCopyFromSliceSmall(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
mustExec(t, conn, `create temporary table foo(
a int2,
b int4,
c int8,
d varchar,
e text,
f date,
g timestamptz
)`)
tzedTime := time.Date(2010, 2, 3, 4, 5, 6, 0, time.Local)
inputRows := [][]interface{}{
{int16(0), int32(1), int64(2), "abc", "efg", time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), tzedTime},
{nil, nil, nil, nil, nil, nil, nil},
}
copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f", "g"},
pgx.CopyFromSlice(len(inputRows), func(i int) ([]interface{}, error) {
return inputRows[i], nil
}))
if err != nil {
t.Errorf("Unexpected error for CopyFrom: %v", err)
}
if int(copyCount) != len(inputRows) {
t.Errorf("Expected CopyFrom to return %d copied rows, but got %d", len(inputRows), copyCount)
}
rows, err := conn.Query(context.Background(), "select * from foo")
if err != nil {
t.Errorf("Unexpected error for Query: %v", err)
}
var outputRows [][]interface{}
for rows.Next() {
row, err := rows.Values()
if err != nil {
t.Errorf("Unexpected error for rows.Values(): %v", err)
}
outputRows = append(outputRows, row)
}
if rows.Err() != nil {
t.Errorf("Unexpected error for rows.Err(): %v", rows.Err())
}
if !reflect.DeepEqual(inputRows, outputRows) {
t.Errorf("Input rows and output rows do not equal: %v -> %v", inputRows, outputRows)
}
ensureConnValid(t, conn)
}
func TestConnCopyFromLarge(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
skipCockroachDB(t, conn, "Skipping due to known server issue: (https://github.com/cockroachdb/cockroach/issues/52722)")
mustExec(t, conn, `create temporary table foo(
a int2,
b int4,
c int8,
d varchar,
e text,
f date,
g timestamptz,
h bytea
)`)
tzedTime := time.Date(2010, 2, 3, 4, 5, 6, 0, time.Local)
inputRows := [][]interface{}{}
for i := 0; i < 10000; i++ {
inputRows = append(inputRows, []interface{}{int16(0), int32(1), int64(2), "abc", "efg", time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), tzedTime, []byte{111, 111, 111, 111}})
}
copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f", "g", "h"}, pgx.CopyFromRows(inputRows))
if err != nil {
t.Errorf("Unexpected error for CopyFrom: %v", err)
}
if int(copyCount) != len(inputRows) {
t.Errorf("Expected CopyFrom to return %d copied rows, but got %d", len(inputRows), copyCount)
}
rows, err := conn.Query(context.Background(), "select * from foo")
if err != nil {
t.Errorf("Unexpected error for Query: %v", err)
}
var outputRows [][]interface{}
for rows.Next() {
row, err := rows.Values()
if err != nil {
t.Errorf("Unexpected error for rows.Values(): %v", err)
}
outputRows = append(outputRows, row)
}
if rows.Err() != nil {
t.Errorf("Unexpected error for rows.Err(): %v", rows.Err())
}
if !reflect.DeepEqual(inputRows, outputRows) {
t.Errorf("Input rows and output rows do not equal")
}
ensureConnValid(t, conn)
}
func TestConnCopyFromEnum(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
ctx := context.Background()
tx, err := conn.Begin(ctx)
require.NoError(t, err)
defer tx.Rollback(ctx)
_, err = tx.Exec(ctx, `drop type if exists color`)
require.NoError(t, err)
_, err = tx.Exec(ctx, `drop type if exists fruit`)
require.NoError(t, err)
_, err = tx.Exec(ctx, `create type color as enum ('blue', 'green', 'orange')`)
require.NoError(t, err)
_, err = tx.Exec(ctx, `create type fruit as enum ('apple', 'orange', 'grape')`)
require.NoError(t, err)
_, err = tx.Exec(ctx, `create table foo(
a text,
b color,
c fruit,
d color,
e fruit,
f text
)`)
require.NoError(t, err)
inputRows := [][]interface{}{
{"abc", "blue", "grape", "orange", "orange", "def"},
{nil, nil, nil, nil, nil, nil},
}
copyCount, err := conn.CopyFrom(ctx, pgx.Identifier{"foo"}, []string{"a", "b", "c", "d", "e", "f"}, pgx.CopyFromRows(inputRows))
require.NoError(t, err)
require.EqualValues(t, len(inputRows), copyCount)
rows, err := conn.Query(ctx, "select * from foo")
require.NoError(t, err)
var outputRows [][]interface{}
for rows.Next() {
row, err := rows.Values()
require.NoError(t, err)
outputRows = append(outputRows, row)
}
require.NoError(t, rows.Err())
if !reflect.DeepEqual(inputRows, outputRows) {
t.Errorf("Input rows and output rows do not equal: %v -> %v", inputRows, outputRows)
}
ensureConnValid(t, conn)
}
func TestConnCopyFromJSON(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
for _, typeName := range []string{"json", "jsonb"} {
if _, ok := conn.ConnInfo().DataTypeForName(typeName); !ok {
return // No JSON/JSONB type -- must be running against old PostgreSQL
}
}
mustExec(t, conn, `create temporary table foo(
a json,
b jsonb
)`)
inputRows := [][]interface{}{
{map[string]interface{}{"foo": "bar"}, map[string]interface{}{"bar": "quz"}},
{nil, nil},
}
copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b"}, pgx.CopyFromRows(inputRows))
if err != nil {
t.Errorf("Unexpected error for CopyFrom: %v", err)
}
if int(copyCount) != len(inputRows) {
t.Errorf("Expected CopyFrom to return %d copied rows, but got %d", len(inputRows), copyCount)
}
rows, err := conn.Query(context.Background(), "select * from foo")
if err != nil {
t.Errorf("Unexpected error for Query: %v", err)
}
var outputRows [][]interface{}
for rows.Next() {
row, err := rows.Values()
if err != nil {
t.Errorf("Unexpected error for rows.Values(): %v", err)
}
outputRows = append(outputRows, row)
}
if rows.Err() != nil {
t.Errorf("Unexpected error for rows.Err(): %v", rows.Err())
}
if !reflect.DeepEqual(inputRows, outputRows) {
t.Errorf("Input rows and output rows do not equal: %v -> %v", inputRows, outputRows)
}
ensureConnValid(t, conn)
}
type clientFailSource struct {
count int
err error
}
func (cfs *clientFailSource) Next() bool {
cfs.count++
return cfs.count < 100
}
func (cfs *clientFailSource) Values() ([]interface{}, error) {
if cfs.count == 3 {
cfs.err = fmt.Errorf("client error")
return nil, cfs.err
}
return []interface{}{make([]byte, 100000)}, nil
}
func (cfs *clientFailSource) Err() error {
return cfs.err
}
func TestConnCopyFromFailServerSideMidway(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
mustExec(t, conn, `create temporary table foo(
a int4,
b varchar not null
)`)
inputRows := [][]interface{}{
{int32(1), "abc"},
{int32(2), nil}, // this row should trigger a failure
{int32(3), "def"},
}
copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b"}, pgx.CopyFromRows(inputRows))
if err == nil {
t.Errorf("Expected CopyFrom return error, but it did not")
}
if _, ok := err.(*pgconn.PgError); !ok {
t.Errorf("Expected CopyFrom return pgx.PgError, but instead it returned: %v", err)
}
if copyCount != 0 {
t.Errorf("Expected CopyFrom to return 0 copied rows, but got %d", copyCount)
}
rows, err := conn.Query(context.Background(), "select * from foo")
if err != nil {
t.Errorf("Unexpected error for Query: %v", err)
}
var outputRows [][]interface{}
for rows.Next() {
row, err := rows.Values()
if err != nil {
t.Errorf("Unexpected error for rows.Values(): %v", err)
}
outputRows = append(outputRows, row)
}
if rows.Err() != nil {
t.Errorf("Unexpected error for rows.Err(): %v", rows.Err())
}
if len(outputRows) != 0 {
t.Errorf("Expected 0 rows, but got %v", outputRows)
}
mustExec(t, conn, "truncate foo")
ensureConnValid(t, conn)
}
type failSource struct {
count int
}
func (fs *failSource) Next() bool {
time.Sleep(time.Millisecond * 100)
fs.count++
return fs.count < 100
}
func (fs *failSource) Values() ([]interface{}, error) {
if fs.count == 3 {
return []interface{}{nil}, nil
}
return []interface{}{make([]byte, 100000)}, nil
}
func (fs *failSource) Err() error {
return nil
}
func TestConnCopyFromFailServerSideMidwayAbortsWithoutWaiting(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
mustExec(t, conn, `create temporary table foo(
a bytea not null
)`)
startTime := time.Now()
copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a"}, &failSource{})
if err == nil {
t.Errorf("Expected CopyFrom return error, but it did not")
}
if _, ok := err.(*pgconn.PgError); !ok {
t.Errorf("Expected CopyFrom return pgx.PgError, but instead it returned: %v", err)
}
if copyCount != 0 {
t.Errorf("Expected CopyFrom to return 0 copied rows, but got %d", copyCount)
}
endTime := time.Now()
copyTime := endTime.Sub(startTime)
if copyTime > time.Second {
t.Errorf("Failing CopyFrom shouldn't have taken so long: %v", copyTime)
}
rows, err := conn.Query(context.Background(), "select * from foo")
if err != nil {
t.Errorf("Unexpected error for Query: %v", err)
}
var outputRows [][]interface{}
for rows.Next() {
row, err := rows.Values()
if err != nil {
t.Errorf("Unexpected error for rows.Values(): %v", err)
}
outputRows = append(outputRows, row)
}
if rows.Err() != nil {
t.Errorf("Unexpected error for rows.Err(): %v", rows.Err())
}
if len(outputRows) != 0 {
t.Errorf("Expected 0 rows, but got %v", outputRows)
}
ensureConnValid(t, conn)
}
type slowFailRaceSource struct {
count int
}
func (fs *slowFailRaceSource) Next() bool {
time.Sleep(time.Millisecond)
fs.count++
return fs.count < 1000
}
func (fs *slowFailRaceSource) Values() ([]interface{}, error) {
if fs.count == 500 {
return []interface{}{nil, nil}, nil
}
return []interface{}{1, make([]byte, 1000)}, nil
}
func (fs *slowFailRaceSource) Err() error {
return nil
}
func TestConnCopyFromSlowFailRace(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
mustExec(t, conn, `create temporary table foo(
a int not null,
b bytea not null
)`)
copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a", "b"}, &slowFailRaceSource{})
if err == nil {
t.Errorf("Expected CopyFrom return error, but it did not")
}
if _, ok := err.(*pgconn.PgError); !ok {
t.Errorf("Expected CopyFrom return pgx.PgError, but instead it returned: %v", err)
}
if copyCount != 0 {
t.Errorf("Expected CopyFrom to return 0 copied rows, but got %d", copyCount)
}
ensureConnValid(t, conn)
}
func TestConnCopyFromCopyFromSourceErrorMidway(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
mustExec(t, conn, `create temporary table foo(
a bytea not null
)`)
copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a"}, &clientFailSource{})
if err == nil {
t.Errorf("Expected CopyFrom return error, but it did not")
}
if copyCount != 0 {
t.Errorf("Expected CopyFrom to return 0 copied rows, but got %d", copyCount)
}
rows, err := conn.Query(context.Background(), "select * from foo")
if err != nil {
t.Errorf("Unexpected error for Query: %v", err)
}
var outputRows [][]interface{}
for rows.Next() {
row, err := rows.Values()
if err != nil {
t.Errorf("Unexpected error for rows.Values(): %v", err)
}
outputRows = append(outputRows, row)
}
if rows.Err() != nil {
t.Errorf("Unexpected error for rows.Err(): %v", rows.Err())
}
if len(outputRows) != 0 {
t.Errorf("Expected 0 rows, but got %v", len(outputRows))
}
ensureConnValid(t, conn)
}
type clientFinalErrSource struct {
count int
}
func (cfs *clientFinalErrSource) Next() bool {
cfs.count++
return cfs.count < 5
}
func (cfs *clientFinalErrSource) Values() ([]interface{}, error) {
return []interface{}{make([]byte, 100000)}, nil
}
func (cfs *clientFinalErrSource) Err() error {
return fmt.Errorf("final error")
}
func TestConnCopyFromCopyFromSourceErrorEnd(t *testing.T) {
t.Parallel()
conn := mustConnectString(t, os.Getenv("PGX_TEST_DATABASE"))
defer closeConn(t, conn)
mustExec(t, conn, `create temporary table foo(
a bytea not null
)`)
copyCount, err := conn.CopyFrom(context.Background(), pgx.Identifier{"foo"}, []string{"a"}, &clientFinalErrSource{})
if err == nil {
t.Errorf("Expected CopyFrom return error, but it did not")
}
if copyCount != 0 {
t.Errorf("Expected CopyFrom to return 0 copied rows, but got %d", copyCount)
}
rows, err := conn.Query(context.Background(), "select * from foo")
if err != nil {
t.Errorf("Unexpected error for Query: %v", err)
}
var outputRows [][]interface{}
for rows.Next() {
row, err := rows.Values()
if err != nil {
t.Errorf("Unexpected error for rows.Values(): %v", err)
}
outputRows = append(outputRows, row)
}
if rows.Err() != nil {
t.Errorf("Unexpected error for rows.Err(): %v", rows.Err())
}
if len(outputRows) != 0 {
t.Errorf("Expected 0 rows, but got %v", outputRows)
}
ensureConnValid(t, conn)
}
|
[
"\"PGX_TEST_DATABASE\"",
"\"PGX_TEST_DATABASE\"",
"\"PGX_TEST_DATABASE\"",
"\"PGX_TEST_DATABASE\"",
"\"PGX_TEST_DATABASE\"",
"\"PGX_TEST_DATABASE\"",
"\"PGX_TEST_DATABASE\"",
"\"PGX_TEST_DATABASE\"",
"\"PGX_TEST_DATABASE\"",
"\"PGX_TEST_DATABASE\""
] |
[] |
[
"PGX_TEST_DATABASE"
] |
[]
|
["PGX_TEST_DATABASE"]
|
go
| 1 | 0 | |
pkg/cmd/roachtest/test_runner.go
|
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package main
import (
"context"
"fmt"
"io"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/cockroachdb/cockroach/pkg/cmd/internal/issues"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/quotapool"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/version"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/petermattis/goid"
)
// testRunner runs tests.
type testRunner struct {
// buildVersion is the version of the Cockroach binary that tests will run against.
buildVersion version.Version
config struct {
// skipClusterValidationOnAttach skips validation on existing clusters that
// the registry uses for running tests.
skipClusterValidationOnAttach bool
// skipClusterStopOnAttach skips stopping existing clusters that
// the registry uses for running tests. It implies skipClusterWipeOnAttach.
skipClusterStopOnAttach bool
skipClusterWipeOnAttach bool
}
status struct {
syncutil.Mutex
running map[*test]struct{}
pass map[*test]struct{}
fail map[*test]struct{}
skip map[*test]struct{}
}
// cr keeps track of all live clusters.
cr *clusterRegistry
workersMu struct {
syncutil.Mutex
// workers is a map from worker name to information about each worker currently running tests.
workers map[string]*workerStatus
}
// work maintains the remaining tests to run.
work *workPool
completedTestsMu struct {
syncutil.Mutex
// completed maintains information on all completed test runs.
completed []completedTestInfo
}
}
// newTestRunner constructs a testRunner.
//
// cr: The cluster registry with which all clusters will be registered. The
// caller provides this as the caller needs to be able to shut clusters down
// on Ctrl+C.
// buildVersion: The version of the Cockroach binary against which tests will run.
func newTestRunner(cr *clusterRegistry, buildVersion version.Version) *testRunner {
r := &testRunner{
cr: cr,
buildVersion: buildVersion,
}
r.config.skipClusterWipeOnAttach = !clusterWipe
r.workersMu.workers = make(map[string]*workerStatus)
return r
}
// clustersOpt groups options for the clusters to be used by the tests.
type clustersOpt struct {
// The type of cluster to use. If localCluster, then no other fields can be
// set.
typ clusterType
// If set, all the tests will run against this roachprod cluster.
clusterName string
// If set, all the clusters will use this ID as part of their name. When
// roachtests is invoked by TeamCity, this will be the build id.
clusterID string
// The name of the user running the tests. This will be part of cluster names.
user string
// cpuQuota specifies how many CPUs can be used concurrently by the roachprod
// clusters. While there's no quota available for creating a new cluster, the
// test runner will wait for other tests to finish and their cluster to be
// destroyed (or reused). Note that this limit is global, not per zone.
cpuQuota int
// If set, clusters will not be wiped or destroyed when a test using the
// respective cluster fails. These cluster will linger around and they'll
// continue counting towards the cpuQuota.
keepClustersOnTestFailure bool
}
func (c clustersOpt) validate() error {
if c.typ == localCluster {
if c.clusterName != "" {
return errors.New("clusterName cannot be set when typ=localCluster")
}
if c.clusterID != "" {
return errors.New("clusterID cannot be set when typ=localCluster")
}
}
return nil
}
// Run runs tests.
//
// Args:
// tests: The tests to run.
// count: How many times to run each test selected by filter.
// parallelism: How many workers to use for running tests. Tests are run
// locally (although generally they run against remote roachprod clusters).
// parallelism bounds the maximum number of tests that run concurrently. Note
// that the concurrency is also affected by cpuQuota.
// clusterOpt: Options for the clusters to use by tests.
// lopt: Options for logging.
func (r *testRunner) Run(
ctx context.Context,
tests []testSpec,
count int,
parallelism int,
clustersOpt clustersOpt,
artifactsDir string,
lopt loggingOpt,
) error {
// Validate options.
if len(tests) == 0 {
return fmt.Errorf("no test matched filters")
}
if err := clustersOpt.validate(); err != nil {
return err
}
if parallelism != 1 {
if clustersOpt.clusterName != "" {
return fmt.Errorf("--cluster incompatible with --parallelism. Use --parallelism=1")
}
if clustersOpt.typ == localCluster {
return fmt.Errorf("--local incompatible with --parallelism. Use --parallelism=1")
}
}
if name := clustersOpt.clusterName; name != "" {
// Since we were given a cluster, check that all tests we have to run have compatible specs.
// We should also check against the spec of the cluster, but we don't
// currently have a way of doing that; we're relying on the fact that attaching to the cluster
// will fail if the cluster is incompatible.
spec := tests[0].Cluster
spec.Lifetime = 0
for i := 1; i < len(tests); i++ {
spec2 := tests[i].Cluster
spec2.Lifetime = 0
if spec != spec2 {
return errors.Errorf("cluster specified but found tests "+
"with incompatible specs: %s (%s) - %s (%s)",
tests[0].Name, spec, tests[i].Name, spec2,
)
}
}
}
var numConcurrentClusterCreations int
if cloud == "aws" {
// AWS has ridiculous API calls limits, so we're going to create one cluster
// at a time. Internally, roachprod has throttling for the calls required to
// create a single cluster.
numConcurrentClusterCreations = 1
} else {
numConcurrentClusterCreations = 1000
}
clusterFactory := newClusterFactory(
clustersOpt.user, clustersOpt.clusterID, lopt.artifactsDir, r.cr, numConcurrentClusterCreations)
// allocateCluster will be used by workers to create new clusters (or to attach
// to an existing one).
allocateCluster := func(
ctx context.Context,
t testSpec,
alloc *quotapool.IntAlloc,
artifactsDir string,
wStatus *workerStatus,
) (*cluster, error) {
wStatus.SetStatus("creating cluster")
defer wStatus.SetStatus("")
lopt.l.PrintfCtx(ctx, "Creating new cluster for test %s: %s", t.Name, t.Cluster)
existingClusterName := clustersOpt.clusterName
if existingClusterName != "" {
// Logs for attaching to a cluster go to a dedicated log file.
logPath := filepath.Join(artifactsDir, runnerLogsDir, "cluster-create", existingClusterName+".log")
clusterL, err := rootLogger(logPath, lopt.tee)
defer clusterL.close()
if err != nil {
return nil, err
}
opt := attachOpt{
skipValidation: r.config.skipClusterValidationOnAttach,
skipStop: r.config.skipClusterStopOnAttach,
skipWipe: r.config.skipClusterWipeOnAttach,
}
return attachToExistingCluster(ctx, existingClusterName, clusterL, t.Cluster, opt, r.cr)
}
cfg := clusterConfig{
spec: t.Cluster,
artifactsDir: artifactsDir,
localCluster: clustersOpt.typ == localCluster,
alloc: alloc,
}
return clusterFactory.newCluster(ctx, cfg, wStatus.SetStatus, lopt.tee)
}
// Seed the default rand source so that different runs get different cluster
// IDs.
rand.Seed(timeutil.Now().UnixNano())
n := len(tests)
if n*count < parallelism {
// Don't spin up more workers than necessary.
parallelism = n * count
}
r.status.running = make(map[*test]struct{})
r.status.pass = make(map[*test]struct{})
r.status.fail = make(map[*test]struct{})
r.status.skip = make(map[*test]struct{})
r.work = newWorkPool(tests, count)
stopper := stop.NewStopper()
errs := &workerErrors{}
qp := quotapool.NewIntPool("cloud cpu", uint64(clustersOpt.cpuQuota))
l := lopt.l
var wg sync.WaitGroup
for i := 0; i < parallelism; i++ {
i := i // Copy for closure.
wg.Add(1)
stopper.RunWorker(ctx, func(ctx context.Context) {
defer wg.Done()
if err := r.runWorker(
ctx, fmt.Sprintf("w%d", i) /* name */, r.work, qp,
stopper.ShouldQuiesce(),
clustersOpt.keepClustersOnTestFailure,
lopt.artifactsDir, lopt.runnerLogPath, lopt.tee, lopt.stdout,
allocateCluster,
l,
); err != nil {
// A worker returned an error. Let's shut down.
msg := fmt.Sprintf("Worker %d returned with error. Quiescing. Error: %+v", i, err)
shout(ctx, l, lopt.stdout, msg)
errs.AddErr(err)
// Quiesce the stopper. This will cause all workers to not pick up more
// tests after finishing the currently running one.
stopper.Quiesce(ctx)
// Interrupt everybody waiting for resources.
if qp != nil {
qp.Close(msg)
}
}
})
}
// Wait for all the workers to finish.
wg.Wait()
r.cr.destroyAllClusters(ctx, l)
if errs.Err() != nil {
shout(ctx, l, lopt.stdout, "FAIL (err: %s)", errs.Err())
return errs.Err()
}
passFailLine := r.generateReport()
shout(ctx, l, lopt.stdout, passFailLine)
if len(r.status.fail) > 0 {
return fmt.Errorf("some tests failed")
}
return nil
}
type clusterAllocatorFn func(
ctx context.Context,
t testSpec,
alloc *quotapool.IntAlloc,
artifactsDir string,
wStatus *workerStatus,
) (*cluster, error)
// runWorker runs tests in a loop until work is exhausted.
//
// Errors are returned in exceptional circumstances, like when a cluster failed
// to be created or when a test timed out and failed to react to its
// cancellation. Upon return, an attempt is performed to destroy the cluster used
// by this worker. If an error is returned, we might have "leaked" cpu quota
// because the cluster destruction might have failed but we've still released
// the quota. Also, we might have "leaked" a test goroutine (in the test
// nonresponsive to timeout case) which might still be running and doing
// arbitrary things to the cluster it was using.
//
// Args:
// name: The worker's name, to be used as a prefix for log messages.
// artifactsRootDir: The artifacts dir. Each test's logs are going to be under a
// run_<n> dir. If empty, test log files will not be created.
// testRunnerLogPath: The path to the test runner's log. It will be copied to
// failing tests' artifacts dir if running under TeamCity.
// stdout: The Writer to use for messages that need to go to stdout (e.g. the
// "=== RUN" and "--- FAIL" lines).
// teeOpt: The teeing option for future test loggers.
// l: The logger to use for more verbose messages.
func (r *testRunner) runWorker(
ctx context.Context,
name string,
work *workPool,
qp *quotapool.IntPool,
interrupt <-chan struct{},
debug bool,
artifactsRootDir string,
testRunnerLogPath string,
teeOpt teeOptType,
stdout io.Writer,
allocateCluster clusterAllocatorFn,
l *logger,
) error {
ctx = logtags.AddTag(ctx, name, nil /* value */)
wStatus := r.addWorker(ctx, name)
defer func() {
r.removeWorker(ctx, name)
}()
var c *cluster // The cluster currently being used.
var err error
// When this method returns we'll destroy the cluster we had at the time.
// Note that, if debug was set, c has been set to nil.
defer func() {
wStatus.SetTest(nil /* test */, testToRunRes{noWork: true})
wStatus.SetStatus("worker done")
wStatus.SetCluster(nil)
if c == nil {
l.PrintfCtx(ctx, "Worker exiting; no cluster to destroy.")
return
}
doDestroy := ctx.Err() == nil
if doDestroy {
l.PrintfCtx(ctx, "Worker exiting; destroying cluster.")
c.Destroy(context.Background(), closeLogger, l)
} else {
l.PrintfCtx(ctx, "Worker exiting with canceled ctx. Not destroying cluster.")
}
}()
// Loop until there's no more work in the pool, we get interrupted, or an
// error occurs.
for {
select {
case <-interrupt:
l.ErrorfCtx(ctx, "worker detected interruption")
return errors.Errorf("interrupted")
default:
if ctx.Err() != nil {
// The context has been canceled. No need to continue.
return errors.Wrap(ctx.Err(), "worker ctx done")
}
}
if c != nil {
if _, ok := c.spec.ReusePolicy.(reusePolicyNone); ok {
wStatus.SetStatus("destroying cluster")
// We use a context that can't be canceled for the Destroy().
c.Destroy(context.Background(), closeLogger, l)
c = nil
}
}
var testToRun testToRunRes
wStatus.SetTest(nil /* test */, testToRunRes{})
wStatus.SetStatus("getting work")
testToRun, c, err = r.getWork(
ctx, work, qp, c, interrupt, l,
getWorkCallbacks{
createCluster: func(ctx context.Context, ttr testToRunRes) (*cluster, error) {
wStatus.SetTest(nil /* test */, ttr)
return allocateCluster(ctx, ttr.spec, ttr.alloc, artifactsRootDir, wStatus)
},
onDestroy: func() {
wStatus.SetCluster(nil)
},
})
if err != nil || testToRun.noWork {
return err
}
c.status("running test")
// Prepare the test's logger.
logPath := ""
var artifactsDir string
var artifactsSpec string
if artifactsRootDir != "" {
escapedTestName := teamCityNameEscape(testToRun.spec.Name)
runSuffix := "run_" + strconv.Itoa(testToRun.runNum)
base := filepath.Join(artifactsRootDir, escapedTestName)
artifactsDir = filepath.Join(base, runSuffix)
logPath = filepath.Join(artifactsDir, "test.log")
// Map artifacts/TestFoo/** => TestFoo/**, i.e. collect the artifacts
// for this test exactly as they are laid out on disk (when the time
// comes).
artifactsSpec = fmt.Sprintf("%s/** => %s", base, escapedTestName)
}
testL, err := rootLogger(logPath, teeOpt)
if err != nil {
return err
}
t := &test{
spec: &testToRun.spec,
buildVersion: r.buildVersion,
artifactsDir: artifactsDir,
artifactsSpec: artifactsSpec,
l: testL,
}
// Tell the cluster that, from now on, it will be run "on behalf of this
// test".
c.setTest(t)
wStatus.SetCluster(c)
wStatus.SetTest(t, testToRun)
wStatus.SetStatus("running test")
// Now run the test.
l.PrintfCtx(ctx, "starting test: %s:%d", testToRun.spec.Name, testToRun.runNum)
var success bool
success, err = r.runTest(ctx, t, testToRun.runNum, c, testRunnerLogPath, stdout, testL)
if err != nil {
shout(ctx, l, stdout, "test returned error: %s: %s", t.Name(), err)
// Mark the test as failed if it isn't already.
if !t.Failed() {
t.printAndFail(0 /* skip */, err)
}
} else {
msg := "test passed"
if !success {
msg = fmt.Sprintf("test failed: %s (run %d)", t.Name(), testToRun.runNum)
}
l.PrintfCtx(ctx, msg)
}
testL.close()
if err != nil || t.Failed() {
failureMsg := fmt.Sprintf("%s (%d) - ", testToRun.spec.Name, testToRun.runNum)
if err != nil {
failureMsg += fmt.Sprintf("%+v", err)
} else {
failureMsg += t.FailureMsg()
}
if debug {
// Save the cluster for future debugging.
c.Save(ctx, failureMsg, l)
// Continue with a fresh cluster.
c = nil
} else {
// On any test failure or error, we destroy the cluster. We could be
// more selective, but this sounds safer.
l.PrintfCtx(ctx, "destroying cluster %s because: %s", c, failureMsg)
c.Destroy(context.Background(), closeLogger, l)
c = nil
}
if err != nil {
return err
}
} else {
// Upon success fetch the perf artifacts from the remote hosts.
getPerfArtifacts(ctx, l, c, t)
}
}
}
// getPerfArtifacts retrieves the perf artifacts for the test.
// If there's an error, oh well, don't do anything rash like fail a test
// which already passed.
func getPerfArtifacts(ctx context.Context, l *logger, c *cluster, t *test) {
g := ctxgroup.WithContext(ctx)
fetchNode := func(node int) func(context.Context) error {
return func(ctx context.Context) error {
testCmd := `'PERF_ARTIFACTS="` + perfArtifactsDir + `"
if [[ -d "${PERF_ARTIFACTS}" ]]; then
echo true
elif [[ -e "${PERF_ARTIFACTS}" ]]; then
ls -la "${PERF_ARTIFACTS}"
exit 1
else
echo false
fi'`
out, err := c.RunWithBuffer(ctx, l, c.Node(node), "bash", "-c", testCmd)
if err != nil {
return errors.Wrapf(err, "failed to check for perf artifacts: %v", string(out))
}
switch out := strings.TrimSpace(string(out)); out {
case "true":
dst := fmt.Sprintf("%s/%d.%s", t.artifactsDir, node, perfArtifactsDir)
return c.Get(ctx, l, perfArtifactsDir, dst, c.Node(node))
case "false":
l.PrintfCtx(ctx, "no perf artifacts exist on node %v", c.Node(node))
return nil
default:
return errors.Errorf("unexpected output when checking for perf artifacts: %s", out)
}
}
}
for _, i := range c.All() {
g.GoCtx(fetchNode(i))
}
if err := g.Wait(); err != nil {
l.PrintfCtx(ctx, "failed to get perf artifacts: %v", err)
}
}
func allStacks() []byte {
// Collect up to 5mb worth of stacks.
b := make([]byte, 5*(1<<20))
return b[:runtime.Stack(b, true /* all */)]
}
// An error is returned if the test is still running (on another goroutine) when
// this returns. This happens when the test doesn't respond to cancellation.
// Returns true if the test is considered to have passed, false otherwise.
//
// Args:
// c: The cluster on which the test will run. runTest() does not wipe or destroy
// the cluster.
// testRunnerLogPath: The path to the test runner's log. It will be copied to
// the test's artifacts dir if the test fails and we're running under
// TeamCity.
func (r *testRunner) runTest(
ctx context.Context,
t *test,
runNum int,
c *cluster,
testRunnerLogPath string,
stdout io.Writer,
l *logger,
) (bool, error) {
if t.spec.Skip != "" {
return false, fmt.Errorf("can't run skipped test: %s: %s", t.Name(), t.spec.Skip)
}
if teamCity {
shout(ctx, l, stdout, "##teamcity[testStarted name='%s' flowId='%s']", t.Name(), t.Name())
} else {
shout(ctx, l, stdout, "=== RUN %s", t.Name())
}
r.status.Lock()
r.status.running[t] = struct{}{}
r.status.Unlock()
t.runner = callerName()
t.runnerID = goid.Get()
defer func() {
t.end = timeutil.Now()
// We only have to record panics if the panic'd value is not the sentinel
// produced by t.Fatal*().
if err := recover(); err != nil && err != errTestFatal {
t.mu.Lock()
t.mu.failed = true
t.mu.output = append(t.mu.output, t.decorate(0 /* skip */, fmt.Sprint(err))...)
t.mu.Unlock()
}
t.mu.Lock()
t.mu.done = true
t.mu.Unlock()
durationStr := fmt.Sprintf("%.2fs", t.duration().Seconds())
if t.Failed() {
t.mu.Lock()
output := fmt.Sprintf("test artifacts and logs in: %s\n", t.ArtifactsDir()) + string(t.mu.output)
t.mu.Unlock()
if teamCity {
shout(ctx, l, stdout, "##teamcity[testFailed name='%s' details='%s' flowId='%s']",
t.Name(), teamCityEscape(output), t.Name(),
)
// Copy a snapshot of the testrunner's log to the test's artifacts dir
// so that we collect it below.
cp := exec.Command("cp", testRunnerLogPath, t.artifactsDir)
if err := cp.Run(); err != nil {
l.ErrorfCtx(ctx, "failed to copy test runner's logs to test artifacts: %s", err)
}
}
shout(ctx, l, stdout, "--- FAIL: %s (%s)\n%s", t.Name(), durationStr, output)
// NB: check NodeCount > 0 to avoid posting issues from this pkg's unit tests.
if issues.CanPost() && t.spec.Run != nil && t.spec.Cluster.NodeCount > 0 {
projectColumnID := 0
if info, ok := roachtestOwners[t.spec.Owner]; ok {
projectColumnID = info.TriageColumnID
}
branch := "<unknown branch>"
if b := os.Getenv("TC_BUILD_BRANCH"); b != "" {
branch = b
}
msg := fmt.Sprintf("The test failed on branch=%s, cloud=%s:\n%s",
branch, cloud, output)
artifacts := fmt.Sprintf("/%s", t.Name())
req := issues.PostRequest{
// TODO(tbg): actually use this as a template.
TitleTemplate: fmt.Sprintf("roachtest: %s failed", t.Name()),
// TODO(tbg): make a template better adapted to roachtest.
BodyTemplate: issues.UnitTestFailureBody,
PackageName: "roachtest",
TestName: t.Name(),
Message: msg,
Artifacts: artifacts,
// Issues posted from roachtest are identifiable as such and
// they are also release blockers (this label may be removed
// by a human upon closer investigation).
ExtraLabels: []string{"O-roachtest", "release-blocker"},
ProjectColumnID: projectColumnID,
}
if err := issues.Post(
context.Background(),
req,
); err != nil {
shout(ctx, l, stdout, "failed to post issue: %s", err)
}
}
} else {
shout(ctx, l, stdout, "--- PASS: %s (%s)", t.Name(), durationStr)
// If `##teamcity[testFailed ...]` is not present before `##teamCity[testFinished ...]`,
// TeamCity regards the test as successful.
}
if teamCity {
shout(ctx, l, stdout, "##teamcity[testFinished name='%s' flowId='%s']", t.Name(), t.Name())
if t.artifactsSpec != "" {
// Tell TeamCity to collect this test's artifacts now. The TC job
// also collects the artifacts directory wholesale at the end, but
// here we make sure that the artifacts for any test that has already
// finished are available in the UI even before the job as a whole
// has completed. We're using the exact same destination to avoid
// duplication of any of the artifacts.
shout(ctx, l, stdout, "##teamcity[publishArtifacts '%s']", t.artifactsSpec)
}
}
r.recordTestFinish(completedTestInfo{
test: t.Name(),
run: runNum,
start: t.start,
end: t.end,
pass: !t.Failed(),
failure: t.FailureMsg(),
})
r.status.Lock()
delete(r.status.running, t)
// Only include tests with a Run function in the summary output.
if t.spec.Run != nil {
if t.Failed() {
r.status.fail[t] = struct{}{}
} else if t.spec.Skip == "" {
r.status.pass[t] = struct{}{}
} else {
r.status.skip[t] = struct{}{}
}
}
r.status.Unlock()
}()
t.start = timeutil.Now()
timeout := 10 * time.Hour
if t.spec.Timeout != 0 {
timeout = t.spec.Timeout
}
// Make sure the cluster has enough life left for the test plus enough headroom
// after the test finishes so that the next test can be selected. If it
// doesn't, extend it.
minExp := timeutil.Now().Add(timeout + time.Hour)
if c.expiration.Before(minExp) {
extend := minExp.Sub(c.expiration)
l.PrintfCtx(ctx, "cluster needs to survive until %s, but has expiration: %s. Extending.",
minExp, c.expiration)
if err := c.Extend(ctx, extend, l); err != nil {
t.printfAndFail(0 /* skip */, "failed to extend cluster: %s", err)
return false, nil
}
}
runCtx, cancel := context.WithCancel(ctx)
defer cancel()
t.mu.Lock()
// t.Fatal() will cancel this context.
t.mu.cancel = cancel
t.mu.Unlock()
// We run the actual test in a different goroutine because it might call
// t.Fatal() which kills the goroutine, and also because we want to enforce a
// timeout.
success := false
done := make(chan struct{})
go func() {
defer close(done) // closed only after we've grabbed the debug info below
// This is the call to actually run the test.
defer func() {
// We only have to record panics if the panic'd value is not the sentinel
// produced by t.Fatal*().
if r := recover(); r != nil && r != errTestFatal {
// TODO(andreimatei): prevent the cluster from being reused.
t.Fatalf("test panicked: %v", r)
}
}()
t.spec.Run(runCtx, t, c)
}()
teardownL, err := c.l.ChildLogger("teardown", quietStderr, quietStdout)
if err != nil {
return false, err
}
select {
case <-done:
s := "success"
if t.Failed() {
s = "failure"
}
c.l.Printf("tearing down after %s; see teardown.log", s)
l, c.l, t.l = teardownL, teardownL, teardownL
case <-time.After(timeout):
c.l.Printf("tearing down after timeout; see teardown.log")
l, c.l, t.l = teardownL, teardownL, teardownL
// Timeouts are often opaque. Improve our changes by dumping the stack
// so that at least we can piece together what the test is trying to
// do at this very moment.
// In large roachtest runs, this will dump everyone else's stack as well,
// but this is just hard to avoid. Moving to a worker model in which
// each roachtest is spawned off as a separate process would address
// this at the expense of ease of communication between the runner and
// the test.
//
// Do this before we cancel the context, which might (hopefully) unblock
// the test. We want to see where it got stuck.
const stacksFile = "__stacks"
if cl, err := t.l.ChildLogger(stacksFile, quietStderr, quietStdout); err == nil {
cl.PrintfCtx(ctx, "all stacks:\n\n%s\n", allStacks())
t.l.PrintfCtx(ctx, "dumped stacks to %s", stacksFile)
}
// Now kill anything going on in this cluster while collecting stacks
// to the logs, to get the server side of the hang.
//
// TODO(tbg): send --sig=3 followed by a hard kill after we've fixed
// https://github.com/cockroachdb/cockroach/issues/45875.
// Signal 11 will dump stacks, but it might be confusing to folks
// who debug from the artifacts only.
//
// Don't use surrounding context, which are likely already canceled.
if nodes := c.All(); len(nodes) > 0 { // avoid tests
innerCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_ = c.StopE(innerCtx, c.All(), stopArgs("--sig=11"))
cancel()
}
// Mark the test as failed (which will also cancel its context). Then
// we'll wait up to 5 minutes in the hope that the test reacts either to
// the ctx cancelation or to the fact that it was marked as failed (and
// all processes nuked out from under it).
// If that happens, great - we return normally and so the cluster can be
// reused. It the test does not react to anything, then we return an
// error, which will cause the caller to stop everything and destroy
// this cluster (as well as all the others). The cluster cannot be
// reused since we have a runaway test goroutine that's presumably going
// to continue using the cluster.
t.printfAndFail(0 /* skip */, "test timed out (%s)", timeout)
select {
case <-done:
if success {
panic("expected success=false after a timeout")
}
case <-time.After(5 * time.Minute):
// We really shouldn't get here unless the test code somehow managed
// to deadlock without blocking on anything remote - since we killed
// everything.
const msg = "test timed out and afterwards failed to respond to cancelation"
t.l.PrintfCtx(ctx, msg)
r.collectClusterLogs(ctx, c, t.l)
// We return an error here because the test goroutine is still running, so
// we want to alert the caller of this unusual situation.
return false, errors.New(msg)
}
}
// Detect dead nodes in an inner defer. Note that this will call
// t.printfAndFail() when appropriate, which will cause the code below to
// enter the t.Failed() branch.
c.FailOnDeadNodes(ctx, t)
if !t.Failed() {
// Detect replica divergence (i.e. ranges in which replicas have arrived
// at the same log position with different states).
//
// We avoid trying to do this when t.Failed() (and in particular when there
// are dead nodes) because for reasons @tbg does not understand this gets
// stuck occasionally, which really ruins the roachtest run. The method
// below already uses a ctx timeout and SQL statement_timeout, but it does
// not seem to be enough.
//
// TODO(testinfra): figure out why this can still get stuck despite the
// above.
c.FailOnReplicaDivergence(ctx, t)
}
if t.Failed() {
r.collectClusterLogs(ctx, c, t.l)
return false, nil
}
return true, nil
}
func (r *testRunner) collectClusterLogs(ctx context.Context, c *cluster, l *logger) {
// NB: fetch the logs even when we have a debug zip because
// debug zip can't ever get the logs for down nodes.
// We only save artifacts for failed tests in CI, so this
// duplication is acceptable.
// NB: fetch the logs *first* in case one of the other steps
// below has problems. For example, `debug zip` is known to
// hang sometimes at the time of writing, see:
// https://github.com/cockroachdb/cockroach/issues/39620
l.PrintfCtx(ctx, "collecting cluster logs")
if err := c.FetchLogs(ctx); err != nil {
l.Printf("failed to download logs: %s", err)
}
if err := c.FetchDmesg(ctx); err != nil {
l.Printf("failed to fetch dmesg: %s", err)
}
if err := c.FetchJournalctl(ctx); err != nil {
l.Printf("failed to fetch journalctl: %s", err)
}
if err := c.FetchCores(ctx); err != nil {
l.Printf("failed to fetch cores: %s", err)
}
if err := c.CopyRoachprodState(ctx); err != nil {
l.Printf("failed to copy roachprod state: %s", err)
}
if err := c.FetchDiskUsage(ctx); err != nil {
l.Printf("failed to fetch disk uage summary: %s", err)
}
if err := c.FetchDebugZip(ctx); err != nil {
l.Printf("failed to collect zip: %s", err)
}
}
func callerName() string {
// Make room for the skip PC.
var pc [2]uintptr
n := runtime.Callers(2, pc[:]) // runtime.Callers + callerName
if n == 0 {
panic("zero callers found")
}
frames := runtime.CallersFrames(pc[:n])
frame, _ := frames.Next()
return frame.Function
}
// generateReport produces the final pass/fail line and produces a slack report
// if configured.
func (r *testRunner) generateReport() string {
r.status.Lock()
defer r.status.Unlock()
postSlackReport(r.status.pass, r.status.fail, r.status.skip)
fails := len(r.status.fail)
var msg string
if fails > 0 {
msg = fmt.Sprintf("FAIL (%d fails)\n", fails)
} else {
msg = "PASS"
}
return msg
}
type getWorkCallbacks struct {
createCluster func(context.Context, testToRunRes) (*cluster, error)
onDestroy func()
}
// getWork selects the next test to run and creates a suitable cluster for it if
// need be. If a new cluster needs to be created, the method blocks until there
// are enough resources available to run it.
// getWork takes in a cluster; if not nil, tests that can reuse it are
// preferred. If a test that can reuse it is not found (or if there's no more
// work), the cluster is destroyed (and so its resources are released).
//
// If the cluster is to be reused, getWork() wipes it.
func (r *testRunner) getWork(
ctx context.Context,
work *workPool,
qp *quotapool.IntPool,
c *cluster,
interrupt <-chan struct{},
l *logger,
callbacks getWorkCallbacks,
) (testToRunRes, *cluster, error) {
select {
case <-interrupt:
return testToRunRes{}, nil, fmt.Errorf("interrupted")
default:
}
testToRun, err := work.getTestToRun(ctx, c, qp, r.cr, callbacks.onDestroy, l)
if err != nil {
return testToRunRes{}, nil, err
}
if !testToRun.noWork {
l.PrintfCtx(ctx, "Selected test: %s run: %d.", testToRun.spec.Name, testToRun.runNum)
}
// Are we done?
if testToRun.noWork {
return testToRun, nil, nil
}
// Create a cluster, if we no longer have one.
if testToRun.canReuseCluster {
l.PrintfCtx(ctx, "Using existing cluster: %s. Wiping", c.name)
if err := c.WipeE(ctx, l); err != nil {
return testToRunRes{}, nil, err
}
if err := c.RunL(ctx, l, c.All(), "rm -rf "+perfArtifactsDir); err != nil {
return testToRunRes{}, nil, errors.Wrapf(err, "failed to remove perf artifacts dir")
}
// Overwrite the spec of the cluster with the one coming from the test. In
// particular, this overwrites the reuse policy to reflect what the test
// intends to do with it.
c.spec = testToRun.spec.Cluster
} else {
var err error
c, err = callbacks.createCluster(ctx, testToRun)
if err != nil {
return testToRunRes{}, nil, err
}
}
return testToRun, c, nil
}
// addWorker updates the bookkeeping for one more worker.
func (r *testRunner) addWorker(ctx context.Context, name string) *workerStatus {
r.workersMu.Lock()
defer r.workersMu.Unlock()
w := &workerStatus{name: name}
if _, ok := r.workersMu.workers[name]; ok {
log.Fatalf(ctx, "worker %q already exists", name)
}
r.workersMu.workers[name] = w
return w
}
// removeWorker deletes the bookkepping for a worker that has finished running.
func (r *testRunner) removeWorker(ctx context.Context, name string) {
r.workersMu.Lock()
delete(r.workersMu.workers, name)
r.workersMu.Unlock()
}
// runHTTPServer starts a server running in the background.
//
// httpPort: The port on which to serve the web interface. Pass 0 for allocating
// a port automatically (which will be printed to stdout).
func (r *testRunner) runHTTPServer(httpPort int, stdout io.Writer) error {
http.HandleFunc("/", r.serveHTTP)
// Run an http server in the background.
// We handle the case where httpPort is 0, which means we automatically
// allocate a port.
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", httpPort))
if err != nil {
return err
}
httpPort = listener.Addr().(*net.TCPAddr).Port
go func() {
if err := http.Serve(listener, nil /* handler */); err != nil {
panic(err)
}
}()
fmt.Fprintf(stdout, "HTTP server listening on all network interfaces, port %d.\n", httpPort)
return nil
}
// serveHTTP is the handler for the test runner's web server.
func (r *testRunner) serveHTTP(wr http.ResponseWriter, req *http.Request) {
fmt.Fprintf(wr, "<html><body>")
fmt.Fprintf(wr, "<a href='debug/pprof'>pprof</a>")
fmt.Fprintf(wr, "<p>")
// Print the workers report.
fmt.Fprintf(wr, "<h2>Workers:</h2>")
fmt.Fprintf(wr, `<table border='1'>
<tr><th>Worker</th>
<th>Worker Status</th>
<th>Test</th>
<th>Cluster</th>
<th>Cluster reused</th>
<th>Test Status</th>
</tr>`)
r.workersMu.Lock()
workers := make([]*workerStatus, len(r.workersMu.workers))
i := 0
for _, w := range r.workersMu.workers {
workers[i] = w
i++
}
r.workersMu.Unlock()
sort.Slice(workers, func(i int, j int) bool {
l := workers[i]
r := workers[j]
return strings.Compare(l.name, r.name) < 0
})
for _, w := range workers {
var testName string
ttr := w.TestToRun()
clusterReused := ""
if ttr.noWork {
testName = "done"
} else if ttr.spec.Name == "" {
testName = "N/A"
} else {
testName = fmt.Sprintf("%s (run %d)", ttr.spec.Name, ttr.runNum)
if ttr.canReuseCluster {
clusterReused = "yes"
} else {
clusterReused = "no"
}
}
var clusterName string
if w.Cluster() != nil {
clusterName = w.Cluster().name
}
t := w.Test()
testStatus := "N/A"
if t != nil {
testStatus = t.GetStatus()
}
fmt.Fprintf(wr, "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n",
w.name, w.Status(), testName, clusterName, clusterReused, testStatus)
}
fmt.Fprintf(wr, "</table>")
// Print the finished tests report.
fmt.Fprintf(wr, "<p>")
fmt.Fprintf(wr, "<h2>Finished tests:</h2>")
fmt.Fprintf(wr, `<table border='1'>
<tr><th>Test</th>
<th>Status</th>
<th>Duration</th>
</tr>`)
for _, t := range r.getCompletedTests() {
name := fmt.Sprintf("%s (run %d)", t.test, t.run)
status := "PASS"
if !t.pass {
status = "FAIL " + t.failure
}
duration := fmt.Sprintf("%s (%s - %s)", t.end.Sub(t.start), t.start, t.end)
fmt.Fprintf(wr, "<tr><td>%s</td><td>%s</td><td>%s</td><tr/>", name, status, duration)
}
fmt.Fprintf(wr, "</table>")
// Print the saved clusters report.
fmt.Fprintf(wr, "<p>")
fmt.Fprintf(wr, "<h2>Clusters left alive for further debugging "+
"(if --debug was specified):</h2>")
fmt.Fprintf(wr, `<table border='1'>
<tr><th>Cluster</th>
<th>Test</th>
</tr>`)
for _, c := range r.cr.savedClusters() {
fmt.Fprintf(wr, "<tr><td>%s</td><td>%s</td><tr/>", c.name, c.savedMsg)
}
fmt.Fprintf(wr, "</table>")
fmt.Fprintf(wr, "<p>")
fmt.Fprintf(wr, "<h2>Tests left:</h2>")
fmt.Fprintf(wr, `<table border='1'>
<tr><th>Test</th>
<th>Runs</th>
</tr>`)
for _, t := range r.work.workRemaining() {
fmt.Fprintf(wr, "<tr><td>%s</td><td>%d</td><tr/>", t.spec.Name, t.count)
}
fmt.Fprintf(wr, "</body></html>")
}
// recordTestFinish updated bookkeeping when a test finishes.
func (r *testRunner) recordTestFinish(info completedTestInfo) {
r.completedTestsMu.Lock()
r.completedTestsMu.completed = append(r.completedTestsMu.completed, info)
r.completedTestsMu.Unlock()
}
// getCompletedTests returns info on all tests that finished running.
func (r *testRunner) getCompletedTests() []completedTestInfo {
r.completedTestsMu.Lock()
defer r.completedTestsMu.Unlock()
res := make([]completedTestInfo, len(r.completedTestsMu.completed))
copy(res, r.completedTestsMu.completed)
return res
}
// completedTestInfo represents information on a completed test run.
type completedTestInfo struct {
test string
run int
start time.Time
end time.Time
pass bool
failure string
}
// PredecessorVersion returns a recent predecessor of the build version (i.e.
// the build tag of the main binary). For example, if the running binary is from
// the master branch prior to releasing 19.2.0, this will return a recent
// (ideally though not necessarily the latest) 19.1 patch release.
func PredecessorVersion(buildVersion version.Version) (string, error) {
if buildVersion == (version.Version{}) {
return "", errors.Errorf("buildVersion not set")
}
buildVersionMajorMinor := fmt.Sprintf("%d.%d", buildVersion.Major(), buildVersion.Minor())
// NB: you can update the values in this map to point at newer patch
// releases. You will need to run acceptance/version-upgrade with the
// checkpoint option enabled to create the missing store directory fixture
// (see runVersionUpgrade). The same is true for adding a new key to this
// map.
verMap := map[string]string{
"20.2": "20.1.7",
"20.1": "19.2.11",
"19.2": "19.1.11",
"19.1": "2.1.9",
"2.2": "2.1.9",
"2.1": "2.0.7",
}
v, ok := verMap[buildVersionMajorMinor]
if !ok {
return "", errors.Errorf("prev version not set for version: %s", buildVersionMajorMinor)
}
return v, nil
}
type workerErrors struct {
mu struct {
syncutil.Mutex
errs []error
}
}
func (we *workerErrors) AddErr(err error) {
we.mu.Lock()
defer we.mu.Unlock()
we.mu.errs = append(we.mu.errs, err)
}
func (we *workerErrors) Err() error {
we.mu.Lock()
defer we.mu.Unlock()
if len(we.mu.errs) == 0 {
return nil
}
// TODO(andrei): Maybe we should do something other than return the first
// error...
return we.mu.errs[0]
}
|
[
"\"TC_BUILD_BRANCH\""
] |
[] |
[
"TC_BUILD_BRANCH"
] |
[]
|
["TC_BUILD_BRANCH"]
|
go
| 1 | 0 | |
models/classification/resnet_attention.py
|
# -*- coding: utf-8 -*-
import os
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.layers import Input, Multiply, GlobalAveragePooling1D, Add, Dense, Activation, ZeroPadding1D, \
BatchNormalization, Flatten, Conv1D, AveragePooling1D, MaxPooling1D, GlobalMaxPooling1D, Lambda, UpSampling1D, Reshape
from tensorflow.keras.models import Model, load_model
from keras.initializers import glorot_uniform
import keras.backend as K
from keras.callbacks import TensorBoard
from utils.AFClassication.data import loaddata
from utils.uts_classification.tools import AdvancedLearnignRateScheduler
from utils.uts_classification.metric import f1,recall,precision
def res_conv(X, filters, base, s):
name_base = base + '/branch'
F1, F2, F3 = filters
##### Branch1 is the main path and Branch2 is the shortcut path #####
X_shortcut = X
##### Branch1 #####
# First component of Branch1
X = BatchNormalization(name=name_base + '1/bn_1')(X)
X = Activation('relu', name=name_base + '1/relu_1')(X)
X = Conv1D(filters=F1, kernel_size=16, strides=1, padding='same', name=name_base + '1/conv_1',
kernel_initializer=glorot_uniform(seed=0))(X)
# Second component of Branch1
X = BatchNormalization(name=name_base + '1/bn_2')(X)
X = Activation('relu', name=name_base + '1/relu_2')(X)
X = Conv1D(filters=F2, kernel_size=48, strides=s, padding='same', name=name_base + '1/conv_2',
kernel_initializer=glorot_uniform(seed=0))(X)
# Third component of Branch1
X = BatchNormalization(name=name_base + '1/bn_3')(X)
X = Activation('relu', name=name_base + '1/relu_3')(X)
X = Conv1D(filters=F3, kernel_size=16, strides=1, padding='same', name=name_base + '1/conv_3',
kernel_initializer=glorot_uniform(seed=0))(X)
##### Branch2 ####
X_shortcut = BatchNormalization(name=name_base + '2/bn_1')(X_shortcut)
X_shortcut = Activation('relu', name=name_base + '2/relu_1')(X_shortcut)
X_shortcut = Conv1D(filters=F3, kernel_size=16, strides=s, padding='same', name=name_base + '2/conv_1',
kernel_initializer=glorot_uniform(seed=0))(X_shortcut)
# Final step: Add Branch1 and Branch2
X = Add(name=base + '/Add')([X, X_shortcut])
return X
def res_identity(X, filters, base):
name_base = base + '/branch'
F1, F2, F3 = filters
##### Branch1 is the main path and Branch2 is the shortcut path #####
X_shortcut = X
##### Branch1 #####
# First component of Branch1
X = BatchNormalization(name=name_base + '1/bn_1')(X)
Shortcut = Activation('relu', name=name_base + '1/relu_1')(X)
X = Conv1D(filters=F1, kernel_size=16, strides=1, padding='same', name=name_base + '1/conv_1',
kernel_initializer=glorot_uniform(seed=0))(Shortcut)
# Second component of Branch1
X = BatchNormalization(name=name_base + '1/bn_2')(X)
X = Activation('relu', name=name_base + '1/relu_2')(X)
X = Conv1D(filters=F2, kernel_size=48, strides=1, padding='same', name=name_base + '1/conv_2',
kernel_initializer=glorot_uniform(seed=0))(X)
# Third component of Branch1
X = BatchNormalization(name=name_base + '1/bn_3')(X)
X = Activation('relu', name=name_base + '1/relu_3')(X)
X = Conv1D(filters=F3, kernel_size=16, strides=1, padding='same', name=name_base + '1/conv_3',
kernel_initializer=glorot_uniform(seed=0))(X)
# Final step: Add Branch1 and the original Input itself
X = Add(name=base + '/Add')([X, X_shortcut])
return X
def Trunk_block(X, F, base):
name_base = base
X = res_identity(X, F, name_base + '/Residual_id_1')
X = res_identity(X, F, name_base + '/Residual_id_2')
return X
def interpolation(input_tensor, ref_tensor, name): # resizes input_tensor wrt. ref_tensor
# resize_nearest_neighbor
# L = ref_tensor.get_shape()[1]
# print(input_tensor.shape)
# x = Reshape((input_tensor.shape[1],1,input_tensor.shape[2]))(input_tensor)
# print(x.shape)
# x = tf.compat.v1.image.resize_nearest_neighbor(x, [L, 1], name=name)
# out = Reshape((x.shape[1],x.shape[3]))(x)
# print(out.shape)
# print(input_tensor.shape)
out = UpSampling1D(size=ref_tensor.shape[1]//input_tensor.shape[1])(input_tensor)
# print(out.shape)
return out
def Attention_1(X, filters, base):
F1, F2, F3 = filters
name_base = base
X = res_identity(X, filters, name_base + '/Pre_Residual_id')
X_Trunk = Trunk_block(X, filters, name_base + '/Trunk')
print("X_Trunk")
print(X_Trunk.shape)
X = MaxPooling1D(3, strides=2, padding='same', name=name_base + '/Mask/pool_3')(X)
print(X.shape)
X = res_identity(X, filters, name_base + '/Mask/Residual_id_3_Down')
Residual_id_3_Down_shortcut = X
Residual_id_3_Down_branched = res_identity(X, filters, name_base + '/Mask/Residual_id_3_Down_branched')
X = MaxPooling1D(3,strides=2, padding='same', name=name_base + '/Mask/pool_2')(X)
print(X.shape)
X = res_identity(X, filters, name_base + '/Mask/Residual_id_2_Down')
Residual_id_2_Down_shortcut = X
Residual_id_2_Down_branched = res_identity(X, filters, name_base + '/Mask/Residual_id_2_Down_branched')
X = MaxPooling1D(3, strides=2, padding='same', name=name_base + '/Mask/pool_1')(X)
print(X.shape)
X = res_identity(X, filters, name_base + '/Mask/Residual_id_1_Down')
X = res_identity(X, filters, name_base + '/Mask/Residual_id_1_Up')
temp_name1 = name_base + "/Mask/Interpool_1"
# X = Lambda(interpolation, arguments={'ref_tensor': Residual_id_2_Down_shortcut, 'name': temp_name1})(X)
X = UpSampling1D(size=Residual_id_2_Down_shortcut.shape[1] // X.shape[1], name=temp_name1)(X)
print(X.shape)
X = Add(name=base + '/Mask/Add_after_Interpool_1')([X, Residual_id_2_Down_branched])
X = res_identity(X, filters, name_base + '/Mask/Residual_id_2_Up')
temp_name2 = name_base + "/Mask/Interpool_2"
# X = Lambda(interpolation, arguments={'ref_tensor': Residual_id_3_Down_shortcut, 'name': temp_name2})(X)
X = UpSampling1D(size=Residual_id_3_Down_shortcut.shape[1] // X.shape[1], name=temp_name2)(X)
print(X.shape)
X = Add(name=base + '/Mask/Add_after_Interpool_2')([X, Residual_id_3_Down_branched])
X = res_identity(X, filters, name_base + '/Mask/Residual_id_3_Up')
temp_name3 = name_base + "/Mask/Interpool_3"
# X = Lambda(interpolation, arguments={'ref_tensor': X_Trunk, 'name': temp_name3})(X)
X = UpSampling1D(size=X_Trunk.shape[1] // X.shape[1], name=temp_name3)(X)
print(X.shape)
X = BatchNormalization(name=name_base + '/Mask/Interpool_3/bn_1')(X)
X = Activation('relu', name=name_base + '/Mask/Interpool_3/relu_1')(X)
X = Conv1D(F3, kernel_size=1, strides=1, padding='same', name=name_base + '/Mask/Interpool_3/conv_1',
kernel_initializer=glorot_uniform(seed=0))(X)
print(X.shape)
X = BatchNormalization(name=name_base + '/Mask/Interpool_3/bn_2')(X)
X = Activation('relu', name=name_base + '/Mask/Interpool_3/relu_2')(X)
X = Conv1D(F3, kernel_size=1, strides=1, padding='same', name=name_base + '/Mask/Interpool_3/conv_2',
kernel_initializer=glorot_uniform(seed=0))(X)
print(X.shape)
X = Activation('sigmoid', name=name_base + '/Mask/sigmoid')(X)
X = Multiply(name=name_base + '/Mutiply')([X_Trunk, X])
X = Add(name=name_base + '/Add')([X_Trunk, X])
X = res_identity(X, filters, name_base + '/Post_Residual_id')
return X
def Attention_2(X, filters, base):
F1, F2, F3 = filters
name_base = base
X = res_identity(X, filters, name_base + '/Pre_Residual_id')
X_Trunk = Trunk_block(X, filters, name_base + '/Trunk')
X = MaxPooling1D(3, strides=2, padding='same', name=name_base + '/Mask/pool_2')(X)
X = res_identity(X, filters, name_base + '/Mask/Residual_id_2_Down')
Residual_id_2_Down_shortcut = X
Residual_id_2_Down_branched = res_identity(X, filters, name_base + '/Mask/Residual_id_2_Down_branched')
X = MaxPooling1D(3, strides=2, padding='same', name=name_base + '/Mask/pool_1')(X)
X = res_identity(X, filters, name_base + '/Mask/Residual_id_1_Down')
X = res_identity(X, filters, name_base + '/Mask/Residual_id_1_Up')
temp_name1 = name_base + "/Mask/Interpool_1"
# X = Lambda(interpolation, arguments={'ref_tensor': Residual_id_2_Down_shortcut, 'name': temp_name1})(X)
X = UpSampling1D(size=Residual_id_2_Down_shortcut.shape[1] // X.shape[1], name=temp_name1)(X)
X = Add(name=base + '/Mask/Add_after_Interpool_1')([X, Residual_id_2_Down_branched])
X = res_identity(X, filters, name_base + '/Mask/Residual_id_2_Up')
temp_name2 = name_base + "/Mask/Interpool_2"
# X = Lambda(interpolation, arguments={'ref_tensor': X_Trunk, 'name': temp_name2})(X)
X = UpSampling1D(size=X_Trunk.shape[1] // X.shape[1], name=temp_name2)(X)
X = BatchNormalization(name=name_base + '/Mask/Interpool_2/bn_1')(X)
X = Activation('relu', name=name_base + '/Mask/Interpool_2/relu_1')(X)
X = Conv1D(F3, kernel_size=1, strides=1, padding='same', name=name_base + '/Mask/Interpool_2/conv_1',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization(name=name_base + '/Mask/Interpool_2/bn_2')(X)
X = Activation('relu', name=name_base + '/Mask/Interpool_2/relu_2')(X)
X = Conv1D(F3, kernel_size=1, strides=1, padding='same', name=name_base + '/Mask/Interpool_2/conv_2',
kernel_initializer=glorot_uniform(seed=0))(X)
X = Activation('sigmoid', name=name_base + '/Mask/sigmoid')(X)
X = Multiply(name=name_base + '/Mutiply')([X_Trunk, X])
X = Add(name=name_base + '/Add')([X_Trunk, X])
X = res_identity(X, filters, name_base + '/Post_Residual_id')
return X
def Attention_3(X, filters, base):
F1, F2, F3 = filters
name_base = base
X = res_identity(X, filters, name_base + '/Pre_Residual_id')
X_Trunk = Trunk_block(X, filters, name_base + '/Trunk')
X = MaxPooling1D(3, strides=2, padding='same', name=name_base + '/Mask/pool_1')(X)
X = res_identity(X, filters, name_base + '/Mask/Residual_id_1_Down')
X = res_identity(X, filters, name_base + '/Mask/Residual_id_1_Up')
temp_name2 = name_base + "/Mask/Interpool_1"
# X = Lambda(interpolation, arguments={'ref_tensor': X_Trunk, 'name': temp_name2})(X)
X = UpSampling1D(size=X_Trunk.shape[1] // X.shape[1], name=temp_name2)(X)
X = BatchNormalization(name=name_base + '/Mask/Interpool_2/bn_1')(X)
X = Activation('relu', name=name_base + '/Mask/Interpool_2/relu_1')(X)
X = Conv1D(F3, kernel_size=1, strides=1, padding='same', name=name_base + '/Mask/Interpool_2/conv_1',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization(name=name_base + '/Mask/Interpool_2/bn_2')(X)
X = Activation('relu', name=name_base + '/Mask/Interpool_2/relu_2')(X)
X = Conv1D(F3, kernel_size=1, strides=1, padding='same', name=name_base + '/Mask/Interpool_2/conv_2',
kernel_initializer=glorot_uniform(seed=0))(X)
X = Activation('sigmoid', name=name_base + '/Mask/sigmoid')(X)
X = Multiply(name=name_base + '/Mutiply')([X_Trunk, X])
X = Add(name=name_base + '/Add')([X_Trunk, X])
X = res_identity(X, filters, name_base + '/Post_Residual_id')
return X
# 加载UCI_HAR_Dataset
(X_train, y_train), (Xval, yval), (final_testset, final_testtarget) , (R_train, Rval, Rtest), (
P_train, Pval, Ptest), (Q_train, Qval, Qtest), (T_train, Tval, Ttest)= loaddata()
shape = X_train[0].shape
if len(shape) == 2:
X_train[0] = np.expand_dims(X_train[0], axis=2)
Xval[0] = np.expand_dims(Xval[0], axis=2)
final_testset[0] = np.expand_dims(final_testset[0], axis=2)
NUM_CLASSES = 3
x_train = np.concatenate((X_train[0],Xval[0]),axis=0)
y_train = np.concatenate((y_train,yval),axis=0)
train_number = int(len(x_train) / 16) * 16
print(x_train.shape)
print(y_train.shape)
print(final_testset[0].shape)
print(final_testtarget.shape)
print(y_train[:3])
input_shape = x_train.shape[1:]
nb_classes = 3
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'
X_input = Input(input_shape)
X = Conv1D(8, 7, strides=2, padding='same', name='conv_1', kernel_initializer=glorot_uniform(seed=0))(
X_input)
X = BatchNormalization(axis=-1, name='bn_1')(X)
X = Activation('relu', name='relu_1')(X)
X = MaxPooling1D(3, strides=2, padding='same', name='pool_1')(X)
X = res_conv(X, [8, 8, 32], 'Residual_conv_1', 1)
### Attention 1 Start
X = Attention_1(X, [8, 8, 32], 'Attention_1')
### Attention 1 End
X = res_conv(X, [16, 16, 64], 'Residual_conv_2', 2)
### Attention 2 Start
X = Attention_2(X, [16, 16, 64], 'Attention_2')
### Attention 2 End
X = res_conv(X, [32, 32, 128], 'Residual_conv_3', 2)
### Attention 3 Start
X = Attention_3(X, [32, 32, 128], 'Attention_3')
### Attention 3 End
X = res_conv(X, [64, 64, 256], 'Residual_conv_4', 2)
X = res_identity(X, [64, 64, 256], 'Residual_id_1')
X = res_identity(X, [64, 64, 256], 'Residual_id_2')
X = BatchNormalization(name='bn_2')(X)
X = Activation('relu', name='relu_2')(X)
print(X.shape)
X = GlobalAveragePooling1D()(X)
print(X.shape)
X = Dense(nb_classes,activation='sigmoid', name='Dense_1')(X)
model = Model(inputs=X_input, outputs=X, name='attention_56')
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='adam',
metrics=['accuracy',recall,precision,f1])
tbCallBack = TensorBoard(log_dir='tensorboard_log', # log 目录
histogram_freq=0, # 按照何等频率(epoch)来计算直方图,0为不计算
# batch_size=32, # 用多大量的数据计算直方图
write_graph=True, # 是否存储网络结构图
write_images=True,# 是否可视化参数
embeddings_freq=0,
embeddings_layer_names=None,
embeddings_metadata=None)
model.fit(x_train[0:train_number],y_train[0:train_number], epochs=100, validation_split=0.1, batch_size=16, callbacks=[keras.callbacks.EarlyStopping(patience=10),
AdvancedLearnignRateScheduler(monitor='val_loss', patience=6, verbose=1, mode='auto', decayRatio=0.1, warmup_batches=5, init_lr=0.001)],verbose=1)
loss, accuracy, recall, precision, f1 = model.evaluate(final_testset[0], final_testtarget)
print(loss)
print(accuracy)
print(recall)
print(precision)
print(f1)
|
[] |
[] |
[
"CUDA_VISIBLE_DEVICES"
] |
[]
|
["CUDA_VISIBLE_DEVICES"]
|
python
| 1 | 0 | |
application.py
|
import os
import re
from flask import Flask, jsonify, render_template, request
from cs50 import SQL
from helpers import lookup
# Configure application
app = Flask(__name__)
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///mashup.db")
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/")
def index():
"""Render map"""
if not os.environ.get("API_KEY"):
raise RuntimeError("API_KEY not set")
return render_template("index.html", key=os.environ.get("API_KEY"))
@app.route("/articles")
def articles():
"""Look up articles for geo"""
alo = request.args.get("geo")
# TODO
return jsonify(lookup(alo))
@app.route("/search")
def search():
"""Search for places that match query"""
q = request.args.get("q") + "%"
# TODO
return jsonify(db.execute("SELECT * FROM places WHERE postal_code LIKE :q OR admin_name1 LIKE :q OR place_name LIKE :q", q=q))
@app.route("/update")
def update():
"""Find up to 10 places within view"""
# Ensure parameters are present
if not request.args.get("sw"):
raise RuntimeError("missing sw")
if not request.args.get("ne"):
raise RuntimeError("missing ne")
# Ensure parameters are in lat,lng format
if not re.search("^-?\d+(?:\.\d+)?,-?\d+(?:\.\d+)?$", request.args.get("sw")):
raise RuntimeError("invalid sw")
if not re.search("^-?\d+(?:\.\d+)?,-?\d+(?:\.\d+)?$", request.args.get("ne")):
raise RuntimeError("invalid ne")
# Explode southwest corner into two variables
sw_lat, sw_lng = map(float, request.args.get("sw").split(","))
# Explode northeast corner into two variables
ne_lat, ne_lng = map(float, request.args.get("ne").split(","))
# Find 10 cities within view, pseudorandomly chosen if more within view
if sw_lng <= ne_lng:
# Doesn't cross the antimeridian
rows = db.execute("""SELECT * FROM places
WHERE :sw_lat <= latitude AND latitude <= :ne_lat AND (:sw_lng <= longitude AND longitude <= :ne_lng)
GROUP BY country_code, place_name, admin_code1
ORDER BY RANDOM()
LIMIT 10""",
sw_lat=sw_lat, ne_lat=ne_lat, sw_lng=sw_lng, ne_lng=ne_lng)
else:
# Crosses the antimeridian
rows = db.execute("""SELECT * FROM places
WHERE :sw_lat <= latitude AND latitude <= :ne_lat AND (:sw_lng <= longitude OR longitude <= :ne_lng)
GROUP BY country_code, place_name, admin_code1
ORDER BY RANDOM()
LIMIT 10""",
sw_lat=sw_lat, ne_lat=ne_lat, sw_lng=sw_lng, ne_lng=ne_lng)
# Output places as JSON
return jsonify(rows)
|
[] |
[] |
[
"API_KEY"
] |
[]
|
["API_KEY"]
|
python
| 1 | 0 | |
fn/common/api.go
|
package common
import (
"crypto/tls"
"net/http"
"os"
httptransport "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
fnclient "github.com/iron-io/functions_go/client"
)
func ApiClient() *fnclient.Functions {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: SSL_SKIP_VERIFY},
}
cl := &http.Client{Transport: tr}
transport := httptransport.NewWithClient(HOST, API_VERSION, []string{SCHEME}, cl)
if os.Getenv("IRON_TOKEN") != "" {
transport.DefaultAuthentication = httptransport.BearerToken(os.Getenv("IRON_TOKEN"))
}
// create the API client, with the transport
client := fnclient.New(transport, strfmt.Default)
return client
}
|
[
"\"IRON_TOKEN\"",
"\"IRON_TOKEN\""
] |
[] |
[
"IRON_TOKEN"
] |
[]
|
["IRON_TOKEN"]
|
go
| 1 | 0 | |
release.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
import sys
# codecov.io project token
import pypandoc
codecov_token = '' or os.environ.get('FORGIVE_DB_CODECOV_TOKEN')
base_dir = os.path.dirname(os.path.abspath(__file__))
sub_commands = {}
def run(*commands):
os.system('cd {} && {}'.format(base_dir, ' && '.join(commands)))
def cmd(name):
def decorator(func):
sub_commands[name] = func
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
def usage():
print('Usage: {} <sub_command> <args...>'.format(sys.argv[0]))
print('Sub command: [{}]'.format(', '.join(sub_commands)))
exit(1)
@cmd('test')
def test():
run('pytest --cov=./', 'codecov --token={}'.format(codecov_token))
@cmd('release')
def release(*setup_commands):
markdown_file = os.path.join(base_dir, 'README.md')
rst_file = os.path.join(base_dir, 'README.rst')
rst_content = pypandoc.convert(markdown_file, 'rst')
with open(rst_file, 'wb') as f:
f.write(rst_content.encode('utf-8'))
run('python setup.py {}'.format(' '.join(setup_commands)))
os.unlink(rst_file)
if __name__ == '__main__':
if len(sys.argv) < 2:
usage()
sub_command = sys.argv[1]
if sub_command not in sub_commands:
usage()
func = sub_commands[sub_command]
func(*sys.argv[2:])
|
[] |
[] |
[
"FORGIVE_DB_CODECOV_TOKEN"
] |
[]
|
["FORGIVE_DB_CODECOV_TOKEN"]
|
python
| 1 | 0 | |
poky/meta/lib/oeqa/selftest/cases/runtime_test.py
|
#
# SPDX-License-Identifier: MIT
#
from oeqa.selftest.case import OESelftestTestCase
from oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars, runqemu
from oeqa.utils.sshcontrol import SSHControl
import os
import re
import tempfile
import shutil
import oe.lsb
from oeqa.core.decorator.data import skipIfNotQemu
class TestExport(OESelftestTestCase):
@classmethod
def tearDownClass(cls):
runCmd("rm -rf /tmp/sdk")
super(TestExport, cls).tearDownClass()
def test_testexport_basic(self):
"""
Summary: Check basic testexport functionality with only ping test enabled.
Expected: 1. testexport directory must be created.
2. runexported.py must run without any error/exception.
3. ping test must succeed.
Product: oe-core
Author: Mariano Lopez <[email protected]>
"""
features = 'INHERIT += "testexport"\n'
# These aren't the actual IP addresses but testexport class needs something defined
features += 'TEST_SERVER_IP = "192.168.7.1"\n'
features += 'TEST_TARGET_IP = "192.168.7.1"\n'
features += 'TEST_SUITES = "ping"\n'
self.write_config(features)
# Build tesexport for core-image-minimal
bitbake('core-image-minimal')
bitbake('-c testexport core-image-minimal')
testexport_dir = get_bb_var('TEST_EXPORT_DIR', 'core-image-minimal')
# Verify if TEST_EXPORT_DIR was created
isdir = os.path.isdir(testexport_dir)
self.assertEqual(True, isdir, 'Failed to create testexport dir: %s' % testexport_dir)
with runqemu('core-image-minimal') as qemu:
# Attempt to run runexported.py to perform ping test
test_path = os.path.join(testexport_dir, "oe-test")
data_file = os.path.join(testexport_dir, 'data', 'testdata.json')
manifest = os.path.join(testexport_dir, 'data', 'manifest')
cmd = ("%s runtime --test-data-file %s --packages-manifest %s "
"--target-ip %s --server-ip %s --quiet"
% (test_path, data_file, manifest, qemu.ip, qemu.server_ip))
result = runCmd(cmd)
# Verify ping test was succesful
self.assertEqual(0, result.status, 'oe-test runtime returned a non 0 status')
def test_testexport_sdk(self):
"""
Summary: Check sdk functionality for testexport.
Expected: 1. testexport directory must be created.
2. SDK tarball must exists.
3. Uncompressing of tarball must succeed.
4. Check if the SDK directory is added to PATH.
5. Run tar from the SDK directory.
Product: oe-core
Author: Mariano Lopez <[email protected]>
"""
features = 'INHERIT += "testexport"\n'
# These aren't the actual IP addresses but testexport class needs something defined
features += 'TEST_SERVER_IP = "192.168.7.1"\n'
features += 'TEST_TARGET_IP = "192.168.7.1"\n'
features += 'TEST_SUITES = "ping"\n'
features += 'TEST_EXPORT_SDK_ENABLED = "1"\n'
features += 'TEST_EXPORT_SDK_PACKAGES = "nativesdk-tar"\n'
self.write_config(features)
# Build tesexport for core-image-minimal
bitbake('core-image-minimal')
bitbake('-c testexport core-image-minimal')
needed_vars = ['TEST_EXPORT_DIR', 'TEST_EXPORT_SDK_DIR', 'TEST_EXPORT_SDK_NAME']
bb_vars = get_bb_vars(needed_vars, 'core-image-minimal')
testexport_dir = bb_vars['TEST_EXPORT_DIR']
sdk_dir = bb_vars['TEST_EXPORT_SDK_DIR']
sdk_name = bb_vars['TEST_EXPORT_SDK_NAME']
# Check for SDK
tarball_name = "%s.sh" % sdk_name
tarball_path = os.path.join(testexport_dir, sdk_dir, tarball_name)
msg = "Couldn't find SDK tarball: %s" % tarball_path
self.assertEqual(os.path.isfile(tarball_path), True, msg)
# Extract SDK and run tar from SDK
result = runCmd("%s -y -d /tmp/sdk" % tarball_path)
self.assertEqual(0, result.status, "Couldn't extract SDK")
env_script = result.output.split()[-1]
result = runCmd(". %s; which tar" % env_script, shell=True)
self.assertEqual(0, result.status, "Couldn't setup SDK environment")
is_sdk_tar = True if "/tmp/sdk" in result.output else False
self.assertTrue(is_sdk_tar, "Couldn't setup SDK environment")
tar_sdk = result.output
result = runCmd("%s --version" % tar_sdk)
self.assertEqual(0, result.status, "Couldn't run tar from SDK")
class TestImage(OESelftestTestCase):
def test_testimage_install(self):
"""
Summary: Check install packages functionality for testimage/testexport.
Expected: 1. Import tests from a directory other than meta.
2. Check install/uninstall of socat.
Product: oe-core
Author: Mariano Lopez <[email protected]>
"""
if get_bb_var('DISTRO') == 'poky-tiny':
self.skipTest('core-image-full-cmdline not buildable for poky-tiny')
features = 'INHERIT += "testimage"\n'
features += 'IMAGE_INSTALL_append = " libssl"\n'
features += 'TEST_SUITES = "ping ssh selftest"\n'
self.write_config(features)
# Build core-image-sato and testimage
bitbake('core-image-full-cmdline socat')
bitbake('-c testimage core-image-full-cmdline')
def test_testimage_dnf(self):
"""
Summary: Check package feeds functionality for dnf
Expected: 1. Check that remote package feeds can be accessed
Product: oe-core
Author: Alexander Kanavin <[email protected]>
"""
if get_bb_var('DISTRO') == 'poky-tiny':
self.skipTest('core-image-full-cmdline not buildable for poky-tiny')
features = 'INHERIT += "testimage"\n'
features += 'TEST_SUITES = "ping ssh dnf_runtime dnf.DnfBasicTest.test_dnf_help"\n'
# We don't yet know what the server ip and port will be - they will be patched
# in at the start of the on-image test
features += 'PACKAGE_FEED_URIS = "http://bogus_ip:bogus_port"\n'
features += 'EXTRA_IMAGE_FEATURES += "package-management"\n'
features += 'PACKAGE_CLASSES = "package_rpm"\n'
bitbake('gnupg-native -c addto_recipe_sysroot')
# Enable package feed signing
self.gpg_home = tempfile.mkdtemp(prefix="oeqa-feed-sign-")
self.track_for_cleanup(self.gpg_home)
signing_key_dir = os.path.join(self.testlayer_path, 'files', 'signing')
runCmd('gpg --batch --homedir %s --import %s' % (self.gpg_home, os.path.join(signing_key_dir, 'key.secret')), native_sysroot=get_bb_var("RECIPE_SYSROOT_NATIVE", "gnupg-native"))
features += 'INHERIT += "sign_package_feed"\n'
features += 'PACKAGE_FEED_GPG_NAME = "testuser"\n'
features += 'PACKAGE_FEED_GPG_PASSPHRASE_FILE = "%s"\n' % os.path.join(signing_key_dir, 'key.passphrase')
features += 'GPG_PATH = "%s"\n' % self.gpg_home
self.write_config(features)
# Build core-image-sato and testimage
bitbake('core-image-full-cmdline socat')
bitbake('-c testimage core-image-full-cmdline')
def test_testimage_virgl_gtk_sdl(self):
"""
Summary: Check host-assisted accelerate OpenGL functionality in qemu with gtk and SDL frontends
Expected: 1. Check that virgl kernel driver is loaded and 3d acceleration is enabled
2. Check that kmscube demo runs without crashing.
Product: oe-core
Author: Alexander Kanavin <[email protected]>
"""
if "DISPLAY" not in os.environ:
self.skipTest("virgl gtk test must be run inside a X session")
distro = oe.lsb.distro_identifier()
if distro and distro == 'debian-8':
self.skipTest('virgl isn\'t working with Debian 8')
if distro and distro == 'debian-9':
self.skipTest('virgl isn\'t working with Debian 9')
if distro and distro == 'centos-7':
self.skipTest('virgl isn\'t working with Centos 7')
if distro and distro == 'opensuseleap-15.0':
self.skipTest('virgl isn\'t working with Opensuse 15.0')
qemu_packageconfig = get_bb_var('PACKAGECONFIG', 'qemu-system-native')
qemu_distrofeatures = get_bb_var('DISTRO_FEATURES', 'qemu-system-native')
features = 'INHERIT += "testimage"\n'
if 'gtk+' not in qemu_packageconfig:
features += 'PACKAGECONFIG_append_pn-qemu-system-native = " gtk+"\n'
if 'sdl' not in qemu_packageconfig:
features += 'PACKAGECONFIG_append_pn-qemu-system-native = " sdl"\n'
if 'opengl' not in qemu_distrofeatures:
features += 'DISTRO_FEATURES_append = " opengl"\n'
features += 'TEST_SUITES = "ping ssh virgl"\n'
features += 'IMAGE_FEATURES_append = " ssh-server-dropbear"\n'
features += 'IMAGE_INSTALL_append = " kmscube"\n'
features_gtk = features + 'TEST_RUNQEMUPARAMS = "gtk gl"\n'
self.write_config(features_gtk)
bitbake('core-image-minimal')
bitbake('-c testimage core-image-minimal')
features_sdl = features + 'TEST_RUNQEMUPARAMS = "sdl gl"\n'
self.write_config(features_sdl)
bitbake('core-image-minimal')
bitbake('-c testimage core-image-minimal')
def test_testimage_virgl_headless(self):
"""
Summary: Check host-assisted accelerate OpenGL functionality in qemu with egl-headless frontend
Expected: 1. Check that virgl kernel driver is loaded and 3d acceleration is enabled
2. Check that kmscube demo runs without crashing.
Product: oe-core
Author: Alexander Kanavin <[email protected]>
"""
import subprocess, os
try:
content = os.listdir("/dev/dri")
if len([i for i in content if i.startswith('render')]) == 0:
self.skipTest("No render nodes found in /dev/dri: %s" %(content))
except FileNotFoundError:
self.skipTest("/dev/dri directory does not exist; no render nodes available on this machine.")
try:
dripath = subprocess.check_output("pkg-config --variable=dridriverdir dri", shell=True)
except subprocess.CalledProcessError as e:
self.skipTest("Could not determine the path to dri drivers on the host via pkg-config.\nPlease install Mesa development files (particularly, dri.pc) on the host machine.")
qemu_distrofeatures = get_bb_var('DISTRO_FEATURES', 'qemu-system-native')
features = 'INHERIT += "testimage"\n'
if 'opengl' not in qemu_distrofeatures:
features += 'DISTRO_FEATURES_append = " opengl"\n'
features += 'TEST_SUITES = "ping ssh virgl"\n'
features += 'IMAGE_FEATURES_append = " ssh-server-dropbear"\n'
features += 'IMAGE_INSTALL_append = " kmscube"\n'
features += 'TEST_RUNQEMUPARAMS = "egl-headless"\n'
self.write_config(features)
bitbake('core-image-minimal')
bitbake('-c testimage core-image-minimal')
class Postinst(OESelftestTestCase):
def init_manager_loop(self, init_manager):
import oe.path
vars = get_bb_vars(("IMAGE_ROOTFS", "sysconfdir"), "core-image-minimal")
rootfs = vars["IMAGE_ROOTFS"]
self.assertIsNotNone(rootfs)
sysconfdir = vars["sysconfdir"]
self.assertIsNotNone(sysconfdir)
# Need to use oe.path here as sysconfdir starts with /
hosttestdir = oe.path.join(rootfs, sysconfdir, "postinst-test")
targettestdir = os.path.join(sysconfdir, "postinst-test")
for classes in ("package_rpm", "package_deb", "package_ipk"):
with self.subTest(init_manager=init_manager, package_class=classes):
features = 'CORE_IMAGE_EXTRA_INSTALL = "postinst-delayed-b"\n'
features += 'IMAGE_FEATURES += "package-management empty-root-password"\n'
features += 'PACKAGE_CLASSES = "%s"\n' % classes
if init_manager == "systemd":
features += 'DISTRO_FEATURES_append = " systemd"\n'
features += 'VIRTUAL-RUNTIME_init_manager = "systemd"\n'
features += 'DISTRO_FEATURES_BACKFILL_CONSIDERED = "sysvinit"\n'
features += 'VIRTUAL-RUNTIME_initscripts = ""\n'
self.write_config(features)
bitbake('core-image-minimal')
self.assertTrue(os.path.isfile(os.path.join(hosttestdir, "rootfs")),
"rootfs state file was not created")
with runqemu('core-image-minimal') as qemu:
# Make the test echo a string and search for that as
# run_serial()'s status code is useless.'
for filename in ("rootfs", "delayed-a", "delayed-b"):
status, output = qemu.run_serial("test -f %s && echo found" % os.path.join(targettestdir, filename))
self.assertEqual(output, "found", "%s was not present on boot" % filename)
@skipIfNotQemu('qemuall', 'Test only runs in qemu')
def test_postinst_rootfs_and_boot_sysvinit(self):
"""
Summary: The purpose of this test case is to verify Post-installation
scripts are called when rootfs is created and also test
that script can be delayed to run at first boot.
Dependencies: NA
Steps: 1. Add proper configuration to local.conf file
2. Build a "core-image-minimal" image
3. Verify that file created by postinst_rootfs recipe is
present on rootfs dir.
4. Boot the image created on qemu and verify that the file
created by postinst_boot recipe is present on image.
Expected: The files are successfully created during rootfs and boot
time for 3 different package managers: rpm,ipk,deb and
for initialization managers: sysvinit.
"""
self.init_manager_loop("sysvinit")
@skipIfNotQemu('qemuall', 'Test only runs in qemu')
def test_postinst_rootfs_and_boot_systemd(self):
"""
Summary: The purpose of this test case is to verify Post-installation
scripts are called when rootfs is created and also test
that script can be delayed to run at first boot.
Dependencies: NA
Steps: 1. Add proper configuration to local.conf file
2. Build a "core-image-minimal" image
3. Verify that file created by postinst_rootfs recipe is
present on rootfs dir.
4. Boot the image created on qemu and verify that the file
created by postinst_boot recipe is present on image.
Expected: The files are successfully created during rootfs and boot
time for 3 different package managers: rpm,ipk,deb and
for initialization managers: systemd.
"""
self.init_manager_loop("systemd")
def test_failing_postinst(self):
"""
Summary: The purpose of this test case is to verify that post-installation
scripts that contain errors are properly reported.
Expected: The scriptlet failure is properly reported.
The file that is created after the error in the scriptlet is not present.
Product: oe-core
Author: Alexander Kanavin <[email protected]>
"""
import oe.path
vars = get_bb_vars(("IMAGE_ROOTFS", "sysconfdir"), "core-image-minimal")
rootfs = vars["IMAGE_ROOTFS"]
self.assertIsNotNone(rootfs)
sysconfdir = vars["sysconfdir"]
self.assertIsNotNone(sysconfdir)
# Need to use oe.path here as sysconfdir starts with /
hosttestdir = oe.path.join(rootfs, sysconfdir, "postinst-test")
for classes in ("package_rpm", "package_deb", "package_ipk"):
with self.subTest(package_class=classes):
features = 'CORE_IMAGE_EXTRA_INSTALL = "postinst-rootfs-failing"\n'
features += 'PACKAGE_CLASSES = "%s"\n' % classes
self.write_config(features)
bb_result = bitbake('core-image-minimal', ignore_status=True)
self.assertGreaterEqual(bb_result.output.find("Postinstall scriptlets of ['postinst-rootfs-failing'] have failed."), 0,
"Warning about a failed scriptlet not found in bitbake output: %s" %(bb_result.output))
self.assertTrue(os.path.isfile(os.path.join(hosttestdir, "rootfs-before-failure")),
"rootfs-before-failure file was not created")
self.assertFalse(os.path.isfile(os.path.join(hosttestdir, "rootfs-after-failure")),
"rootfs-after-failure file was created")
class SystemTap(OESelftestTestCase):
"""
Summary: The purpose of this test case is to verify native crosstap
works while talking to a target.
Expected: The script should successfully connect to the qemu machine
and run some systemtap examples on a qemu machine.
"""
@classmethod
def setUpClass(cls):
super(SystemTap, cls).setUpClass()
cls.image = "core-image-minimal"
def default_config(self):
return """
# These aren't the actual IP addresses but testexport class needs something defined
TEST_SERVER_IP = "192.168.7.1"
TEST_TARGET_IP = "192.168.7.2"
EXTRA_IMAGE_FEATURES += "tools-profile dbg-pkgs"
IMAGE_FEATURES_append = " ssh-server-dropbear"
# enables kernel debug symbols
KERNEL_EXTRA_FEATURES_append = " features/debug/debug-kernel.scc"
KERNEL_EXTRA_FEATURES_append = " features/systemtap/systemtap.scc"
# add systemtap run-time into target image if it is not there yet
IMAGE_INSTALL_append = " systemtap"
"""
def test_crosstap_helloworld(self):
self.write_config(self.default_config())
bitbake('systemtap-native')
systemtap_examples = os.path.join(get_bb_var("WORKDIR","systemtap-native"), "usr/share/systemtap/examples")
bitbake(self.image)
with runqemu(self.image) as qemu:
cmd = "crosstap -r [email protected] -s %s/general/helloworld.stp " % systemtap_examples
result = runCmd(cmd)
self.assertEqual(0, result.status, 'crosstap helloworld returned a non 0 status:%s' % result.output)
def test_crosstap_pstree(self):
self.write_config(self.default_config())
bitbake('systemtap-native')
systemtap_examples = os.path.join(get_bb_var("WORKDIR","systemtap-native"), "usr/share/systemtap/examples")
bitbake(self.image)
with runqemu(self.image) as qemu:
cmd = "crosstap -r [email protected] -s %s/process/pstree.stp" % systemtap_examples
result = runCmd(cmd)
self.assertEqual(0, result.status, 'crosstap pstree returned a non 0 status:%s' % result.output)
def test_crosstap_syscalls_by_proc(self):
self.write_config(self.default_config())
bitbake('systemtap-native')
systemtap_examples = os.path.join(get_bb_var("WORKDIR","systemtap-native"), "usr/share/systemtap/examples")
bitbake(self.image)
with runqemu(self.image) as qemu:
cmd = "crosstap -r [email protected] -s %s/process/ syscalls_by_proc.stp" % systemtap_examples
result = runCmd(cmd)
self.assertEqual(0, result.status, 'crosstap syscalls_by_proc returned a non 0 status:%s' % result.output)
def test_crosstap_syscalls_by_pid(self):
self.write_config(self.default_config())
bitbake('systemtap-native')
systemtap_examples = os.path.join(get_bb_var("WORKDIR","systemtap-native"), "usr/share/systemtap/examples")
bitbake(self.image)
with runqemu(self.image) as qemu:
cmd = "crosstap -r [email protected] -s %s/process/ syscalls_by_pid.stp" % systemtap_examples
result = runCmd(cmd)
self.assertEqual(0, result.status, 'crosstap syscalls_by_pid returned a non 0 status:%s' % result.output)
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
app.py
|
import os
from flask import Flask, render_template, make_response, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/main.js')
def main_js():
return render_template('main.js')
@app.route('/davidshimjs-qrcodejs/qrcode.js')
def qr_code_js():
return render_template('davidshimjs-qrcodejs/qrcode.js')
@app.route('/davidshimjs-qrcodejs/jquery.min.js')
def jquery_js():
return render_template('davidshimjs-qrcodejs/jquery.min.js')
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
[] |
[] |
[
"PORT"
] |
[]
|
["PORT"]
|
python
| 1 | 0 | |
rest/accounts/instance-get-example-1/instance-get-example-1.6.x.py
|
# Download the Python helper library from twilio.com/docs/python/install
import os
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
# To set up environmental variables, see http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
account = client.api.accounts(account_sid).fetch()
print(account.date_created)
|
[] |
[] |
[
"TWILIO_AUTH_TOKEN",
"TWILIO_ACCOUNT_SID"
] |
[]
|
["TWILIO_AUTH_TOKEN", "TWILIO_ACCOUNT_SID"]
|
python
| 2 | 0 | |
engine/SCons/Script/__init__.py
|
"""SCons.Script
This file implements the main() function used by the scons script.
Architecturally, this *is* the scons script, and will likely only be
called from the external "scons" wrapper. Consequently, anything here
should not be, or be considered, part of the build engine. If it's
something that we expect other software to want to use, it should go in
some other module. If it's specific to the "scons" script invocation,
it goes here.
"""
#
# Copyright (c) 2001 - 2017 The SCons Foundation
#
# 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.
#
__revision__ = "src/engine/SCons/Script/__init__.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
import time
start_time = time.time()
import collections
import os
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import sys
# Special chicken-and-egg handling of the "--debug=memoizer" flag:
#
# SCons.Memoize contains a metaclass implementation that affects how
# the other classes are instantiated. The Memoizer may add shim methods
# to classes that have methods that cache computed values in order to
# count and report the hits and misses.
#
# If we wait to enable the Memoization until after we've parsed the
# command line options normally, it will be too late, because the Memoizer
# will have already analyzed the classes that it's Memoizing and decided
# to not add the shims. So we use a special-case, up-front check for
# the "--debug=memoizer" flag and enable Memoizer before we import any
# of the other modules that use it.
_args = sys.argv + os.environ.get('SCONSFLAGS', '').split()
if "--debug=memoizer" in _args:
import SCons.Memoize
import SCons.Warnings
try:
SCons.Memoize.EnableMemoization()
except SCons.Warnings.Warning:
# Some warning was thrown. Arrange for it to be displayed
# or not after warnings are configured.
from . import Main
exc_type, exc_value, tb = sys.exc_info()
Main.delayed_warnings.append((exc_type, exc_value))
del _args
import SCons.Action
import SCons.Builder
import SCons.Environment
import SCons.Node.FS
import SCons.Options
import SCons.Platform
import SCons.Scanner
import SCons.SConf
import SCons.Subst
import SCons.Tool
import SCons.Util
import SCons.Variables
import SCons.Defaults
from . import Main
main = Main.main
# The following are global class definitions and variables that used to
# live directly in this module back before 0.96.90, when it contained
# a lot of code. Some SConscript files in widely-distributed packages
# (Blender is the specific example) actually reached into SCons.Script
# directly to use some of these. Rather than break those SConscript
# files, we're going to propagate these names into the SCons.Script
# namespace here.
#
# Some of these are commented out because it's *really* unlikely anyone
# used them, but we're going to leave the comment here to try to make
# it obvious what to do if the situation arises.
BuildTask = Main.BuildTask
CleanTask = Main.CleanTask
QuestionTask = Main.QuestionTask
#PrintHelp = Main.PrintHelp
#SConscriptSettableOptions = Main.SConscriptSettableOptions
AddOption = Main.AddOption
PrintHelp = Main.PrintHelp
GetOption = Main.GetOption
SetOption = Main.SetOption
Progress = Main.Progress
GetBuildFailures = Main.GetBuildFailures
#keep_going_on_error = Main.keep_going_on_error
#print_dtree = Main.print_dtree
#print_explanations = Main.print_explanations
#print_includes = Main.print_includes
#print_objects = Main.print_objects
#print_time = Main.print_time
#print_tree = Main.print_tree
#memory_stats = Main.memory_stats
#ignore_errors = Main.ignore_errors
#sconscript_time = Main.sconscript_time
#command_time = Main.command_time
#exit_status = Main.exit_status
#profiling = Main.profiling
#repositories = Main.repositories
#
from . import SConscript
_SConscript = SConscript
call_stack = _SConscript.call_stack
#
Action = SCons.Action.Action
AddMethod = SCons.Util.AddMethod
AllowSubstExceptions = SCons.Subst.SetAllowableExceptions
Builder = SCons.Builder.Builder
Configure = _SConscript.Configure
Environment = SCons.Environment.Environment
#OptParser = SCons.SConsOptions.OptParser
FindPathDirs = SCons.Scanner.FindPathDirs
Platform = SCons.Platform.Platform
Return = _SConscript.Return
Scanner = SCons.Scanner.Base
Tool = SCons.Tool.Tool
WhereIs = SCons.Util.WhereIs
#
BoolVariable = SCons.Variables.BoolVariable
EnumVariable = SCons.Variables.EnumVariable
ListVariable = SCons.Variables.ListVariable
PackageVariable = SCons.Variables.PackageVariable
PathVariable = SCons.Variables.PathVariable
# Deprecated names that will go away some day.
BoolOption = SCons.Options.BoolOption
EnumOption = SCons.Options.EnumOption
ListOption = SCons.Options.ListOption
PackageOption = SCons.Options.PackageOption
PathOption = SCons.Options.PathOption
# Action factories.
Chmod = SCons.Defaults.Chmod
Copy = SCons.Defaults.Copy
Delete = SCons.Defaults.Delete
Mkdir = SCons.Defaults.Mkdir
Move = SCons.Defaults.Move
Touch = SCons.Defaults.Touch
# Pre-made, public scanners.
CScanner = SCons.Tool.CScanner
DScanner = SCons.Tool.DScanner
DirScanner = SCons.Defaults.DirScanner
ProgramScanner = SCons.Tool.ProgramScanner
SourceFileScanner = SCons.Tool.SourceFileScanner
# Functions we might still convert to Environment methods.
CScan = SCons.Defaults.CScan
DefaultEnvironment = SCons.Defaults.DefaultEnvironment
# Other variables we provide.
class TargetList(collections.UserList):
def _do_nothing(self, *args, **kw):
pass
def _add_Default(self, list):
self.extend(list)
def _clear(self):
del self[:]
ARGUMENTS = {}
ARGLIST = []
BUILD_TARGETS = TargetList()
COMMAND_LINE_TARGETS = []
DEFAULT_TARGETS = []
# BUILD_TARGETS can be modified in the SConscript files. If so, we
# want to treat the modified BUILD_TARGETS list as if they specified
# targets on the command line. To do that, though, we need to know if
# BUILD_TARGETS was modified through "official" APIs or by hand. We do
# this by updating two lists in parallel, the documented BUILD_TARGETS
# list, above, and this internal _build_plus_default targets list which
# should only have "official" API changes. Then Script/Main.py can
# compare these two afterwards to figure out if the user added their
# own targets to BUILD_TARGETS.
_build_plus_default = TargetList()
def _Add_Arguments(alist):
for arg in alist:
a, b = arg.split('=', 1)
ARGUMENTS[a] = b
ARGLIST.append((a, b))
def _Add_Targets(tlist):
if tlist:
COMMAND_LINE_TARGETS.extend(tlist)
BUILD_TARGETS.extend(tlist)
BUILD_TARGETS._add_Default = BUILD_TARGETS._do_nothing
BUILD_TARGETS._clear = BUILD_TARGETS._do_nothing
_build_plus_default.extend(tlist)
_build_plus_default._add_Default = _build_plus_default._do_nothing
_build_plus_default._clear = _build_plus_default._do_nothing
def _Set_Default_Targets_Has_Been_Called(d, fs):
return DEFAULT_TARGETS
def _Set_Default_Targets_Has_Not_Been_Called(d, fs):
if d is None:
d = [fs.Dir('.')]
return d
_Get_Default_Targets = _Set_Default_Targets_Has_Not_Been_Called
def _Set_Default_Targets(env, tlist):
global DEFAULT_TARGETS
global _Get_Default_Targets
_Get_Default_Targets = _Set_Default_Targets_Has_Been_Called
for t in tlist:
if t is None:
# Delete the elements from the list in-place, don't
# reassign an empty list to DEFAULT_TARGETS, so that the
# variables will still point to the same object we point to.
del DEFAULT_TARGETS[:]
BUILD_TARGETS._clear()
_build_plus_default._clear()
elif isinstance(t, SCons.Node.Node):
DEFAULT_TARGETS.append(t)
BUILD_TARGETS._add_Default([t])
_build_plus_default._add_Default([t])
else:
nodes = env.arg2nodes(t, env.fs.Entry)
DEFAULT_TARGETS.extend(nodes)
BUILD_TARGETS._add_Default(nodes)
_build_plus_default._add_Default(nodes)
#
help_text = None
def HelpFunction(text, append=False):
global help_text
if help_text is None:
if append:
s = StringIO()
PrintHelp(s)
help_text = s.getvalue()
s.close()
else:
help_text = ""
help_text= help_text + text
#
# Will be non-zero if we are reading an SConscript file.
sconscript_reading = 0
#
def Variables(files=[], args=ARGUMENTS):
return SCons.Variables.Variables(files, args)
def Options(files=[], args=ARGUMENTS):
return SCons.Options.Options(files, args)
# The list of global functions to add to the SConscript name space
# that end up calling corresponding methods or Builders in the
# DefaultEnvironment().
GlobalDefaultEnvironmentFunctions = [
# Methods from the SConsEnvironment class, above.
'Default',
'EnsurePythonVersion',
'EnsureSConsVersion',
'Exit',
'Export',
'GetLaunchDir',
'Help',
'Import',
#'SConscript', is handled separately, below.
'SConscriptChdir',
# Methods from the Environment.Base class.
'AddPostAction',
'AddPreAction',
'Alias',
'AlwaysBuild',
'BuildDir',
'CacheDir',
'Clean',
#The Command() method is handled separately, below.
'Decider',
'Depends',
'Dir',
'NoClean',
'NoCache',
'Entry',
'Execute',
'File',
'FindFile',
'FindInstalledFiles',
'FindSourceFiles',
'Flatten',
'GetBuildPath',
'Glob',
'Ignore',
'Install',
'InstallAs',
'InstallVersionedLib',
'Literal',
'Local',
'ParseDepends',
'Precious',
'PyPackageDir',
'Repository',
'Requires',
'SConsignFile',
'SideEffect',
'SourceCode',
'SourceSignatures',
'Split',
'Tag',
'TargetSignatures',
'Value',
'VariantDir',
]
GlobalDefaultBuilders = [
# Supported builders.
'CFile',
'CXXFile',
'DVI',
'Jar',
'Java',
'JavaH',
'Library',
'LoadableModule',
'M4',
'MSVSProject',
'Object',
'PCH',
'PDF',
'PostScript',
'Program',
'RES',
'RMIC',
'SharedLibrary',
'SharedObject',
'StaticLibrary',
'StaticObject',
'Tar',
'TypeLibrary',
'Zip',
'Package',
]
for name in GlobalDefaultEnvironmentFunctions + GlobalDefaultBuilders:
exec ("%s = _SConscript.DefaultEnvironmentCall(%s)" % (name, repr(name)))
del name
# There are a handful of variables that used to live in the
# Script/SConscript.py module that some SConscript files out there were
# accessing directly as SCons.Script.SConscript.*. The problem is that
# "SConscript" in this namespace is no longer a module, it's a global
# function call--or more precisely, an object that implements a global
# function call through the default Environment. Nevertheless, we can
# maintain backwards compatibility for SConscripts that were reaching in
# this way by hanging some attributes off the "SConscript" object here.
SConscript = _SConscript.DefaultEnvironmentCall('SConscript')
# Make SConscript look enough like the module it used to be so
# that pychecker doesn't barf.
SConscript.__name__ = 'SConscript'
SConscript.Arguments = ARGUMENTS
SConscript.ArgList = ARGLIST
SConscript.BuildTargets = BUILD_TARGETS
SConscript.CommandLineTargets = COMMAND_LINE_TARGETS
SConscript.DefaultTargets = DEFAULT_TARGETS
# The global Command() function must be handled differently than the
# global functions for other construction environment methods because
# we want people to be able to use Actions that must expand $TARGET
# and $SOURCE later, when (and if) the Action is invoked to build
# the target(s). We do this with the subst=1 argument, which creates
# a DefaultEnvironmentCall instance that wraps up a normal default
# construction environment that performs variable substitution, not a
# proxy that doesn't.
#
# There's a flaw here, though, because any other $-variables on a command
# line will *also* be expanded, each to a null string, but that should
# only be a problem in the unusual case where someone was passing a '$'
# on a command line and *expected* the $ to get through to the shell
# because they were calling Command() and not env.Command()... This is
# unlikely enough that we're going to leave this as is and cross that
# bridge if someone actually comes to it.
Command = _SConscript.DefaultEnvironmentCall('Command', subst=1)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
[] |
[] |
[
"SCONSFLAGS"
] |
[]
|
["SCONSFLAGS"]
|
python
| 1 | 0 | |
mindspore/profiler/profiling.py
|
# Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""Profiling api file."""
import os
import re
import stat
import time
import json
from enum import Enum
from mindspore import log as logger, context
from mindspore.communication.management import GlobalComm, release, get_rank
import mindspore._c_expression as c_expression
from mindspore.dataset.core.config import _stop_dataset_profiler
from mindspore.profiler.common.exceptions.exceptions import ProfilerFileNotFoundException, \
ProfilerIOException, ProfilerException, ProfilerRawFileException
from mindspore.profiler.common.util import get_file_names, fwrite_format
from mindspore.profiler.common.validator.validate_path import \
validate_and_normalize_path
from mindspore.profiler.parser.aicpu_data_parser import DataPreProcessParser
from mindspore.profiler.parser.framework_parser import FrameworkParser
from mindspore.profiler.parser.hwts_log_parser import HWTSLogParser
from mindspore.profiler.parser.integrator import Integrator
from mindspore.profiler.parser.integrator import GpuTimelineGenerator, AscendTimelineGenerator
from mindspore.profiler.parser.memory_usage_parser import MemoryUsageParser
from mindspore.profiler.parser.minddata_parser import MinddataParser
from mindspore.profiler.parser.minddata_analyzer import MinddataProfilingAnalyzer
from mindspore.profiler.parser.flops_parser import FlopsParser
from mindspore.profiler.parser.minddata_pipeline_parser import \
MinddataPipelineParser
from mindspore.profiler.parser.optime_parser import OPComputeTimeParser
from mindspore.profiler.parser.step_trace_parser import GpuStepTraceParser, AscendStepTraceParser
from mindspore.nn.cell import Cell
INIT_OP_NAME = 'Default/InitDataSetQueue'
class ProfileOption(Enum):
"""
Profile Option Enum which be used in Profiler.profile.
"""
trainable_parameters = 0
class Profiler:
"""
Performance profiling API.
This API enables MindSpore users to profile the performance of neural network.
Profiler supports Ascend and GPU, both of them are used in the same way,
but only output_path in args works on GPU.
Args:
output_path (str): Output data path.
optypes_not_deal (str): (Ascend only) Op type names, determine the data of which optype should be collected
and analysed,will deal with all op if null; Different op types should be separated by comma.
ascend_job_id (str): (Ascend only) The directory where the profiling files to be parsed are located;
This parameter is used to support offline parsing.
Examples:
>>> import numpy as np
>>> from mindspore import nn, context
>>> from mindspore.train import Model
>>> import mindspore.dataset as ds
>>> from mindspore.profiler import Profiler
>>>
>>>
>>> class Net(nn.Cell):
... def __init__(self):
... super(Net, self).__init__()
... self.fc = nn.Dense(2,2)
... def construct(self, x):
... return self.fc(x)
>>>
>>> def generator():
... for i in range(2):
... yield (np.ones([2, 2]).astype(np.float32), np.ones([2]).astype(np.int32))
>>>
>>> def train(net):
... optimizer = nn.Momentum(net.trainable_params(), 1, 0.9)
... loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
... data = ds.GeneratorDataset(generator, ["data", "label"])
... model = Model(net, loss, optimizer)
... model.train(1, data)
>>>
>>> if __name__ == '__main__':
... # If the device_target is GPU, set the device_target to "GPU"
... context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
...
... # Init Profiler
... # Note that the Profiler should be initialized after context.set_context and before model.train
... # If you are running in parallel mode on Ascend, the Profiler should be initialized before HCCL
... # initialized.
... profiler = Profiler()
...
... # Train Model
... net = Net()
... train(net)
...
... # Profiler end
... profiler.analyse()
"""
_hwts_output_filename_target = "output_format_data_hwts_"
_opcompute_output_filename_target = "output_op_compute_time_"
_aicpu_op_output_filename_target = "output_data_preprocess_aicpu_"
def __init__(self, **kwargs):
# get device_id and device_target
self._get_devid_and_devtarget()
self._get_output_path(kwargs)
os.environ['PROFILING_MODE'] = 'true'
os.environ['MINDDATA_PROFILING_DIR'] = self._output_path
if self._device_target:
CPUProfiler = c_expression.CPUProfiler
self._cpu_profiler = CPUProfiler.get_instance()
self._cpu_profiler.init(self._output_path)
self._cpu_profiler.step_profiling_enable(True)
if self._device_target and self._device_target == "GPU":
GPUProfiler = c_expression.GPUProfiler
self._gpu_profiler = GPUProfiler.get_instance()
self._gpu_profiler.init(self._output_path)
self._gpu_profiler.step_profiling_enable(True)
if GlobalComm.WORLD_COMM_GROUP == "nccl_world_group":
self._dev_id = str(get_rank())
os.environ['DEVICE_ID'] = self._dev_id
if kwargs:
logger.warning("Params not be supported yet on GPU.")
elif self._device_target and self._device_target == "Ascend":
optypes_not_deal = kwargs.pop("optypes_not_deal", "Variable")
if not isinstance(optypes_not_deal, str):
raise TypeError("The parameter optypes_not_deal must be str.")
job_dir = kwargs.pop("ascend_job_id", "")
if job_dir:
job_dir = validate_and_normalize_path(job_dir)
if not os.path.exists(job_dir):
msg = f"Invalid ascend_job_id: {job_dir}, Please pass the absolute path of the JOB dir"
logger.error(msg)
raise ValueError(msg)
self._output_path, _ = os.path.split(job_dir)
if kwargs:
logger.warning("There are invalid params which don't work.")
os.environ['DEVICE_ID'] = self._dev_id
fp_point = os.environ.get("PROFILING_FP_START", "")
bp_point = os.environ.get("PROFILING_BP_END", "")
profiling_options = {
"output": self._output_path,
"fp_point": fp_point,
"bp_point": bp_point,
"training_trace": "on",
"task_trace": "on",
"aic_metrics": "PipeUtilization",
"aicpu": "on"
}
profiling_options = json.dumps(profiling_options)
# Characters longer than 2048 are ignored, resulting in profiling option resolution errors
if len(profiling_options) > 2048:
msg = "The parameter length exceeds the limit (2048), please input valid parameters."
logger.error(msg)
raise ValueError(msg)
# use context interface to open profiling, for the new mindspore version(after 2020.5.21)
context.set_context(enable_profiling=True, profiling_options=profiling_options)
base_profiling_container_path = os.path.join(self._output_path, "container")
container_path = os.path.join(base_profiling_container_path, self._dev_id)
data_path = os.path.join(container_path, "data")
data_path = validate_and_normalize_path(data_path)
if not os.path.exists(data_path):
os.makedirs(data_path, exist_ok=True)
self._filt_optype_names = optypes_not_deal.split(",") if optypes_not_deal else []
# add job id env through user input later
self._job_id_env = 0
self._start_time = int(time.time() * 10000000)
logger.info("Profiling: profiling start time: %d", self._start_time)
def analyse(self):
"""
Collect and analyse performance data, called after training or during training. The example shows above.
"""
self._cpu_profiler.stop()
_stop_dataset_profiler()
if self._device_target and self._device_target == "GPU":
self._gpu_analyse()
elif self._device_target and self._device_target == "Ascend":
self._ascend_analyse()
def _ascend_analyse(self):
"""Collect and analyse ascend performance data"""
release()
job_id = self._get_profiling_job_id()
logger.info("Profiling: job id is %s ", job_id)
source_path = os.path.join(self._output_path, job_id)
# parse hwts.log.data.45.dev file, and get task profiling data
hwts_output_filename = self._hwts_output_filename_target + self._dev_id + ".txt"
hwts_output_filename = os.path.join(self._output_path, hwts_output_filename)
source_path = validate_and_normalize_path(source_path)
hwts_output_filename = validate_and_normalize_path(hwts_output_filename)
hwtslog_parser = HWTSLogParser(source_path, hwts_output_filename)
hwtslog_parser.execute()
# parse Framework file, and get the relation of op and tasks
framework_parser = FrameworkParser(job_id, self._dev_id, self._output_path)
framework_parser.parse()
op_task_dict = framework_parser.to_task_id_full_op_name_dict()
if not op_task_dict:
logger.error("Profiling: fail to parse framework files.")
return
# get op compute time from hwts data and framework data, write output_op_compute_time.txt
opcompute_output_filename = self._opcompute_output_filename_target + self._dev_id + ".txt"
opcompute_output_filename = os.path.join(self._output_path, opcompute_output_filename)
opcompute_output_filename = validate_and_normalize_path(opcompute_output_filename)
optime_parser = OPComputeTimeParser(
hwts_output_filename, opcompute_output_filename,
op_task_dict, self._output_path, self._dev_id
)
optime_parser.execute()
# parse DATA_PREPROCESS.dev.AICPU file, write output_data_preprocess_aicpu_x.txt
output_data_preprocess_aicpu = self._aicpu_op_output_filename_target + self._dev_id + ".txt"
output_data_preprocess_aicpu = os.path.join(self._output_path, output_data_preprocess_aicpu)
output_data_preprocess_aicpu = validate_and_normalize_path(output_data_preprocess_aicpu)
aicpu_data_parser = DataPreProcessParser(source_path, output_data_preprocess_aicpu)
aicpu_data_parser.execute()
# get op FLOPs from aicore.data.x.slice.0 file, and compute FLOPS, write output_op_flops_x.txt
flops_parser = FlopsParser(source_path, self._output_path, op_task_dict, self._dev_id)
flops_parser.execute()
# Parsing minddata AICPU profiling
MinddataParser.execute(source_path, self._output_path, self._dev_id)
# parse minddata pipeline operator and queue
try:
pipeline_parser = MinddataPipelineParser(self._output_path, self._dev_id, self._output_path)
pipeline_parser.parse()
except ProfilerException as err:
logger.warning(err.message)
# Analyze minddata information
try:
md_analyzer = MinddataProfilingAnalyzer(self._output_path, self._device_target, self._dev_id,
self._output_path)
md_analyzer.analyze()
except ProfilerException as err:
logger.warning(err.message)
# analyse op compute time info
try:
self._analyser_op_info()
except ProfilerException as err:
logger.warning(err.message)
# analyse step trace info
points = None
try:
points = self._analyse_step_trace(source_path, framework_parser)
except ProfilerException as err:
logger.warning(err.message)
# analyse timeline info
try:
self._analyse_timeline(aicpu_data_parser, optime_parser, source_path)
except (ProfilerIOException, ProfilerFileNotFoundException, RuntimeError) as err:
logger.warning('Fail to write timeline data: %s', err)
# analyse memory usage info
try:
self._analyse_memory_usage(points)
except (ProfilerIOException, ProfilerFileNotFoundException, ProfilerRawFileException) as err:
logger.warning(err.message)
os.environ['PROFILING_MODE'] = str("false")
context.set_context(enable_profiling=False)
def _gpu_analyse(self):
"""Collect and analyse gpu performance data"""
self._dev_id = context.get_context("device_id")
if GlobalComm.WORLD_COMM_GROUP == "nccl_world_group":
self._dev_id = str(get_rank())
self._gpu_profiler.stop()
timeline_generator = self._generate_timeline()
# parse minddata pipeline operator and queue for GPU
try:
pipeline_parser = MinddataPipelineParser(self._output_path, self._dev_id, self._output_path)
pipeline_parser.parse()
except ProfilerException as err:
logger.warning(err.message)
# Analyze minddata information
try:
md_analyzer = MinddataProfilingAnalyzer(self._output_path, self._device_target, self._dev_id,
self._output_path)
md_analyzer.analyze()
except ProfilerException as err:
logger.warning(err.message)
# analyse step trace info
try:
self._analyse_step_trace(is_training_mode_flag=timeline_generator.check_op_name('Gradients'))
except ProfilerException as err:
logger.warning(err.message)
os.environ['PROFILING_MODE'] = str("false")
logger.warning(
'\nMemory Usage is not supported on GPU currently.\n'
'Please running on Ascend if you would like to see memory analysis, '
'otherwise, this warning can be ignored.'
)
def _analyse_step_trace(self, source_path=None, framework_parser=None, is_training_mode_flag=True):
"""
Analyse step trace data and save the result.
Args:
source_path (str): The directory that contains the step trace original data.
framework_parser (FrameworkParser): The framework parse instance.
is_training_mode_flag (bool): Whether in training mode or not.
"""
logger.info("Begin to parse step trace.")
# construct output path
step_trace_intermediate_file_path = os.path.join(
self._output_path,
f'step_trace_raw_{self._dev_id}_detail_time.csv'
)
point_info_file_path = os.path.join(
self._output_path,
'step_trace_point_info.json'
)
step_trace_intermediate_file_path = validate_and_normalize_path(step_trace_intermediate_file_path)
point_info_file_path = validate_and_normalize_path(point_info_file_path)
if self._device_target and self._device_target == 'GPU':
input_file_path = os.path.join(
self._output_path,
f'step_trace_profiling_{self._dev_id}.txt'
)
parser = GpuStepTraceParser(input_dir=input_file_path,
output_file_path=step_trace_intermediate_file_path,
is_training_mode=is_training_mode_flag)
parser.parse_and_save()
point_info = parser.record_point_info(input_file_path, point_info_file_path)
else:
# whether keep the first step
skip_first_step_flag = framework_parser.check_op_name(INIT_OP_NAME)
point_info = framework_parser.point_info
# recognize inference or training mode
is_traning_mode_flag = framework_parser.check_op_name("Gradients")
# parser the step trace files and save the result to disk
source_path = validate_and_normalize_path(source_path)
parser = AscendStepTraceParser(input_dir=source_path,
output_file_path=step_trace_intermediate_file_path,
job_id=self._job_id_env,
skip_first_step=skip_first_step_flag,
is_training_mode=is_traning_mode_flag)
parser.update_tag_op_type_map(point_info)
parser.parse_and_save()
point_info = parser.record_point_info(point_info, point_info_file_path)
# print parser result
parser.show()
logger.info("Finish saving the intermediate result: %s", step_trace_intermediate_file_path)
logger.info("The point info is: %s", point_info)
return point_info
def _analyse_timeline(self, aicpu_parser, optime_parser, source_path):
"""
Analyse and parse timeline info.
Args:
aicpu_parser (DataPreProcessParser): The parser instance for AI CPU operator
execution time calculation.
optime_parser (OPComputeTimeParserParser): The parser instance for AI Core
operator execution time calculation.
"""
timeline_analyser = AscendTimelineGenerator(self._output_path, self._dev_id)
# Get framework info
integrator = Integrator(self._output_path, self._dev_id)
aicore_detail_data = integrator.get_aicore_detail_data()
aicore_detail_data_size = len(aicore_detail_data)
col_names = ['op_name', 'op_type', 'avg_execution_time', 'subgraph',
'full_op_name', 'op_info']
framework_info = {
'col_name': col_names,
'object': aicore_detail_data,
'size': aicore_detail_data_size
}
all_reduce_info = integrator.query_for_all_reduce()
# Get timeline info
logger.info('Start writing timeline info...')
logger.info('Warm Prompt: It could take a few minutes if you are training '
'with a complex network or more than 10 steps.')
# Add info into timeline, such as AI CPU, AllReduce, framework info.
aicpu_info = aicpu_parser.query_aicpu_data()
min_cycle_counter = min(aicpu_parser.min_cycle_counter, optime_parser.min_cycle_counter)
timeline_analyser.init_timeline(all_reduce_info, framework_info, aicpu_info,
min_cycle_counter, source_path)
size_limit = 100 * 1024 * 1024 # 100MB
timeline_analyser.write_timeline(size_limit)
timeline_analyser.write_timeline_summary()
def _generate_timeline(self):
"""Used for gpu, generate timeline info, write to json format file."""
try:
size_limit = 100 * 1024 * 1024 # 100MB
timeline_generator = GpuTimelineGenerator(self._output_path, self._dev_id)
timeline_generator.init_timeline()
timeline_generator.write_timeline(size_limit)
timeline_generator.write_timeline_summary()
return timeline_generator
except (ProfilerIOException, ProfilerFileNotFoundException, RuntimeError) as err:
logger.warning('Fail to write timeline data: %s', err)
raise RuntimeError('Fail to write timeline data.')
def _analyse_memory_usage(self, points):
"""Analyse memory usage data."""
integrator = Integrator(self._output_path, self._dev_id)
aicore_detail_data = integrator.get_aicore_detail_data()
memory_parser = MemoryUsageParser(self._output_path, self._dev_id)
memory_parser.init_memory_usage_info(aicore_detail_data, points)
memory_parser.write_memory_files()
def _get_profiling_job_id(self):
"""Get profiling job id, which was generated by ada service.
Returns:
str, profiling job id.
"""
job_id = ""
for item in os.listdir(self._output_path):
if item.startswith('JOB'):
path = os.path.join(self._output_path, item)
log_file = get_file_names(path, "host_start.log")
if not log_file:
logger.error("Profiling: job path %s, host_start.log not exist.", path)
continue
training_device_id = log_file[0].split('.')[-1]
if self._dev_id == training_device_id:
log_file = os.path.join(path, log_file[0])
job_start_time = self._parse_host_start_log(log_file)
if not job_start_time:
logger.error("Profiling: job path %s, fail to get job start info.", path)
break
job_id = item
if self._start_time > int(job_start_time):
logger.info("Profiling: job path %s, start_time %s, training start_time %d.",
path, job_start_time, self._start_time)
break
else:
logger.info("Profiling: job path %s, dev id %s, training device id %s.",
path, training_device_id, self._dev_id)
if not job_id:
msg = "Fail to get profiling job, please check whether job dir was generated, " \
"or may be the device id from job dir dismatch the device_id in current process."
raise RuntimeError(msg)
return job_id
def _parse_host_start_log(self, input_file):
"""
Parse host start log file, get the start time of the job.
Args:
input_file (str): The file path of the host start log file.
Returns:
str, job start time.
"""
job_start_time = ""
with open(input_file) as f:
for line in f.readlines():
if "clock_realtime" in line:
# 16 means the first digit of the timestamp, len(line)-3 means the last.
job_start_time = line[16:len(line)-3]
return job_start_time
def _analyser_op_info(self):
"""Analyse the operator information."""
integrator = Integrator(self._output_path, self._dev_id)
integrator.integrate()
aicore_type_result = self._query_op_type_info()
detail_file_path = os.path.join(
self._output_path,
'output_op_compute_time_detail_{}.txt'.format(self._dev_id)
)
fwrite_format(detail_file_path, data_source='title:op compute time')
display_names = [
'optype_name', 'compute_time(ms, per-step)',
'called_times(per-step)', 'percent'
]
fwrite_format(detail_file_path, data_source=" ".join(display_names), is_print=True)
fwrite_format(detail_file_path, data_source=aicore_type_result, is_print=True)
op_type_order = [item[0] for item in aicore_type_result]
aicore_detail_result = self._query_op_detail_info(op_type_order)
fwrite_format(detail_file_path, data_source='', is_print=True)
fwrite_format(detail_file_path, data_source='Detail:', is_print=True)
fwrite_format(detail_file_path, data_source=" ".join(aicore_detail_result.get('col_name_detail')),
is_print=True)
fwrite_format(detail_file_path, data_source=aicore_detail_result.get('object'), is_print=True)
def _query_op_type_info(self):
"""
Query AICORE operator type information.
Returns:
list[list], the AICORE operator type and execution time information.
"""
integrator = Integrator(self._output_path, self._dev_id)
return integrator.get_aicore_data()
def _query_op_detail_info(self, op_type_order):
"""
Query AICORE operator detail information.
Args:
op_type_order(list): The name of the op type in order.
Returns:
dict, the AICORE operator detail information.
"""
op_type_condition = {}
if self._filt_optype_names:
op_type_condition['not_in'] = self._filt_optype_names
filter_condition = {
'op_type': op_type_condition,
'is_display_detail': False,
}
integrator = Integrator(self._output_path, self._dev_id)
return integrator.query_and_sort_by_op_type(filter_condition, op_type_order)
def _get_devid_and_devtarget(self):
"""Get device id and target of this training."""
device_target = ""
dev_id = ""
try:
dev_id = str(context.get_context("device_id"))
device_target = context.get_context("device_target")
except ValueError as err:
logger.error("Profiling: fail to get context, %s", err)
if not dev_id or not dev_id.isdigit():
dev_id = os.getenv('DEVICE_ID')
if not dev_id or not dev_id.isdigit():
dev_id = "0"
logger.error("Fail to get DEVICE_ID, use 0 instead.")
if device_target and device_target not in ["Ascend", "GPU"]:
msg = "Profiling: unsupported backend: %s" % device_target
raise RuntimeError(msg)
self._dev_id = dev_id
self._device_target = device_target
def _get_output_path(self, kwargs):
"""Get output path of profiling data."""
current_time = int(time.time())
# to avoid getting different timestamp from different process in multi-card training,
# set the timestamp as exist timestamp if it's difference is less than 6 seconds.
def _select_timestamp(dir_name, re_pattern, input_time):
"""select the timestamp from current_time and exist timestamp."""
timestamp_diff_threshold = 6
exist_timestamp_list = []
select_time = input_time
if not os.path.exists(dir_name):
os.makedirs(dir_name, exist_ok=True)
for file_name in os.listdir(dir_name):
match_res = re_pattern.match(file_name)
if match_res:
exist_timestamp_list.append(int(match_res.group(1)))
if exist_timestamp_list:
time_diff_list = [input_time - timestamp for timestamp in exist_timestamp_list]
min_time_diff = min(time_diff_list)
if min_time_diff <= timestamp_diff_threshold:
select_time = exist_timestamp_list[time_diff_list.index(min_time_diff)]
return select_time
if "output_path" not in kwargs:
selected_timestamp = _select_timestamp(os.getcwd(), re.compile(r'data-(\d+)'), current_time)
output_path = f"data-{selected_timestamp}"
self._output_path = validate_and_normalize_path(output_path)
else:
output_path = kwargs.pop("output_path")
self._output_path = validate_and_normalize_path(output_path)
selected_timestamp = _select_timestamp(self._output_path,
re.compile(r'profiler-(\d+)'), current_time)
self._output_path = os.path.join(self._output_path, f"profiler-{selected_timestamp}")
if not os.path.exists(self._output_path):
os.makedirs(self._output_path, exist_ok=True)
os.chmod(self._output_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
else:
logger.warning("The target dir already exists. "
"There may be some old profiling data, and they will be rewrote in the end.")
@staticmethod
def profile(network=None, profile_option=None):
"""
Get the number of trainable parameters in the training network.
Args:
network (Cell): The training network.
profile_option (ProfileOption): The profile option.
Returns:
dict, the key is the option name, the value is the result of option.
"""
result = dict()
if not profile_option:
raise ValueError("The parameter profile_option must pass a value using ProfileOption.")
if profile_option == ProfileOption.trainable_parameters:
if not isinstance(network, Cell):
msg = "Profiling: The network should be an object of nn.Cell"
raise ValueError(msg)
param_nums = len(network.parameters_dict())
result = {"trainable_parameters": param_nums}
else:
raise ValueError("Wrong options.")
return result
|
[] |
[] |
[
"PROFILING_FP_START",
"PROFILING_BP_END",
"PROFILING_MODE",
"MINDDATA_PROFILING_DIR",
"DEVICE_ID"
] |
[]
|
["PROFILING_FP_START", "PROFILING_BP_END", "PROFILING_MODE", "MINDDATA_PROFILING_DIR", "DEVICE_ID"]
|
python
| 5 | 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', 'makewiki.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 | |
src/cmd/go/go_test.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main_test
import (
"bytes"
"fmt"
"go/format"
"internal/race"
"internal/testenv"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"testing"
"time"
)
var (
canRun = true // whether we can run go or ./testgo
canRace = false // whether we can run the race detector
canCgo = false // whether we can use cgo
exeSuffix string // ".exe" on Windows
skipExternal = false // skip external tests
)
func init() {
switch runtime.GOOS {
case "android", "nacl":
canRun = false
case "darwin":
switch runtime.GOARCH {
case "arm", "arm64":
canRun = false
}
case "linux":
switch runtime.GOARCH {
case "arm":
// many linux/arm machines are too slow to run
// the full set of external tests.
skipExternal = true
case "mips", "mipsle", "mips64", "mips64le":
// Also slow.
skipExternal = true
if testenv.Builder() != "" {
// On the builders, skip the cmd/go
// tests. They're too slow and already
// covered by other ports. There's
// nothing os/arch specific in the
// tests.
canRun = false
}
}
case "freebsd":
switch runtime.GOARCH {
case "arm":
// many freebsd/arm machines are too slow to run
// the full set of external tests.
skipExternal = true
canRun = false
}
case "windows":
exeSuffix = ".exe"
}
}
// testGOROOT is the GOROOT to use when running testgo, a cmd/go binary
// build from this process's current GOROOT, but run from a different
// (temp) directory.
var testGOROOT string
var testCC string
// The TestMain function creates a go command for testing purposes and
// deletes it after the tests have been run.
func TestMain(m *testing.M) {
if canRun {
args := []string{"build", "-tags", "testgo", "-o", "testgo" + exeSuffix}
if race.Enabled {
args = append(args, "-race")
}
out, err := exec.Command("go", args...).CombinedOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out)
os.Exit(2)
}
out, err = exec.Command("go", "env", "GOROOT").CombinedOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "could not find testing GOROOT: %v\n%s", err, out)
os.Exit(2)
}
testGOROOT = strings.TrimSpace(string(out))
out, err = exec.Command("go", "env", "CC").CombinedOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "could not find testing CC: %v\n%s", err, out)
os.Exit(2)
}
testCC = strings.TrimSpace(string(out))
if out, err := exec.Command("./testgo"+exeSuffix, "env", "CGO_ENABLED").Output(); err != nil {
fmt.Fprintf(os.Stderr, "running testgo failed: %v\n", err)
canRun = false
} else {
canCgo, err = strconv.ParseBool(strings.TrimSpace(string(out)))
if err != nil {
fmt.Fprintf(os.Stderr, "can't parse go env CGO_ENABLED output: %v\n", strings.TrimSpace(string(out)))
}
}
switch runtime.GOOS {
case "linux", "darwin", "freebsd", "windows":
// The race detector doesn't work on Alpine Linux:
// golang.org/issue/14481
canRace = canCgo && runtime.GOARCH == "amd64" && !isAlpineLinux()
}
}
// Don't let these environment variables confuse the test.
os.Unsetenv("GOBIN")
os.Unsetenv("GOPATH")
os.Unsetenv("GIT_ALLOW_PROTOCOL")
if home, ccacheDir := os.Getenv("HOME"), os.Getenv("CCACHE_DIR"); home != "" && ccacheDir == "" {
// On some systems the default C compiler is ccache.
// Setting HOME to a non-existent directory will break
// those systems. Set CCACHE_DIR to cope. Issue 17668.
os.Setenv("CCACHE_DIR", filepath.Join(home, ".ccache"))
}
os.Setenv("HOME", "/test-go-home-does-not-exist")
r := m.Run()
if canRun {
os.Remove("testgo" + exeSuffix)
}
os.Exit(r)
}
func isAlpineLinux() bool {
if runtime.GOOS != "linux" {
return false
}
fi, err := os.Lstat("/etc/alpine-release")
return err == nil && fi.Mode().IsRegular()
}
// The length of an mtime tick on this system. This is an estimate of
// how long we need to sleep to ensure that the mtime of two files is
// different.
// We used to try to be clever but that didn't always work (see golang.org/issue/12205).
var mtimeTick time.Duration = 1 * time.Second
// Manage a single run of the testgo binary.
type testgoData struct {
t *testing.T
temps []string
wd string
env []string
tempdir string
ran bool
inParallel bool
stdout, stderr bytes.Buffer
}
// testgo sets up for a test that runs testgo.
func testgo(t *testing.T) *testgoData {
testenv.MustHaveGoBuild(t)
if skipExternal {
t.Skip("skipping external tests on %s/%s", runtime.GOOS, runtime.GOARCH)
}
return &testgoData{t: t}
}
// must gives a fatal error if err is not nil.
func (tg *testgoData) must(err error) {
if err != nil {
tg.t.Fatal(err)
}
}
// check gives a test non-fatal error if err is not nil.
func (tg *testgoData) check(err error) {
if err != nil {
tg.t.Error(err)
}
}
// parallel runs the test in parallel by calling t.Parallel.
func (tg *testgoData) parallel() {
if tg.ran {
tg.t.Fatal("internal testsuite error: call to parallel after run")
}
if tg.wd != "" {
tg.t.Fatal("internal testsuite error: call to parallel after cd")
}
for _, e := range tg.env {
if strings.HasPrefix(e, "GOROOT=") || strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
val := e[strings.Index(e, "=")+1:]
if strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata") {
tg.t.Fatalf("internal testsuite error: call to parallel with testdata in environment (%s)", e)
}
}
}
tg.inParallel = true
tg.t.Parallel()
}
// pwd returns the current directory.
func (tg *testgoData) pwd() string {
wd, err := os.Getwd()
if err != nil {
tg.t.Fatalf("could not get working directory: %v", err)
}
return wd
}
// cd changes the current directory to the named directory. Note that
// using this means that the test must not be run in parallel with any
// other tests.
func (tg *testgoData) cd(dir string) {
if tg.inParallel {
tg.t.Fatal("internal testsuite error: changing directory when running in parallel")
}
if tg.wd == "" {
tg.wd = tg.pwd()
}
abs, err := filepath.Abs(dir)
tg.must(os.Chdir(dir))
if err == nil {
tg.setenv("PWD", abs)
}
}
// sleep sleeps for one tick, where a tick is a conservative estimate
// of how long it takes for a file modification to get a different
// mtime.
func (tg *testgoData) sleep() {
time.Sleep(mtimeTick)
}
// setenv sets an environment variable to use when running the test go
// command.
func (tg *testgoData) setenv(name, val string) {
if tg.inParallel && (name == "GOROOT" || name == "GOPATH" || name == "GOBIN") && (strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata")) {
tg.t.Fatalf("internal testsuite error: call to setenv with testdata (%s=%s) after parallel", name, val)
}
tg.unsetenv(name)
tg.env = append(tg.env, name+"="+val)
}
// unsetenv removes an environment variable.
func (tg *testgoData) unsetenv(name string) {
if tg.env == nil {
tg.env = append([]string(nil), os.Environ()...)
}
for i, v := range tg.env {
if strings.HasPrefix(v, name+"=") {
tg.env = append(tg.env[:i], tg.env[i+1:]...)
break
}
}
}
func (tg *testgoData) goTool() string {
if tg.wd == "" {
return "./testgo" + exeSuffix
}
return filepath.Join(tg.wd, "testgo"+exeSuffix)
}
// doRun runs the test go command, recording stdout and stderr and
// returning exit status.
func (tg *testgoData) doRun(args []string) error {
if !canRun {
panic("testgoData.doRun called but canRun false")
}
if tg.inParallel {
for _, arg := range args {
if strings.HasPrefix(arg, "testdata") || strings.HasPrefix(arg, "./testdata") {
tg.t.Fatal("internal testsuite error: parallel run using testdata")
}
}
}
hasGoroot := false
for _, v := range tg.env {
if strings.HasPrefix(v, "GOROOT=") {
hasGoroot = true
break
}
}
prog := tg.goTool()
if !hasGoroot {
tg.setenv("GOROOT", testGOROOT)
}
tg.t.Logf("running testgo %v", args)
cmd := exec.Command(prog, args...)
tg.stdout.Reset()
tg.stderr.Reset()
cmd.Stdout = &tg.stdout
cmd.Stderr = &tg.stderr
cmd.Env = tg.env
status := cmd.Run()
if tg.stdout.Len() > 0 {
tg.t.Log("standard output:")
tg.t.Log(tg.stdout.String())
}
if tg.stderr.Len() > 0 {
tg.t.Log("standard error:")
tg.t.Log(tg.stderr.String())
}
tg.ran = true
return status
}
// run runs the test go command, and expects it to succeed.
func (tg *testgoData) run(args ...string) {
if status := tg.doRun(args); status != nil {
tg.t.Logf("go %v failed unexpectedly: %v", args, status)
tg.t.FailNow()
}
}
// runFail runs the test go command, and expects it to fail.
func (tg *testgoData) runFail(args ...string) {
if status := tg.doRun(args); status == nil {
tg.t.Fatal("testgo succeeded unexpectedly")
} else {
tg.t.Log("testgo failed as expected:", status)
}
}
// runGit runs a git command, and expects it to succeed.
func (tg *testgoData) runGit(dir string, args ...string) {
cmd := exec.Command("git", args...)
tg.stdout.Reset()
tg.stderr.Reset()
cmd.Stdout = &tg.stdout
cmd.Stderr = &tg.stderr
cmd.Dir = dir
cmd.Env = tg.env
status := cmd.Run()
if tg.stdout.Len() > 0 {
tg.t.Log("git standard output:")
tg.t.Log(tg.stdout.String())
}
if tg.stderr.Len() > 0 {
tg.t.Log("git standard error:")
tg.t.Log(tg.stderr.String())
}
if status != nil {
tg.t.Logf("git %v failed unexpectedly: %v", args, status)
tg.t.FailNow()
}
}
// getStdout returns standard output of the testgo run as a string.
func (tg *testgoData) getStdout() string {
if !tg.ran {
tg.t.Fatal("internal testsuite error: stdout called before run")
}
return tg.stdout.String()
}
// getStderr returns standard error of the testgo run as a string.
func (tg *testgoData) getStderr() string {
if !tg.ran {
tg.t.Fatal("internal testsuite error: stdout called before run")
}
return tg.stderr.String()
}
// doGrepMatch looks for a regular expression in a buffer, and returns
// whether it is found. The regular expression is matched against
// each line separately, as with the grep command.
func (tg *testgoData) doGrepMatch(match string, b *bytes.Buffer) bool {
if !tg.ran {
tg.t.Fatal("internal testsuite error: grep called before run")
}
re := regexp.MustCompile(match)
for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
if re.Match(ln) {
return true
}
}
return false
}
// doGrep looks for a regular expression in a buffer and fails if it
// is not found. The name argument is the name of the output we are
// searching, "output" or "error". The msg argument is logged on
// failure.
func (tg *testgoData) doGrep(match string, b *bytes.Buffer, name, msg string) {
if !tg.doGrepMatch(match, b) {
tg.t.Log(msg)
tg.t.Logf("pattern %v not found in standard %s", match, name)
tg.t.FailNow()
}
}
// grepStdout looks for a regular expression in the test run's
// standard output and fails, logging msg, if it is not found.
func (tg *testgoData) grepStdout(match, msg string) {
tg.doGrep(match, &tg.stdout, "output", msg)
}
// grepStderr looks for a regular expression in the test run's
// standard error and fails, logging msg, if it is not found.
func (tg *testgoData) grepStderr(match, msg string) {
tg.doGrep(match, &tg.stderr, "error", msg)
}
// grepBoth looks for a regular expression in the test run's standard
// output or stand error and fails, logging msg, if it is not found.
func (tg *testgoData) grepBoth(match, msg string) {
if !tg.doGrepMatch(match, &tg.stdout) && !tg.doGrepMatch(match, &tg.stderr) {
tg.t.Log(msg)
tg.t.Logf("pattern %v not found in standard output or standard error", match)
tg.t.FailNow()
}
}
// doGrepNot looks for a regular expression in a buffer and fails if
// it is found. The name and msg arguments are as for doGrep.
func (tg *testgoData) doGrepNot(match string, b *bytes.Buffer, name, msg string) {
if tg.doGrepMatch(match, b) {
tg.t.Log(msg)
tg.t.Logf("pattern %v found unexpectedly in standard %s", match, name)
tg.t.FailNow()
}
}
// grepStdoutNot looks for a regular expression in the test run's
// standard output and fails, logging msg, if it is found.
func (tg *testgoData) grepStdoutNot(match, msg string) {
tg.doGrepNot(match, &tg.stdout, "output", msg)
}
// grepStderrNot looks for a regular expression in the test run's
// standard error and fails, logging msg, if it is found.
func (tg *testgoData) grepStderrNot(match, msg string) {
tg.doGrepNot(match, &tg.stderr, "error", msg)
}
// grepBothNot looks for a regular expression in the test run's
// standard output or stand error and fails, logging msg, if it is
// found.
func (tg *testgoData) grepBothNot(match, msg string) {
if tg.doGrepMatch(match, &tg.stdout) || tg.doGrepMatch(match, &tg.stderr) {
tg.t.Log(msg)
tg.t.Fatalf("pattern %v found unexpectedly in standard output or standard error", match)
}
}
// doGrepCount counts the number of times a regexp is seen in a buffer.
func (tg *testgoData) doGrepCount(match string, b *bytes.Buffer) int {
if !tg.ran {
tg.t.Fatal("internal testsuite error: doGrepCount called before run")
}
re := regexp.MustCompile(match)
c := 0
for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
if re.Match(ln) {
c++
}
}
return c
}
// grepCountBoth returns the number of times a regexp is seen in both
// standard output and standard error.
func (tg *testgoData) grepCountBoth(match string) int {
return tg.doGrepCount(match, &tg.stdout) + tg.doGrepCount(match, &tg.stderr)
}
// creatingTemp records that the test plans to create a temporary file
// or directory. If the file or directory exists already, it will be
// removed. When the test completes, the file or directory will be
// removed if it exists.
func (tg *testgoData) creatingTemp(path string) {
if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) {
tg.t.Fatalf("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path)
}
// If we have changed the working directory, make sure we have
// an absolute path, because we are going to change directory
// back before we remove the temporary.
if tg.wd != "" && !filepath.IsAbs(path) {
path = filepath.Join(tg.pwd(), path)
}
tg.must(os.RemoveAll(path))
tg.temps = append(tg.temps, path)
}
// makeTempdir makes a temporary directory for a run of testgo. If
// the temporary directory was already created, this does nothing.
func (tg *testgoData) makeTempdir() {
if tg.tempdir == "" {
var err error
tg.tempdir, err = ioutil.TempDir("", "gotest")
tg.must(err)
}
}
// tempFile adds a temporary file for a run of testgo.
func (tg *testgoData) tempFile(path, contents string) {
tg.makeTempdir()
tg.must(os.MkdirAll(filepath.Join(tg.tempdir, filepath.Dir(path)), 0755))
bytes := []byte(contents)
if strings.HasSuffix(path, ".go") {
formatted, err := format.Source(bytes)
if err == nil {
bytes = formatted
}
}
tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644))
}
// tempDir adds a temporary directory for a run of testgo.
func (tg *testgoData) tempDir(path string) {
tg.makeTempdir()
if err := os.MkdirAll(filepath.Join(tg.tempdir, path), 0755); err != nil && !os.IsExist(err) {
tg.t.Fatal(err)
}
}
// path returns the absolute pathname to file with the temporary
// directory.
func (tg *testgoData) path(name string) string {
if tg.tempdir == "" {
tg.t.Fatalf("internal testsuite error: path(%q) with no tempdir", name)
}
if name == "." {
return tg.tempdir
}
return filepath.Join(tg.tempdir, name)
}
// mustExist fails if path does not exist.
func (tg *testgoData) mustExist(path string) {
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
tg.t.Fatalf("%s does not exist but should", path)
}
tg.t.Fatalf("%s stat failed: %v", path, err)
}
}
// mustNotExist fails if path exists.
func (tg *testgoData) mustNotExist(path string) {
if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
tg.t.Fatalf("%s exists but should not (%v)", path, err)
}
}
// wantExecutable fails with msg if path is not executable.
func (tg *testgoData) wantExecutable(path, msg string) {
if st, err := os.Stat(path); err != nil {
if !os.IsNotExist(err) {
tg.t.Log(err)
}
tg.t.Fatal(msg)
} else {
if runtime.GOOS != "windows" && st.Mode()&0111 == 0 {
tg.t.Fatalf("binary %s exists but is not executable", path)
}
}
}
// wantArchive fails if path is not an archive.
func (tg *testgoData) wantArchive(path string) {
f, err := os.Open(path)
if err != nil {
tg.t.Fatal(err)
}
buf := make([]byte, 100)
io.ReadFull(f, buf)
f.Close()
if !bytes.HasPrefix(buf, []byte("!<arch>\n")) {
tg.t.Fatalf("file %s exists but is not an archive", path)
}
}
// isStale reports whether pkg is stale, and why
func (tg *testgoData) isStale(pkg string) (bool, string) {
tg.run("list", "-f", "{{.Stale}}:{{.StaleReason}}", pkg)
v := strings.TrimSpace(tg.getStdout())
f := strings.SplitN(v, ":", 2)
if len(f) == 2 {
switch f[0] {
case "true":
return true, f[1]
case "false":
return false, f[1]
}
}
tg.t.Fatalf("unexpected output checking staleness of package %v: %v", pkg, v)
panic("unreachable")
}
// wantStale fails with msg if pkg is not stale.
func (tg *testgoData) wantStale(pkg, reason, msg string) {
stale, why := tg.isStale(pkg)
if !stale {
tg.t.Fatal(msg)
}
if reason == "" && why != "" || !strings.Contains(why, reason) {
tg.t.Errorf("wrong reason for Stale=true: %q, want %q", why, reason)
}
}
// wantNotStale fails with msg if pkg is stale.
func (tg *testgoData) wantNotStale(pkg, reason, msg string) {
stale, why := tg.isStale(pkg)
if stale {
tg.t.Fatal(msg)
}
if reason == "" && why != "" || !strings.Contains(why, reason) {
tg.t.Errorf("wrong reason for Stale=false: %q, want %q", why, reason)
}
}
// cleanup cleans up a test that runs testgo.
func (tg *testgoData) cleanup() {
if tg.wd != "" {
if err := os.Chdir(tg.wd); err != nil {
// We are unlikely to be able to continue.
fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err)
os.Exit(2)
}
}
for _, path := range tg.temps {
tg.check(os.RemoveAll(path))
}
if tg.tempdir != "" {
tg.check(os.RemoveAll(tg.tempdir))
}
}
// failSSH puts an ssh executable in the PATH that always fails.
// This is to stub out uses of ssh by go get.
func (tg *testgoData) failSSH() {
wd, err := os.Getwd()
if err != nil {
tg.t.Fatal(err)
}
fail := filepath.Join(wd, "testdata/failssh")
tg.setenv("PATH", fmt.Sprintf("%v%c%v", fail, filepath.ListSeparator, os.Getenv("PATH")))
}
func TestFileLineInErrorMessages(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("err.go", `package main; import "bar"`)
path := tg.path("err.go")
tg.runFail("run", path)
shortPath := path
if rel, err := filepath.Rel(tg.pwd(), path); err == nil && len(rel) < len(path) {
shortPath = rel
}
tg.grepStderr("^"+regexp.QuoteMeta(shortPath)+":", "missing file:line in error message")
}
func TestProgramNameInCrashMessages(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("triv.go", `package main; func main() {}`)
tg.runFail("build", "-ldflags", "-crash_for_testing", tg.path("triv.go"))
tg.grepStderr(`[/\\]tool[/\\].*[/\\]link`, "missing linker name in error message")
}
func TestBrokenTestsWithoutTestFunctionsAllFail(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.runFail("test", "./testdata/src/badtest/...")
tg.grepBothNot("^ok", "test passed unexpectedly")
tg.grepBoth("FAIL.*badtest/badexec", "test did not run everything")
tg.grepBoth("FAIL.*badtest/badsyntax", "test did not run everything")
tg.grepBoth("FAIL.*badtest/badvar", "test did not run everything")
}
func TestGoBuildDashAInDevBranch(t *testing.T) {
if testing.Short() {
t.Skip("don't rebuild the standard library in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("install", "math") // should be up to date already but just in case
tg.setenv("TESTGO_IS_GO_RELEASE", "0")
tg.run("build", "-v", "-a", "math")
tg.grepStderr("runtime", "testgo build -a math in dev branch DID NOT build runtime, but should have")
// Everything is out of date. Rebuild to leave things in a better state.
tg.run("install", "std")
}
func TestGoBuildDashAInReleaseBranch(t *testing.T) {
if testing.Short() {
t.Skip("don't rebuild the standard library in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("install", "math", "net/http") // should be up to date already but just in case
tg.setenv("TESTGO_IS_GO_RELEASE", "1")
tg.run("install", "-v", "-a", "math")
tg.grepStderr("runtime", "testgo build -a math in release branch DID NOT build runtime, but should have")
// Now runtime.a is updated (newer mtime), so everything would look stale if not for being a release.
tg.run("build", "-v", "net/http")
tg.grepStderrNot("strconv", "testgo build -v net/http in release branch with newer runtime.a DID build strconv but should not have")
tg.grepStderrNot("golang.org/x/net/http2/hpack", "testgo build -v net/http in release branch with newer runtime.a DID build .../golang.org/x/net/http2/hpack but should not have")
tg.grepStderrNot("net/http", "testgo build -v net/http in release branch with newer runtime.a DID build net/http but should not have")
// Everything is out of date. Rebuild to leave things in a better state.
tg.run("install", "std")
}
func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) {
if testing.Short() {
t.Skip("don't rebuild the standard library in short mode")
}
tg := testgo(t)
defer tg.cleanup()
addNL := func(name string) (restore func()) {
data, err := ioutil.ReadFile(name)
if err != nil {
t.Fatal(err)
}
old := data
data = append(data, '\n')
if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil {
t.Fatal(err)
}
tg.sleep()
return func() {
if err := ioutil.WriteFile(name, old, 0666); err != nil {
t.Fatal(err)
}
}
}
tg.setenv("TESTGO_IS_GO_RELEASE", "1")
tg.tempFile("d1/src/p1/p1.go", `package p1`)
tg.setenv("GOPATH", tg.path("d1"))
tg.run("install", "-a", "p1")
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly")
tg.sleep()
// Changing mtime and content of runtime/internal/sys/sys.go
// should have no effect: we're in a release, which doesn't rebuild
// for general mtime or content changes.
sys := runtime.GOROOT() + "/src/runtime/internal/sys/sys.go"
restore := addNL(sys)
defer restore()
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after updating runtime/internal/sys/sys.go")
restore()
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after restoring runtime/internal/sys/sys.go")
// But changing runtime/internal/sys/zversion.go should have an effect:
// that's how we tell when we flip from one release to another.
zversion := runtime.GOROOT() + "/src/runtime/internal/sys/zversion.go"
restore = addNL(zversion)
defer restore()
tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing to new release")
restore()
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after changing back to old release")
addNL(zversion)
tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing again to new release")
tg.run("install", "p1")
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with new release")
// Restore to "old" release.
restore()
tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing to old release after new build")
tg.run("install", "p1")
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release")
// Everything is out of date. Rebuild to leave things in a better state.
tg.run("install", "std")
}
func TestGoListStandard(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.cd(runtime.GOROOT() + "/src")
tg.run("list", "-f", "{{if not .Standard}}{{.ImportPath}}{{end}}", "./...")
stdout := tg.getStdout()
for _, line := range strings.Split(stdout, "\n") {
if strings.HasPrefix(line, "_/") && strings.HasSuffix(line, "/src") {
// $GOROOT/src shows up if there are any .go files there.
// We don't care.
continue
}
if line == "" {
continue
}
t.Errorf("package in GOROOT not listed as standard: %v", line)
}
// Similarly, expanding std should include some of our vendored code.
tg.run("list", "std", "cmd")
tg.grepStdout("golang.org/x/net/http2/hpack", "list std cmd did not mention vendored hpack")
tg.grepStdout("golang.org/x/arch/x86/x86asm", "list std cmd did not mention vendored x86asm")
}
func TestGoInstallCleansUpAfterGoBuild(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.tempFile("src/mycmd/main.go", `package main; func main(){}`)
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src/mycmd"))
doesNotExist := func(file, msg string) {
if _, err := os.Stat(file); err == nil {
t.Fatal(msg)
} else if !os.IsNotExist(err) {
t.Fatal(msg, "error:", err)
}
}
tg.run("build")
tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary")
tg.run("install")
doesNotExist("mycmd"+exeSuffix, "testgo install did not remove command binary")
tg.run("build")
tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (second time)")
// Running install with arguments does not remove the target,
// even in the same directory.
tg.run("install", "mycmd")
tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary when run in mycmd")
tg.run("build")
tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (third time)")
// And especially not outside the directory.
tg.cd(tg.path("."))
if data, err := ioutil.ReadFile("src/mycmd/mycmd" + exeSuffix); err != nil {
t.Fatal("could not read file:", err)
} else {
if err := ioutil.WriteFile("mycmd"+exeSuffix, data, 0555); err != nil {
t.Fatal("could not write file:", err)
}
}
tg.run("install", "mycmd")
tg.wantExecutable("src/mycmd/mycmd"+exeSuffix, "testgo install mycmd removed command binary from its source dir when run outside mycmd")
tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary from current dir when run outside mycmd")
}
func TestGoInstallRebuildsStalePackagesInOtherGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("d1/src/p1/p1.go", `package p1
import "p2"
func F() { p2.F() }`)
tg.tempFile("d2/src/p2/p2.go", `package p2
func F() {}`)
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", tg.path("d1")+sep+tg.path("d2"))
tg.run("install", "p1")
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly")
tg.wantNotStale("p2", "", "./testgo list claims p2 is stale, incorrectly")
tg.sleep()
if f, err := os.OpenFile(tg.path("d2/src/p2/p2.go"), os.O_WRONLY|os.O_APPEND, 0); err != nil {
t.Fatal(err)
} else if _, err = f.WriteString(`func G() {}`); err != nil {
t.Fatal(err)
} else {
tg.must(f.Close())
}
tg.wantStale("p2", "newer source file", "./testgo list claims p2 is NOT stale, incorrectly")
tg.wantStale("p1", "stale dependency", "./testgo list claims p1 is NOT stale, incorrectly")
tg.run("install", "p1")
tg.wantNotStale("p2", "", "./testgo list claims p2 is stale after reinstall, incorrectly")
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after reinstall, incorrectly")
}
func TestGoInstallDetectsRemovedFiles(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/mypkg/x.go", `package mypkg`)
tg.tempFile("src/mypkg/y.go", `package mypkg`)
tg.tempFile("src/mypkg/z.go", `// +build missingtag
package mypkg`)
tg.setenv("GOPATH", tg.path("."))
tg.run("install", "mypkg")
tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale, incorrectly")
// z.go was not part of the build; removing it is okay.
tg.must(os.Remove(tg.path("src/mypkg/z.go")))
tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale after removing z.go; should not be stale")
// y.go was part of the package; removing it should be detected.
tg.must(os.Remove(tg.path("src/mypkg/y.go")))
tg.wantStale("mypkg", "build ID mismatch", "./testgo list mypkg claims mypkg is NOT stale after removing y.go; should be stale")
}
func TestWildcardMatchesSyntaxErrorDirs(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.tempFile("src/mypkg/x.go", `package mypkg`)
tg.tempFile("src/mypkg/y.go", `pkg mypackage`)
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src/mypkg"))
tg.runFail("list", "./...")
tg.runFail("build", "./...")
tg.runFail("install", "./...")
}
func TestGoListWithTags(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("src/mypkg/x.go", "// +build thetag\n\npackage mypkg\n")
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("./src"))
tg.run("list", "-tags=thetag", "./my...")
tg.grepStdout("mypkg", "did not find mypkg")
}
func TestGoInstallErrorOnCrossCompileToBin(t *testing.T) {
if testing.Short() {
t.Skip("don't install into GOROOT in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("src/mycmd/x.go", `package main
func main() {}`)
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src/mycmd"))
tg.run("build", "mycmd")
goarch := "386"
if runtime.GOARCH == "386" {
goarch = "amd64"
}
tg.setenv("GOOS", "linux")
tg.setenv("GOARCH", goarch)
tg.run("install", "mycmd")
tg.setenv("GOBIN", tg.path("."))
tg.runFail("install", "mycmd")
tg.run("install", "cmd/pack")
}
func TestGoInstallDetectsRemovedFilesInPackageMain(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/mycmd/x.go", `package main
func main() {}`)
tg.tempFile("src/mycmd/y.go", `package main`)
tg.tempFile("src/mycmd/z.go", `// +build missingtag
package main`)
tg.setenv("GOPATH", tg.path("."))
tg.run("install", "mycmd")
tg.wantNotStale("mycmd", "", "./testgo list mypkg claims mycmd is stale, incorrectly")
// z.go was not part of the build; removing it is okay.
tg.must(os.Remove(tg.path("src/mycmd/z.go")))
tg.wantNotStale("mycmd", "", "./testgo list mycmd claims mycmd is stale after removing z.go; should not be stale")
// y.go was part of the package; removing it should be detected.
tg.must(os.Remove(tg.path("src/mycmd/y.go")))
tg.wantStale("mycmd", "build ID mismatch", "./testgo list mycmd claims mycmd is NOT stale after removing y.go; should be stale")
}
func testLocalRun(tg *testgoData, exepath, local, match string) {
out, err := exec.Command(exepath).Output()
if err != nil {
tg.t.Fatalf("error running %v: %v", exepath, err)
}
if !regexp.MustCompile(match).Match(out) {
tg.t.Log(string(out))
tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local)
}
}
func testLocalEasy(tg *testgoData, local string) {
exepath := "./easy" + exeSuffix
tg.creatingTemp(exepath)
tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go"))
testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
}
func testLocalEasySub(tg *testgoData, local string) {
exepath := "./easysub" + exeSuffix
tg.creatingTemp(exepath)
tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go"))
testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
}
func testLocalHard(tg *testgoData, local string) {
exepath := "./hard" + exeSuffix
tg.creatingTemp(exepath)
tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go"))
testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`)
}
func testLocalInstall(tg *testgoData, local string) {
tg.runFail("install", filepath.Join("testdata", local, "easy.go"))
}
func TestLocalImportsEasy(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
testLocalEasy(tg, "local")
}
func TestLocalImportsEasySub(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
testLocalEasySub(tg, "local")
}
func TestLocalImportsHard(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
testLocalHard(tg, "local")
}
func TestLocalImportsGoInstallShouldFail(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
testLocalInstall(tg, "local")
}
const badDirName = `#$%:, &()*;<=>?\^{}`
func copyBad(tg *testgoData) {
if runtime.GOOS == "windows" {
tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName)
}
tg.must(filepath.Walk("testdata/local",
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
var data []byte
data, err = ioutil.ReadFile(path)
if err != nil {
return err
}
newpath := strings.Replace(path, "local", badDirName, 1)
tg.tempFile(newpath, string(data))
return nil
}))
tg.cd(tg.path("."))
}
func TestBadImportsEasy(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
copyBad(tg)
testLocalEasy(tg, badDirName)
}
func TestBadImportsEasySub(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
copyBad(tg)
testLocalEasySub(tg, badDirName)
}
func TestBadImportsHard(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
copyBad(tg)
testLocalHard(tg, badDirName)
}
func TestBadImportsGoInstallShouldFail(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
copyBad(tg)
testLocalInstall(tg, badDirName)
}
func TestInternalPackagesInGOROOTAreRespected(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("build", "-v", "./testdata/testinternal")
tg.grepBoth(`testinternal(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrong error message for testdata/testinternal")
}
func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("build", "-v", "./testdata/testinternal2")
tg.grepBoth(`testinternal2(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrote error message for testdata/testinternal2")
}
func TestRunInternal(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
dir := filepath.Join(tg.pwd(), "testdata")
tg.setenv("GOPATH", dir)
tg.run("run", filepath.Join(dir, "src/run/good.go"))
tg.runFail("run", filepath.Join(dir, "src/run/bad.go"))
tg.grepStderr(`testdata(\/|\\)src(\/|\\)run(\/|\\)bad\.go\:3\:8\: use of internal package not allowed`, "unexpected error for run/bad.go")
}
func testMove(t *testing.T, vcs, url, base, config string) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "-d", url)
tg.run("get", "-d", "-u", url)
switch vcs {
case "svn":
// SVN doesn't believe in text files so we can't just edit the config.
// Check out a different repo into the wrong place.
tg.must(os.RemoveAll(tg.path("src/code.google.com/p/rsc-svn")))
tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk")
tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn")))
default:
path := tg.path(filepath.Join("src", config))
data, err := ioutil.ReadFile(path)
tg.must(err)
data = bytes.Replace(data, []byte(base), []byte(base+"XXX"), -1)
tg.must(ioutil.WriteFile(path, data, 0644))
}
if vcs == "git" {
// git will ask for a username and password when we
// run go get -d -f -u. An empty username and
// password will work. Prevent asking by setting
// GIT_ASKPASS.
tg.creatingTemp("sink" + exeSuffix)
tg.tempFile("src/sink/sink.go", `package main; func main() {}`)
tg.run("build", "-o", "sink"+exeSuffix, "sink")
tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix))
}
tg.runFail("get", "-d", "-u", url)
tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason")
tg.runFail("get", "-d", "-f", "-u", url)
tg.grepStderr("validating server certificate|not found", "go get -d -f -u "+url+" failed for wrong reason")
}
func TestInternalPackageErrorsAreHandled(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("list", "./testdata/testinternal3")
}
func TestInternalCache(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4"))
tg.runFail("build", "p")
tg.grepStderr("internal", "did not fail to build p")
}
func TestMoveGit(t *testing.T) {
testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config")
}
// TODO(rsc): Set up a test case on bitbucket for hg.
// func TestMoveHG(t *testing.T) {
// testMove(t, "hg", "rsc.io/x86/x86asm", "x86", "rsc.io/x86/.hg/hgrc")
// }
// TODO(rsc): Set up a test case on SourceForge (?) for svn.
// func testMoveSVN(t *testing.T) {
// testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-")
// }
func TestImportCommandMatch(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
tg.run("build", "./testdata/importcom/works.go")
}
func TestImportCommentMismatch(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
tg.runFail("build", "./testdata/importcom/wrongplace.go")
tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import")
}
func TestImportCommentSyntaxError(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
tg.runFail("build", "./testdata/importcom/bad.go")
tg.grepStderr("cannot parse import comment", "go build did not mention syntax error")
}
func TestImportCommentConflict(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
tg.runFail("build", "./testdata/importcom/conflict.go")
tg.grepStderr("found import comments", "go build did not mention comment conflict")
}
// cmd/go: custom import path checking should not apply to Go packages without import comment.
func TestIssue10952(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
if _, err := exec.LookPath("git"); err != nil {
t.Skip("skipping because git binary not found")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
const importPath = "github.com/zombiezen/go-get-issue-10952"
tg.run("get", "-d", "-u", importPath)
repoDir := tg.path("src/" + importPath)
tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git")
tg.run("get", "-d", "-u", importPath)
}
func TestIssue16471(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
if _, err := exec.LookPath("git"); err != nil {
t.Skip("skipping because git binary not found")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
tg.must(os.MkdirAll(tg.path("src/rsc.io/go-get-issue-10952"), 0755))
tg.runGit(tg.path("src/rsc.io"), "clone", "https://github.com/zombiezen/go-get-issue-10952")
tg.runFail("get", "-u", "rsc.io/go-get-issue-10952")
tg.grepStderr("rsc.io/go-get-issue-10952 is a custom import path for https://github.com/rsc/go-get-issue-10952, but .* is checked out from https://github.com/zombiezen/go-get-issue-10952", "did not detect updated import path")
}
// Test git clone URL that uses SCP-like syntax and custom import path checking.
func TestIssue11457(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
if _, err := exec.LookPath("git"); err != nil {
t.Skip("skipping because git binary not found")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
const importPath = "rsc.io/go-get-issue-11457"
tg.run("get", "-d", "-u", importPath)
repoDir := tg.path("src/" + importPath)
tg.runGit(repoDir, "remote", "set-url", "origin", "[email protected]:rsc/go-get-issue-11457")
// At this time, custom import path checking compares remotes verbatim (rather than
// just the host and path, skipping scheme and user), so we expect go get -u to fail.
// However, the goal of this test is to verify that gitRemoteRepo correctly parsed
// the SCP-like syntax, and we expect it to appear in the error message.
tg.runFail("get", "-d", "-u", importPath)
want := " is checked out from ssh://[email protected]/rsc/go-get-issue-11457"
if !strings.HasSuffix(strings.TrimSpace(tg.getStderr()), want) {
t.Error("expected clone URL to appear in stderr")
}
}
func TestGetGitDefaultBranch(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
if _, err := exec.LookPath("git"); err != nil {
t.Skip("skipping because git binary not found")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
// This repo has two branches, master and another-branch.
// The another-branch is the default that you get from 'git clone'.
// The go get command variants should not override this.
const importPath = "github.com/rsc/go-get-default-branch"
tg.run("get", "-d", importPath)
repoDir := tg.path("src/" + importPath)
tg.runGit(repoDir, "branch", "--contains", "HEAD")
tg.grepStdout(`\* another-branch`, "not on correct default branch")
tg.run("get", "-d", "-u", importPath)
tg.runGit(repoDir, "branch", "--contains", "HEAD")
tg.grepStdout(`\* another-branch`, "not on correct default branch")
}
func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "syntaxerror")
tg.grepStderr("FAIL", "go test did not say FAIL")
}
func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("list", "...")
tg.grepBoth("badpkg", "go list ... failure does not mention badpkg")
tg.run("list", "m...")
}
func TestRelativeImportsGoTest(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "./testdata/testimport")
}
func TestRelativeImportsGoTestDashI(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-i", "./testdata/testimport")
}
func TestRelativeImportsInCommandLinePackage(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
files, err := filepath.Glob("./testdata/testimport/*.go")
tg.must(err)
tg.run(append([]string{"test"}, files...)...)
}
func TestNonCanonicalImportPaths(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("build", "canonical/d")
tg.grepStderr("package canonical/d", "did not report canonical/d")
tg.grepStderr("imports canonical/b", "did not report canonical/b")
tg.grepStderr("imports canonical/a/: non-canonical", "did not report canonical/a/")
}
func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1"))
tg.runFail("get", "-u", "foo")
// TODO(iant): We should not have to use strconv.Quote here.
// The code in vcs.go should be changed so that it is not required.
quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo"))
quoted = quoted[1 : len(quoted)-1]
tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo")
}
func TestInstallFailsWithNoBuildableFiles(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.setenv("CGO_ENABLED", "0")
tg.runFail("install", "cgotest")
tg.grepStderr("no buildable Go source files", "go install cgotest did not report 'no buildable Go Source files'")
}
func TestRelativeGOBINFail(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("triv.go", `package main; func main() {}`)
tg.setenv("GOBIN", ".")
tg.runFail("install")
tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path")
}
// Test that without $GOBIN set, binaries get installed
// into the GOPATH bin directory.
func TestInstallIntoGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("install", "go-cmd-test")
tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
}
// Issue 12407
func TestBuildOutputToDevNull(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("build", "-o", os.DevNull, "go-cmd-test")
}
func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
gobin := filepath.Join(tg.pwd(), "testdata", "bin")
tg.creatingTemp(gobin)
tg.setenv("GOBIN", gobin)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now()))
tg.sleep()
tg.run("test", "main_test")
tg.run("install", "main_test")
tg.wantNotStale("main_test", "", "after go install, main listed as stale")
tg.run("test", "main_test")
}
// The runtime version string takes one of two forms:
// "go1.X[.Y]" for Go releases, and "devel +hash" at tip.
// Determine whether we are in a released copy by
// inspecting the version.
var isGoRelease = strings.HasPrefix(runtime.Version(), "go1")
// Issue 12690
func TestPackageNotStaleWithTrailingSlash(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// Make sure the packages below are not stale.
tg.run("install", "runtime", "os", "io")
goroot := runtime.GOROOT()
tg.setenv("GOROOT", goroot+"/")
want := ""
if isGoRelease {
want = "standard package in Go release distribution"
}
tg.wantNotStale("runtime", want, "with trailing slash in GOROOT, runtime listed as stale")
tg.wantNotStale("os", want, "with trailing slash in GOROOT, os listed as stale")
tg.wantNotStale("io", want, "with trailing slash in GOROOT, io listed as stale")
}
// With $GOBIN set, binaries get installed to $GOBIN.
func TestInstallIntoGOBIN(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
tg.creatingTemp(gobin)
tg.setenv("GOBIN", gobin)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("install", "go-cmd-test")
tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test")
}
// Issue 11065
func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test")
tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix))
tg.setenv("GOBIN", pkg)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.cd(pkg)
tg.run("install")
tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory")
}
// Without $GOBIN set, installing a program outside $GOPATH should fail
// (there is nowhere to install it).
func TestInstallWithoutDestinationFails(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go")
tg.grepStderr("no install location for .go files listed on command line", "wrong error")
}
// With $GOBIN set, should install there.
func TestInstallToGOBINCommandLinePackage(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
tg.creatingTemp(gobin)
tg.setenv("GOBIN", gobin)
tg.run("install", "testdata/src/go-cmd-test/helloworld.go")
tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld")
}
func TestGoGetNonPkg(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("gobin")
tg.setenv("GOPATH", tg.path("."))
tg.setenv("GOBIN", tg.path("gobin"))
tg.runFail("get", "-d", "golang.org/x/tools")
tg.grepStderr("golang.org/x/tools: no buildable Go source files", "missing error")
tg.runFail("get", "-d", "-u", "golang.org/x/tools")
tg.grepStderr("golang.org/x/tools: no buildable Go source files", "missing error")
tg.runFail("get", "-d", "golang.org/x/tools")
tg.grepStderr("golang.org/x/tools: no buildable Go source files", "missing error")
}
func TestGoGetTestOnlyPkg(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("gopath")
tg.setenv("GOPATH", tg.path("gopath"))
tg.run("get", "golang.org/x/tour/content")
tg.run("get", "-t", "golang.org/x/tour/content")
}
func TestInstalls(t *testing.T) {
if testing.Short() {
t.Skip("don't install into GOROOT in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("gobin")
tg.setenv("GOPATH", tg.path("."))
goroot := runtime.GOROOT()
tg.setenv("GOROOT", goroot)
// cmd/fix installs into tool
tg.run("env", "GOOS")
goos := strings.TrimSpace(tg.getStdout())
tg.setenv("GOOS", goos)
tg.run("env", "GOARCH")
goarch := strings.TrimSpace(tg.getStdout())
tg.setenv("GOARCH", goarch)
fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix
tg.must(os.RemoveAll(fixbin))
tg.run("install", "cmd/fix")
tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool")
tg.must(os.Remove(fixbin))
tg.setenv("GOBIN", tg.path("gobin"))
tg.run("install", "cmd/fix")
tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set")
tg.unsetenv("GOBIN")
// gopath program installs into GOBIN
tg.tempFile("src/progname/p.go", `package main; func main() {}`)
tg.setenv("GOBIN", tg.path("gobin"))
tg.run("install", "progname")
tg.unsetenv("GOBIN")
tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname")
// gopath program installs into GOPATH/bin
tg.run("install", "progname")
tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname")
}
func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", ".")
tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
}
func TestRejectRelativePathsInGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".")
tg.runFail("build", "go-cmd-test")
tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
}
func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", "testdata")
tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
}
// Issue 4104.
func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.run("test", "errors", "errors", "errors", "errors", "errors")
if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") {
t.Error("go test errors errors errors errors errors tested the same package multiple times")
}
}
func TestGoListHasAConsistentOrder(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.run("list", "std")
first := tg.getStdout()
tg.run("list", "std")
if first != tg.getStdout() {
t.Error("go list std ordering is inconsistent")
}
}
func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.run("list", "std")
tg.grepStdoutNot("cmd/", "go list std shows commands")
}
func TestGoListCmdOnlyShowsCommands(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.run("list", "cmd")
out := strings.TrimSpace(tg.getStdout())
for _, line := range strings.Split(out, "\n") {
if !strings.Contains(line, "cmd/") {
t.Error("go list cmd shows non-commands")
break
}
}
}
func TestGoListDedupsPackages(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("list", "xtestonly", "./testdata/src/xtestonly/...")
got := strings.TrimSpace(tg.getStdout())
const want = "xtestonly"
if got != want {
t.Errorf("got %q; want %q", got, want)
}
}
// Issue 4096. Validate the output of unsuccessful go install foo/quxx.
func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.runFail("install", "foo/quxx")
if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 {
t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`)
}
}
func TestGOROOTSearchFailureReporting(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.runFail("install", "foo/quxx")
if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 {
t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`)
}
}
func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
tg.runFail("install", "foo/quxx")
if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 {
t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`)
}
}
// Test (from $GOPATH) annotation is reported for the first GOPATH entry,
func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
tg.runFail("install", "foo/quxx")
if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 {
t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`)
}
}
// but not on the second.
func TestMentionGOPATHNotOnSecondEntry(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
tg.runFail("install", "foo/quxx")
if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 {
t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`)
}
}
func homeEnvName() string {
switch runtime.GOOS {
case "windows":
return "USERPROFILE"
case "plan9":
return "home"
default:
return "HOME"
}
}
func TestDefaultGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("home/go")
tg.setenv(homeEnvName(), tg.path("home"))
tg.run("env", "GOPATH")
tg.grepStdout(regexp.QuoteMeta(tg.path("home/go")), "want GOPATH=$HOME/go")
tg.setenv("GOROOT", tg.path("home/go"))
tg.run("env", "GOPATH")
tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go")
tg.setenv("GOROOT", tg.path("home/go")+"/")
tg.run("env", "GOPATH")
tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go/")
}
func TestDefaultGOPATHGet(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", "")
tg.tempDir("home")
tg.setenv(homeEnvName(), tg.path("home"))
// warn for creating directory
tg.run("get", "-v", "github.com/golang/example/hello")
tg.grepStderr("created GOPATH="+regexp.QuoteMeta(tg.path("home/go"))+"; see 'go help gopath'", "did not create GOPATH")
// no warning if directory already exists
tg.must(os.RemoveAll(tg.path("home/go")))
tg.tempDir("home/go")
tg.run("get", "github.com/golang/example/hello")
tg.grepStderrNot(".", "expected no output on standard error")
// error if $HOME/go is a file
tg.must(os.RemoveAll(tg.path("home/go")))
tg.tempFile("home/go", "")
tg.runFail("get", "github.com/golang/example/hello")
tg.grepStderr(`mkdir .*[/\\]go: .*(not a directory|cannot find the path)`, "expected error because $HOME/go is a file")
}
func TestDefaultGOPATHPrintedSearchList(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", "")
tg.tempDir("home")
tg.setenv(homeEnvName(), tg.path("home"))
tg.runFail("install", "github.com/golang/example/hello")
tg.grepStderr(regexp.QuoteMeta(tg.path("home/go/src/github.com/golang/example/hello"))+`.*from \$GOPATH`, "expected default GOPATH")
}
// Issue 4186. go get cannot be used to download packages to $GOROOT.
// Test that without GOPATH set, go get should fail.
func TestGoGetIntoGOROOT(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
// Fails because GOROOT=GOPATH
tg.setenv("GOPATH", tg.path("."))
tg.setenv("GOROOT", tg.path("."))
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
// Fails because GOROOT=GOPATH after cleaning.
tg.setenv("GOPATH", tg.path(".")+"/")
tg.setenv("GOROOT", tg.path("."))
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
tg.setenv("GOPATH", tg.path("."))
tg.setenv("GOROOT", tg.path(".")+"/")
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
// Fails because GOROOT=$HOME/go so default GOPATH unset.
tg.tempDir("home/go")
tg.setenv(homeEnvName(), tg.path("home"))
tg.setenv("GOPATH", "")
tg.setenv("GOROOT", tg.path("home/go"))
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
tg.setenv(homeEnvName(), tg.path("home")+"/")
tg.setenv("GOPATH", "")
tg.setenv("GOROOT", tg.path("home/go"))
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
tg.setenv(homeEnvName(), tg.path("home"))
tg.setenv("GOPATH", "")
tg.setenv("GOROOT", tg.path("home/go")+"/")
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
}
func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("main.go", `package main
var extern string
func main() {
println(extern)
}`)
tg.run("run", "-ldflags", `-X "main.extern=hello world"`, tg.path("main.go"))
tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`)
}
func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.run("test", "-cpuprofile", "errors.prof", "errors")
tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test")
}
func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test")
}
func TestGoTestMutexprofileLeavesBinaryBehind(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.run("test", "-mutexprofile", "errors.prof", "errors")
tg.wantExecutable("errors.test"+exeSuffix, "go test -mutexprofile did not create errors.test")
}
func TestGoTestMutexprofileDashOControlsBinaryLocation(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.run("test", "-mutexprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
tg.wantExecutable("myerrors.test"+exeSuffix, "go test -mutexprofile -o myerrors.test did not create myerrors.test")
}
func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test")
}
func TestGoTestDashOWritesBinary(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
}
func TestGoTestDashIDashOWritesBinary(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.run("test", "-v", "-i", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
tg.grepBothNot("PASS|FAIL", "test should not have run")
tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
}
// Issue 4568.
func TestSymlinksList(t *testing.T) {
testenv.MustHaveSymlink(t)
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.tempDir("src")
tg.must(os.Symlink(tg.path("."), tg.path("src/dir1")))
tg.tempFile("src/dir1/p.go", "package p")
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src"))
tg.run("list", "-f", "{{.Root}}", "dir1")
if strings.TrimSpace(tg.getStdout()) != tg.path(".") {
t.Error("confused by symlinks")
}
}
// Issue 14054.
func TestSymlinksVendor(t *testing.T) {
testenv.MustHaveSymlink(t)
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.tempDir("gopath/src/dir1/vendor/v")
tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}")
tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v")
tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
tg.setenv("GOPATH", tg.path("gopath"))
tg.cd(tg.path("symdir1"))
tg.run("list", "-f", "{{.Root}}", ".")
if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
t.Error("list confused by symlinks")
}
// All of these should succeed, not die in vendor-handling code.
tg.run("run", "p.go")
tg.run("build")
tg.run("install")
}
// Issue 15201.
func TestSymlinksVendor15201(t *testing.T) {
testenv.MustHaveSymlink(t)
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("gopath/src/x/y/_vendor/src/x")
tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y")))
tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n")
tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor")))
tg.tempFile("gopath/src/x/y/z/z.go", "package z\n")
tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath"))
tg.cd(tg.path("gopath/src"))
tg.run("list", "./...")
}
func TestSymlinksInternal(t *testing.T) {
testenv.MustHaveSymlink(t)
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("gopath/src/dir1/internal/v")
tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}")
tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v")
tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
tg.setenv("GOPATH", tg.path("gopath"))
tg.cd(tg.path("symdir1"))
tg.run("list", "-f", "{{.Root}}", ".")
if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
t.Error("list confused by symlinks")
}
// All of these should succeed, not die in internal-handling code.
tg.run("run", "p.go")
tg.run("build")
tg.run("install")
}
// Issue 4515.
func TestInstallWithTags(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("bin")
tg.tempFile("src/example/a/main.go", `package main
func main() {}`)
tg.tempFile("src/example/b/main.go", `// +build mytag
package main
func main() {}`)
tg.setenv("GOPATH", tg.path("."))
tg.run("install", "-tags", "mytag", "example/a", "example/b")
tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries")
tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries")
tg.must(os.Remove(tg.path("bin/a" + exeSuffix)))
tg.must(os.Remove(tg.path("bin/b" + exeSuffix)))
tg.run("install", "-tags", "mytag", "example/...")
tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries")
tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries")
tg.run("list", "-tags", "mytag", "example/b...")
if strings.TrimSpace(tg.getStdout()) != "example/b" {
t.Error("go list example/b did not find example/b")
}
}
// Issue 4773
func TestCaseCollisions(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src/example/a/pkg")
tg.tempDir("src/example/a/Pkg")
tg.tempDir("src/example/b")
tg.setenv("GOPATH", tg.path("."))
tg.tempFile("src/example/a/a.go", `package p
import (
_ "example/a/pkg"
_ "example/a/Pkg"
)`)
tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`)
tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`)
tg.runFail("list", "example/a")
tg.grepStderr("case-insensitive import collision", "go list example/a did not report import collision")
tg.tempFile("src/example/b/file.go", `package b`)
tg.tempFile("src/example/b/FILE.go", `package b`)
f, err := os.Open(tg.path("src/example/b"))
tg.must(err)
names, err := f.Readdirnames(0)
tg.must(err)
tg.check(f.Close())
args := []string{"list"}
if len(names) == 2 {
// case-sensitive file system, let directory read find both files
args = append(args, "example/b")
} else {
// case-insensitive file system, list files explicitly on command line
args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go"))
}
tg.runFail(args...)
tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision")
}
// Issue 8181.
func TestGoGetDashTIssue8181(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b")
tg.run("list", "...")
tg.grepStdout("x/build/gerrit", "missing expected x/build/gerrit")
}
func TestIssue11307(t *testing.T) {
// go get -u was not working except in checkout directory
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "github.com/rsc/go-get-issue-11307")
tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing
}
func TestShadowingLogic(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
pwd := tg.pwd()
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2"))
// The math in root1 is not "math" because the standard math is.
tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math")
pwdForwardSlash := strings.Replace(pwd, string(os.PathSeparator), "/", -1)
if !strings.HasPrefix(pwdForwardSlash, "/") {
pwdForwardSlash = "/" + pwdForwardSlash
}
// The output will have makeImportValid applies, but we only
// bother to deal with characters we might reasonably see.
for _, r := range " :" {
pwdForwardSlash = strings.Replace(pwdForwardSlash, string(r), "_", -1)
}
want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")"
if strings.TrimSpace(tg.getStdout()) != want {
t.Error("shadowed math is not shadowed; looking for", want)
}
// The foo in root1 is "foo".
tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo")
if strings.TrimSpace(tg.getStdout()) != "(foo) ()" {
t.Error("unshadowed foo is shadowed")
}
// The foo in root2 is not "foo" because the foo in root1 got there first.
tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo")
want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")"
if strings.TrimSpace(tg.getStdout()) != want {
t.Error("shadowed foo is not shadowed; looking for", want)
}
// The error for go install should mention the conflicting directory.
tg.runFail("install", "./testdata/shadow/root2/src/foo")
want = "go install: no install location for " + filepath.Join(pwd, "testdata", "shadow", "root2", "src", "foo") + ": hidden by " + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo")
if strings.TrimSpace(tg.getStderr()) != want {
t.Error("wrong shadowed install error; looking for", want)
}
}
// Only succeeds if source order is preserved.
func TestSourceFileNameOrderPreserved(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go")
}
// Check that coverage analysis works at all.
// Don't worry about the exact numbers but require not 0.0%.
func checkCoverage(tg *testgoData, data string) {
if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) {
tg.t.Error("some coverage results are 0.0%")
}
tg.t.Log(data)
}
func TestCoverageRuns(t *testing.T) {
if testing.Short() {
t.Skip("don't build libraries for coverage in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp")
data := tg.getStdout() + tg.getStderr()
tg.run("test", "-short", "-cover", "strings", "math", "regexp")
data += tg.getStdout() + tg.getStderr()
checkCoverage(tg, data)
}
// Check that coverage analysis uses set mode.
func TestCoverageUsesSetMode(t *testing.T) {
if testing.Short() {
t.Skip("don't build libraries for coverage in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.creatingTemp("testdata/cover.out")
tg.run("test", "-short", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
data := tg.getStdout() + tg.getStderr()
if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
t.Error(err)
} else {
if !bytes.Contains(out, []byte("mode: set")) {
t.Error("missing mode: set")
}
}
checkCoverage(tg, data)
}
func TestCoverageUsesAtomicModeForRace(t *testing.T) {
if testing.Short() {
t.Skip("don't build libraries for coverage in short mode")
}
if !canRace {
t.Skip("skipping because race detector not supported")
}
tg := testgo(t)
defer tg.cleanup()
tg.creatingTemp("testdata/cover.out")
tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
data := tg.getStdout() + tg.getStderr()
if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
t.Error(err)
} else {
if !bytes.Contains(out, []byte("mode: atomic")) {
t.Error("missing mode: atomic")
}
}
checkCoverage(tg, data)
}
func TestCoverageImportMainLoop(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "importmain/test")
tg.grepStderr("not an importable package", "did not detect import main")
tg.runFail("test", "-cover", "importmain/test")
tg.grepStderr("not an importable package", "did not detect import main")
}
func TestPluginNonMain(t *testing.T) {
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
pkg := filepath.Join(wd, "testdata", "testdep", "p2")
tg := testgo(t)
defer tg.cleanup()
tg.runFail("build", "-buildmode=plugin", pkg)
}
func TestTestEmpty(t *testing.T) {
if !canRace {
t.Skip("no race detector")
}
wd, _ := os.Getwd()
testdata := filepath.Join(wd, "testdata")
for _, dir := range []string{"pkg", "test", "xtest", "pkgtest", "pkgxtest", "pkgtestxtest", "testxtest"} {
t.Run(dir, func(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", testdata)
tg.cd(filepath.Join(testdata, "src/empty/"+dir))
tg.run("test", "-cover", "-coverpkg=.", "-race")
})
if testing.Short() {
break
}
}
}
func TestTestRaceInstall(t *testing.T) {
if !canRace {
t.Skip("no race detector")
}
if testing.Short() && testenv.Builder() == "" {
t.Skip("don't rebuild the standard library in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.tempDir("pkg")
pkgdir := tg.path("pkg")
tg.run("install", "-race", "-pkgdir="+pkgdir, "std")
tg.run("test", "-race", "-pkgdir="+pkgdir, "-i", "-v", "empty/pkg")
if tg.getStderr() != "" {
t.Error("go test -i -race: rebuilds cached packages")
}
}
func TestBuildDryRunWithCgo(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("foo.go", `package main
/*
#include <limits.h>
*/
import "C"
func main() {
println(C.INT_MAX)
}`)
tg.run("build", "-n", tg.path("foo.go"))
tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file")
}
func TestCoverageWithCgo(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
for _, dir := range []string{"cgocover", "cgocover2", "cgocover3", "cgocover4"} {
t.Run(dir, func(t *testing.T) {
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "-short", "-cover", dir)
data := tg.getStdout() + tg.getStderr()
checkCoverage(tg, data)
})
}
}
func TestCgoDependsOnSyscall(t *testing.T) {
if testing.Short() {
t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode")
}
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
if !canRace {
t.Skip("skipping because race detector not supported")
}
tg := testgo(t)
defer tg.cleanup()
files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race"))
tg.must(err)
for _, file := range files {
tg.check(os.RemoveAll(file))
}
tg.tempFile("src/foo/foo.go", `
package foo
//#include <stdio.h>
import "C"`)
tg.setenv("GOPATH", tg.path("."))
tg.run("build", "-race", "foo")
}
func TestCgoShowsFullPathNames(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/x/y/dirname/foo.go", `
package foo
import "C"
func f() {`)
tg.setenv("GOPATH", tg.path("."))
tg.runFail("build", "x/y/dirname")
tg.grepBoth("x/y/dirname", "error did not use full path")
}
func TestCgoHandlesWlORIGIN(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/origin/origin.go", `package origin
// #cgo !darwin LDFLAGS: -Wl,-rpath -Wl,$ORIGIN
// void f(void) {}
import "C"
func f() { C.f() }`)
tg.setenv("GOPATH", tg.path("."))
tg.run("build", "origin")
}
func TestCgoPkgConfig(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.run("env", "PKG_CONFIG")
pkgConfig := strings.TrimSpace(tg.getStdout())
if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil {
t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out)
}
// OpenBSD's pkg-config is strict about whitespace and only
// supports backslash-escaped whitespace. It does not support
// quotes, which the normal freedesktop.org pkg-config does
// support. See http://man.openbsd.org/pkg-config.1
tg.tempFile("foo.pc", `
Name: foo
Description: The foo library
Version: 1.0.0
Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world
`)
tg.tempFile("foo.go", `package main
/*
#cgo pkg-config: foo
int value() {
return DEFINED_FROM_PKG_CONFIG;
}
*/
import "C"
import "os"
func main() {
if C.value() != 42 {
println("value() =", C.value(), "wanted 42")
os.Exit(1)
}
}
`)
tg.setenv("PKG_CONFIG_PATH", tg.path("."))
tg.run("run", tg.path("foo.go"))
}
// "go test -c -test.bench=XXX errors" should not hang
func TestIssue6480(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.run("test", "-c", "-test.bench=XXX", "errors")
}
// cmd/cgo: undefined reference when linking a C-library using gccgo
func TestIssue7573(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
if _, err := exec.LookPath("gccgo"); err != nil {
t.Skip("skipping because no gccgo compiler found")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/cgoref/cgoref.go", `
package main
// #cgo LDFLAGS: -L alibpath -lalib
// void f(void) {}
import "C"
func main() { C.f() }`)
tg.setenv("GOPATH", tg.path("."))
tg.run("build", "-n", "-compiler", "gccgo", "cgoref")
tg.grepStderr(`gccgo.*\-L alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`)
}
func TestListTemplateContextFunction(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
v string
want string
}{
{"GOARCH", runtime.GOARCH},
{"GOOS", runtime.GOOS},
{"GOROOT", filepath.Clean(runtime.GOROOT())},
{"GOPATH", os.Getenv("GOPATH")},
{"CgoEnabled", ""},
{"UseAllFiles", ""},
{"Compiler", ""},
{"BuildTags", ""},
{"ReleaseTags", ""},
{"InstallSuffix", ""},
} {
tt := tt
t.Run(tt.v, func(t *testing.T) {
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tmpl := "{{context." + tt.v + "}}"
tg.run("list", "-f", tmpl)
if tt.want == "" {
return
}
if got := strings.TrimSpace(tg.getStdout()); got != tt.want {
t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want)
}
})
}
}
// cmd/go: "go test" should fail if package does not build
func TestIssue7108(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "notest")
}
// cmd/go: go test -a foo does not rebuild regexp.
func TestIssue6844(t *testing.T) {
if testing.Short() {
t.Skip("don't rebuild the standard library in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.creatingTemp("deps.test" + exeSuffix)
tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go")
tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp")
}
func TestBuildDashIInstallsDependencies(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/x/y/foo/foo.go", `package foo
func F() {}`)
tg.tempFile("src/x/y/bar/bar.go", `package bar
import "x/y/foo"
func F() { foo.F() }`)
tg.setenv("GOPATH", tg.path("."))
checkbar := func(desc string) {
tg.sleep()
tg.must(os.Chtimes(tg.path("src/x/y/foo/foo.go"), time.Now(), time.Now()))
tg.sleep()
tg.run("build", "-v", "-i", "x/y/bar")
tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo")
tg.run("build", "-v", "-i", "x/y/bar")
tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo")
}
checkbar("pkg")
tg.creatingTemp("bar" + exeSuffix)
tg.tempFile("src/x/y/bar/bar.go", `package main
import "x/y/foo"
func main() { foo.F() }`)
checkbar("cmd")
}
func TestGoBuildInTestOnlyDirectoryFailsWithAGoodError(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("build", "./testdata/testonly")
tg.grepStderr("no buildable Go", "go build ./testdata/testonly produced unexpected error")
}
func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "-c", "testcycle/p3")
tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error")
tg.runFail("test", "-c", "testcycle/q1")
tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error")
}
func TestGoTestFooTestWorks(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "testdata/standalone_test.go")
}
func TestGoTestFlagsAfterPackage(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags.
tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags.
}
func TestGoTestShowInProgressOnInterrupt(t *testing.T) {
if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
t.Skipf("skipping test on %s - lack of full unix-like signal support", runtime.GOOS)
}
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-v", "testdata/inprogress_interrupt_test.go")
testsInProgress := "tests in progress: TestParallel, TestSerial"
tg.grepStdout(testsInProgress, "tests which haven't completed should be listed in progress")
}
func TestGoTestXtestonlyWorks(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("clean", "-i", "xtestonly")
tg.run("test", "xtestonly")
}
func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-v", "./testdata/norunexample")
tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built")
}
func TestGoGenerateHandlesSimpleCommand(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping because windows has no echo command")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("generate", "./testdata/generate/test1.go")
tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output")
}
func TestGoGenerateHandlesCommandAlias(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping because windows has no echo command")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("generate", "./testdata/generate/test2.go")
tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output")
}
func TestGoGenerateVariableSubstitution(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping because windows has no echo command")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("generate", "./testdata/generate/test3.go")
tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output")
}
func TestGoGenerateRunFlag(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping because windows has no echo command")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go")
tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes")
tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no")
}
func TestGoGenerateEnv(t *testing.T) {
switch runtime.GOOS {
case "plan9", "windows":
t.Skipf("skipping because %s does not have the env command", runtime.GOOS)
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("env.go", "package main\n\n//go:generate env")
tg.run("generate", tg.path("env.go"))
for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} {
tg.grepStdout("^"+v+"=", "go generate environment missing "+v)
}
}
func TestGoGenerateBadImports(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping because windows has no echo command")
}
// This package has an invalid import causing an import cycle,
// but go generate is supposed to still run.
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("generate", "gencycle")
tg.grepStdout("hello world", "go generate gencycle did not run generator")
}
func TestGoGetCustomDomainWildcard(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "-u", "rsc.io/pdf/...")
tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd")
}
func TestGoGetInternalWildcard(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
// used to fail with errors about internal packages
tg.run("get", "github.com/rsc/go-get-issue-11960/...")
}
func TestGoVetWithExternalTests(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.run("install", "cmd/vet")
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("vet", "vetpkg")
tg.grepBoth("missing argument for Printf", "go vet vetpkg did not find missing argument for Printf")
}
func TestGoVetWithTags(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.run("install", "cmd/vet")
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("vet", "-tags", "tagtest", "vetpkg")
tg.grepBoth(`c\.go.*wrong number of args for format`, "go vet vetpkg did not run scan tagged file")
}
func TestGoVetWithFlagsOn(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.run("install", "cmd/vet")
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("vet", "-printf", "vetpkg")
tg.grepBoth("missing argument for Printf", "go vet -printf vetpkg did not find missing argument for Printf")
}
func TestGoVetWithFlagsOff(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.run("install", "cmd/vet")
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("vet", "-printf=false", "vetpkg")
}
// Issue 9767, 19769.
func TestGoGetDotSlashDownload(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("src/rsc.io")
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src/rsc.io"))
tg.run("get", "./pprof_mac_fix")
}
// Issue 13037: Was not parsing <meta> tags in 404 served over HTTPS
func TestGoGetHTTPS404(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
switch runtime.GOOS {
case "darwin", "linux", "freebsd":
default:
t.Skipf("test case does not work on %s", runtime.GOOS)
}
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "bazil.org/fuse/fs/fstestutil")
}
// Test that you cannot import a main package.
// See golang.org/issue/4210 and golang.org/issue/17475.
func TestImportMain(t *testing.T) {
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
// Importing package main from that package main's test should work.
tg.tempFile("src/x/main.go", `package main
var X int
func main() {}`)
tg.tempFile("src/x/main_test.go", `package main_test
import xmain "x"
import "testing"
var _ = xmain.X
func TestFoo(t *testing.T) {}
`)
tg.setenv("GOPATH", tg.path("."))
tg.creatingTemp("x")
tg.run("build", "x")
tg.run("test", "x")
// Importing package main from another package should fail.
tg.tempFile("src/p1/p.go", `package p1
import xmain "x"
var _ = xmain.X
`)
tg.runFail("build", "p1")
tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
// ... even in that package's test.
tg.tempFile("src/p2/p.go", `package p2
`)
tg.tempFile("src/p2/p_test.go", `package p2
import xmain "x"
import "testing"
var _ = xmain.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "p2")
tg.runFail("test", "p2")
tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
// ... even if that package's test is an xtest.
tg.tempFile("src/p3/p.go", `package p
`)
tg.tempFile("src/p3/p_test.go", `package p_test
import xmain "x"
import "testing"
var _ = xmain.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "p3")
tg.runFail("test", "p3")
tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
// ... even if that package is a package main
tg.tempFile("src/p4/p.go", `package main
func main() {}
`)
tg.tempFile("src/p4/p_test.go", `package main
import xmain "x"
import "testing"
var _ = xmain.X
func TestFoo(t *testing.T) {}
`)
tg.creatingTemp("p4" + exeSuffix)
tg.run("build", "p4")
tg.runFail("test", "p4")
tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
// ... even if that package is a package main using an xtest.
tg.tempFile("src/p5/p.go", `package main
func main() {}
`)
tg.tempFile("src/p5/p_test.go", `package main_test
import xmain "x"
import "testing"
var _ = xmain.X
func TestFoo(t *testing.T) {}
`)
tg.creatingTemp("p5" + exeSuffix)
tg.run("build", "p5")
tg.runFail("test", "p5")
tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
}
// Test that you cannot use a local import in a package
// accessed by a non-local import (found in a GOPATH/GOROOT).
// See golang.org/issue/17475.
func TestImportLocal(t *testing.T) {
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.tempFile("src/dir/x/x.go", `package x
var X int
`)
tg.setenv("GOPATH", tg.path("."))
tg.run("build", "dir/x")
// Ordinary import should work.
tg.tempFile("src/dir/p0/p.go", `package p0
import "dir/x"
var _ = x.X
`)
tg.run("build", "dir/p0")
// Relative import should not.
tg.tempFile("src/dir/p1/p.go", `package p1
import "../x"
var _ = x.X
`)
tg.runFail("build", "dir/p1")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in a test.
tg.tempFile("src/dir/p2/p.go", `package p2
`)
tg.tempFile("src/dir/p2/p_test.go", `package p2
import "../x"
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/p2")
tg.runFail("test", "dir/p2")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in an xtest.
tg.tempFile("src/dir/p2/p_test.go", `package p2_test
import "../x"
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/p2")
tg.runFail("test", "dir/p2")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// Relative import starting with ./ should not work either.
tg.tempFile("src/dir/d.go", `package dir
import "./x"
var _ = x.X
`)
tg.runFail("build", "dir")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in a test.
tg.tempFile("src/dir/d.go", `package dir
`)
tg.tempFile("src/dir/d_test.go", `package dir
import "./x"
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir")
tg.runFail("test", "dir")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in an xtest.
tg.tempFile("src/dir/d_test.go", `package dir_test
import "./x"
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir")
tg.runFail("test", "dir")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// Relative import plain ".." should not work.
tg.tempFile("src/dir/x/y/y.go", `package dir
import ".."
var _ = x.X
`)
tg.runFail("build", "dir/x/y")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in a test.
tg.tempFile("src/dir/x/y/y.go", `package y
`)
tg.tempFile("src/dir/x/y/y_test.go", `package y
import ".."
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/x/y")
tg.runFail("test", "dir/x/y")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in an x test.
tg.tempFile("src/dir/x/y/y_test.go", `package y_test
import ".."
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/x/y")
tg.runFail("test", "dir/x/y")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// Relative import "." should not work.
tg.tempFile("src/dir/x/xx.go", `package x
import "."
var _ = x.X
`)
tg.runFail("build", "dir/x")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in a test.
tg.tempFile("src/dir/x/xx.go", `package x
`)
tg.tempFile("src/dir/x/xx_test.go", `package x
import "."
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/x")
tg.runFail("test", "dir/x")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in an xtest.
tg.tempFile("src/dir/x/xx.go", `package x
`)
tg.tempFile("src/dir/x/xx_test.go", `package x_test
import "."
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/x")
tg.runFail("test", "dir/x")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
}
func TestGoGetInsecure(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.failSSH()
const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
// Try go get -d of HTTP-only repo (should fail).
tg.runFail("get", "-d", repo)
// Try again with -insecure (should succeed).
tg.run("get", "-d", "-insecure", repo)
// Try updating without -insecure (should fail).
tg.runFail("get", "-d", "-u", "-f", repo)
}
func TestGoGetUpdateInsecure(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
const repo = "github.com/golang/example"
// Clone the repo via HTTP manually.
cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
}
// Update without -insecure should fail.
// Update with -insecure should succeed.
// We need -f to ignore import comments.
const pkg = repo + "/hello"
tg.runFail("get", "-d", "-u", "-f", pkg)
tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
}
func TestGoGetInsecureCustomDomain(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
tg.runFail("get", "-d", repo)
tg.run("get", "-d", "-insecure", repo)
}
func TestGoRunDirs(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.cd("testdata/rundir")
tg.runFail("run", "x.go", "sub/sub.go")
tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
tg.runFail("run", "sub/sub.go", "x.go")
tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
}
func TestGoInstallPkgdir(t *testing.T) {
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.makeTempdir()
pkg := tg.path(".")
tg.run("install", "-pkgdir", pkg, "errors")
_, err := os.Stat(filepath.Join(pkg, "errors.a"))
tg.must(err)
_, err = os.Stat(filepath.Join(pkg, "runtime.a"))
tg.must(err)
}
func TestGoTestRaceInstallCgo(t *testing.T) {
if !canRace {
t.Skip("skipping because race detector not supported")
}
// golang.org/issue/10500.
// This used to install a race-enabled cgo.
tg := testgo(t)
defer tg.cleanup()
tg.run("tool", "-n", "cgo")
cgo := strings.TrimSpace(tg.stdout.String())
old, err := os.Stat(cgo)
tg.must(err)
tg.run("test", "-race", "-i", "runtime/race")
new, err := os.Stat(cgo)
tg.must(err)
if !new.ModTime().Equal(old.ModTime()) {
t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
}
}
func TestGoTestRaceFailures(t *testing.T) {
if !canRace {
t.Skip("skipping because race detector not supported")
}
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "testrace")
tg.runFail("test", "-race", "testrace")
tg.grepStdout("FAIL: TestRace", "TestRace did not fail")
tg.grepBothNot("PASS", "something passed")
tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".")
tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail")
tg.grepBothNot("PASS", "something passed")
}
func TestGoTestImportErrorStack(t *testing.T) {
const out = `package testdep/p1 (test)
imports testdep/p2
imports testdep/p3: no buildable Go source files`
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "testdep/p1")
if !strings.Contains(tg.stderr.String(), out) {
t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String())
}
}
func TestGoGetUpdate(t *testing.T) {
// golang.org/issue/9224.
// The recursive updating was trying to walk to
// former dependencies, not current ones.
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
rewind := func() {
tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
cmd := exec.Command("git", "reset", "--hard", "HEAD~")
cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git: %v\n%s", err, out)
}
}
rewind()
tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
// Again with -d -u.
rewind()
tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
}
func TestGoGetDomainRoot(t *testing.T) {
// golang.org/issue/9357.
// go get foo.io (not foo.io/subdir) was not working consistently.
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
// go-get-issue-9357.appspot.com is running
// the code at github.com/rsc/go-get-issue-9357,
// a trivial Go on App Engine app that serves a
// <meta> tag for the domain root.
tg.run("get", "-d", "go-get-issue-9357.appspot.com")
tg.run("get", "go-get-issue-9357.appspot.com")
tg.run("get", "-u", "go-get-issue-9357.appspot.com")
tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
tg.run("get", "go-get-issue-9357.appspot.com")
tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
tg.run("get", "-u", "go-get-issue-9357.appspot.com")
}
func TestGoInstallShadowedGOPATH(t *testing.T) {
// golang.org/issue/3652.
// go get foo.io (not foo.io/subdir) was not working consistently.
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
tg.tempDir("gopath1/src/test")
tg.tempDir("gopath2/src/test")
tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
tg.cd(tg.path("gopath2/src/test"))
tg.runFail("install")
tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
}
func TestGoBuildGOPATHOrder(t *testing.T) {
// golang.org/issue/14176#issuecomment-179895769
// golang.org/issue/14192
// -I arguments to compiler could end up not in GOPATH order,
// leading to unexpected import resolution in the compiler.
// This is still not a complete fix (see golang.org/issue/14271 and next test)
// but it is clearly OK and enough to fix both of the two reported
// instances of the underlying problem. It will have to do for now.
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2"))
tg.tempFile("p1/src/foo/foo.go", "package foo\n")
tg.tempFile("p2/src/baz/baz.go", "package baz\n")
tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
tg.tempFile("p1/src/bar/bar.go", `
package bar
import _ "baz"
import _ "foo"
`)
tg.run("install", "-x", "bar")
}
func TestGoBuildGOPATHOrderBroken(t *testing.T) {
// This test is known not to work.
// See golang.org/issue/14271.
t.Skip("golang.org/issue/14271")
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.tempFile("p1/src/foo/foo.go", "package foo\n")
tg.tempFile("p2/src/baz/baz.go", "package baz\n")
tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n")
tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
tg.tempFile("p1/src/bar/bar.go", `
package bar
import _ "baz"
import _ "foo"
`)
colon := string(filepath.ListSeparator)
tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2"))
tg.run("install", "-x", "bar")
tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1"))
tg.run("install", "-x", "bar")
}
func TestIssue11709(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("run.go", `
package main
import "os"
func main() {
if os.Getenv("TERM") != "" {
os.Exit(1)
}
}`)
tg.unsetenv("TERM")
tg.run("run", tg.path("run.go"))
}
func TestIssue12096(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("test_test.go", `
package main
import ("os"; "testing")
func TestEnv(t *testing.T) {
if os.Getenv("TERM") != "" {
t.Fatal("TERM is set")
}
}`)
tg.unsetenv("TERM")
tg.run("test", tg.path("test_test.go"))
}
func TestGoBuildOutput(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.cd(tg.path("."))
nonExeSuffix := ".exe"
if exeSuffix == ".exe" {
nonExeSuffix = ""
}
tg.tempFile("x.go", "package main\nfunc main(){}\n")
tg.run("build", "x.go")
tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
tg.must(os.Remove(tg.path("x" + exeSuffix)))
tg.mustNotExist("x" + nonExeSuffix)
tg.run("build", "-o", "myprog", "x.go")
tg.mustNotExist("x")
tg.mustNotExist("x.exe")
tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
tg.mustNotExist("myprog.exe")
tg.tempFile("p.go", "package p\n")
tg.run("build", "p.go")
tg.mustNotExist("p")
tg.mustNotExist("p.a")
tg.mustNotExist("p.o")
tg.mustNotExist("p.exe")
tg.run("build", "-o", "p.a", "p.go")
tg.wantArchive("p.a")
tg.run("build", "cmd/gofmt")
tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
tg.mustNotExist("gofmt" + nonExeSuffix)
tg.run("build", "-o", "mygofmt", "cmd/gofmt")
tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
tg.mustNotExist("mygofmt.exe")
tg.mustNotExist("gofmt")
tg.mustNotExist("gofmt.exe")
tg.run("build", "sync/atomic")
tg.mustNotExist("atomic")
tg.mustNotExist("atomic.exe")
tg.run("build", "-o", "myatomic.a", "sync/atomic")
tg.wantArchive("myatomic.a")
tg.mustNotExist("atomic")
tg.mustNotExist("atomic.a")
tg.mustNotExist("atomic.exe")
tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
}
func TestGoBuildARM(t *testing.T) {
if testing.Short() {
t.Skip("skipping cross-compile in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.setenv("GOARCH", "arm")
tg.setenv("GOOS", "linux")
tg.setenv("GOARM", "5")
tg.tempFile("hello.go", `package main
func main() {}`)
tg.run("build", "hello.go")
tg.grepStderrNot("unable to find math.a", "did not build math.a correctly")
}
func TestIssue13655(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
for _, pkg := range []string{"runtime", "runtime/internal/atomic"} {
tg.run("list", "-f", "{{.Deps}}", pkg)
tg.grepStdout("runtime/internal/sys", "did not find required dependency of "+pkg+" on runtime/internal/sys")
}
}
// For issue 14337.
func TestParallelTest(t *testing.T) {
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.makeTempdir()
const testSrc = `package package_test
import (
"testing"
)
func TestTest(t *testing.T) {
}`
tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
tg.setenv("GOPATH", tg.path("."))
tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
}
func TestCgoConsistentResults(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
switch runtime.GOOS {
case "freebsd":
testenv.SkipFlaky(t, 15405)
case "solaris":
testenv.SkipFlaky(t, 13247)
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
exe1 := tg.path("cgotest1" + exeSuffix)
exe2 := tg.path("cgotest2" + exeSuffix)
tg.run("build", "-o", exe1, "cgotest")
tg.run("build", "-x", "-o", exe2, "cgotest")
b1, err := ioutil.ReadFile(exe1)
tg.must(err)
b2, err := ioutil.ReadFile(exe2)
tg.must(err)
if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) {
t.Skip("skipping because C compiler does not support -fdebug-prefix-map")
}
if !bytes.Equal(b1, b2) {
t.Error("building cgotest twice did not produce the same output")
}
}
// Issue 14444: go get -u .../ duplicate loads errors
func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "-u", ".../")
tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache")
}
// Issue 17119 more duplicate load errors
func TestIssue17119(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("build", "dupload")
tg.grepBothNot("duplicate load|internal error", "internal error")
}
func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal")
tg.grepBothNot("^ok", "test passed unexpectedly")
tg.grepBoth("FAIL.*benchfatal", "test did not run everything")
}
func TestBinaryOnlyPackages(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.tempFile("src/p1/p1.go", `//go:binary-only-package
package p1
`)
tg.wantStale("p1", "cannot access install target", "p1 is binary-only but has no binary, should be stale")
tg.runFail("install", "p1")
tg.grepStderr("missing or invalid package binary", "did not report attempt to compile binary-only package")
tg.tempFile("src/p1/p1.go", `
package p1
import "fmt"
func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } }
`)
tg.run("install", "p1")
os.Remove(tg.path("src/p1/p1.go"))
tg.mustNotExist(tg.path("src/p1/p1.go"))
tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great
package p2
import "p1"
func F() { p1.F(true) }
`)
tg.runFail("install", "p2")
tg.grepStderr("no buildable Go source files", "did not complain about missing sources")
tg.tempFile("src/p1/missing.go", `//go:binary-only-package
package p1
func G()
`)
tg.wantNotStale("p1", "no source code", "should NOT want to rebuild p1 (first)")
tg.run("install", "-x", "p1") // no-op, up to date
tg.grepBothNot("/compile", "should not have run compiler")
tg.run("install", "p2") // does not rebuild p1 (or else p2 will fail)
tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
// changes to the non-source-code do not matter,
// and only one file needs the special comment.
tg.tempFile("src/p1/missing2.go", `
package p1
func H()
`)
tg.wantNotStale("p1", "no source code", "should NOT want to rebuild p1 (second)")
tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
tg.tempFile("src/p3/p3.go", `
package main
import (
"p1"
"p2"
)
func main() {
p1.F(false)
p2.F()
}
`)
tg.run("install", "p3")
tg.run("run", tg.path("src/p3/p3.go"))
tg.grepStdout("hello from p1", "did not see message from p1")
tg.tempFile("src/p4/p4.go", `package main`)
tg.tempFile("src/p4/p4not.go", `//go:binary-only-package
// +build asdf
package main
`)
tg.run("list", "-f", "{{.BinaryOnly}}", "p4")
tg.grepStdout("false", "did not see BinaryOnly=false for p4")
}
// Issue 16050.
func TestAlwaysLinkSysoFiles(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src/syso")
tg.tempFile("src/syso/a.syso", ``)
tg.tempFile("src/syso/b.go", `package syso`)
tg.setenv("GOPATH", tg.path("."))
// We should see the .syso file regardless of the setting of
// CGO_ENABLED.
tg.setenv("CGO_ENABLED", "1")
tg.run("list", "-f", "{{.SysoFiles}}", "syso")
tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1")
tg.setenv("CGO_ENABLED", "0")
tg.run("list", "-f", "{{.SysoFiles}}", "syso")
tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0")
}
// Issue 16120.
func TestGenerateUsesBuildContext(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("this test won't run under Windows")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src/gen")
tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n")
tg.setenv("GOPATH", tg.path("."))
tg.setenv("GOOS", "linux")
tg.setenv("GOARCH", "amd64")
tg.run("generate", "gen")
tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination")
tg.setenv("GOOS", "darwin")
tg.setenv("GOARCH", "386")
tg.run("generate", "gen")
tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination")
}
// Issue 14450: go get -u .../ tried to import not downloaded package
func TestGoGetUpdateWithWildcard(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a"
tg.run("get", aPkgImportPath)
tg.run("get", "-u", ".../")
tg.grepStderrNot("cannot find package", "did not update packages given wildcard path")
var expectedPkgPaths = []string{
"src/github.com/tmwh/go-get-issue-14450/b",
"src/github.com/tmwh/go-get-issue-14450-b-dependency/c",
"src/github.com/tmwh/go-get-issue-14450-b-dependency/d",
}
for _, importPath := range expectedPkgPaths {
_, err := os.Stat(tg.path(importPath))
tg.must(err)
}
const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e"
tg.mustNotExist(tg.path(notExpectedPkgPath))
}
func TestGoEnv(t *testing.T) {
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.setenv("GOARCH", "arm")
tg.run("env", "GOARCH")
tg.grepStdout("^arm$", "GOARCH not honored")
tg.run("env", "GCCGO")
tg.grepStdout(".", "GCCGO unexpectedly empty")
tg.run("env", "CGO_CFLAGS")
tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty")
tg.setenv("CGO_CFLAGS", "-foobar")
tg.run("env", "CGO_CFLAGS")
tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored")
tg.setenv("CC", "gcc -fmust -fgo -ffaster")
tg.run("env", "CC")
tg.grepStdout("gcc", "CC not found")
tg.run("env", "GOGCCFLAGS")
tg.grepStdout("-ffaster", "CC arguments not found")
}
const (
noMatchesPattern = `(?m)^ok.*\[no tests to run\]`
okPattern = `(?m)^ok`
)
func TestMatchesNoTests(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go")
tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
}
func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth("FAIL", "go test did not say FAIL")
}
func TestMatchesNoBenchmarksIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
func TestMatchesOnlyExampleIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "Example", "testdata/example1_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
func TestMatchesOnlyBenchmarkIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
func TestBenchmarkLabels(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "-run", "^$", "-bench", ".", "bench")
tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench")
tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times")
}
func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:")
}
func TestMatchesOnlyTestIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "Test", "testdata/standalone_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
func TestMatchesNoTestsWithSubtests(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go")
tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
}
func TestMatchesNoSubtestsMatch(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go")
tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
}
func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth("FAIL", "go test did not say FAIL")
}
func TestMatchesOnlySubtestIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
func TestMatchesNoSubtestsParallel(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go")
tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
}
func TestMatchesOnlySubtestParallelIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
// Issue 18845
func TestBenchTimeout(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go")
}
func TestLinkXImportPathEscape(t *testing.T) {
// golang.org/issue/16710
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
exe := "./linkx" + exeSuffix
tg.creatingTemp(exe)
tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main")
out, err := exec.Command(exe).CombinedOutput()
if err != nil {
tg.t.Fatal(err)
}
if string(out) != "linkXworked\n" {
tg.t.Log(string(out))
tg.t.Fatal(`incorrect output: expected "linkXworked\n"`)
}
}
// Issue 18044.
func TestLdBindNow(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("LD_BIND_NOW", "1")
tg.run("help")
}
// Issue 18225.
// This is really a cmd/asm issue but this is a convenient place to test it.
func TestConcurrentAsm(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
asm := `DATA ·constants<>+0x0(SB)/8,$0
GLOBL ·constants<>(SB),8,$8
`
tg.tempFile("go/src/p/a.s", asm)
tg.tempFile("go/src/p/b.s", asm)
tg.tempFile("go/src/p/p.go", `package p`)
tg.setenv("GOPATH", tg.path("go"))
tg.run("build", "p")
}
// Issue 18778.
func TestDotDotDotOutsideGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("pkgs/a.go", `package x`)
tg.tempFile("pkgs/a_test.go", `package x_test
import "testing"
func TestX(t *testing.T) {}`)
tg.tempFile("pkgs/a/a.go", `package a`)
tg.tempFile("pkgs/a/a_test.go", `package a_test
import "testing"
func TestA(t *testing.T) {}`)
tg.cd(tg.path("pkgs"))
tg.run("build", "./...")
tg.run("test", "./...")
tg.run("list", "./...")
tg.grepStdout("pkgs$", "expected package not listed")
tg.grepStdout("pkgs/a", "expected package not listed")
}
// Issue 18975.
func TestFFLAGS(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("p/src/p/main.go", `package main
// #cgo FFLAGS: -no-such-fortran-flag
import "C"
func main() {}
`)
tg.tempFile("p/src/p/a.f", `! comment`)
tg.setenv("GOPATH", tg.path("p"))
// This should normally fail because we are passing an unknown flag,
// but issue #19080 points to Fortran compilers that succeed anyhow.
// To work either way we call doRun directly rather than run or runFail.
tg.doRun([]string{"build", "-x", "p"})
tg.grepStderr("no-such-fortran-flag", `missing expected "-no-such-fortran-flag"`)
}
// Issue 19198.
// This is really a cmd/link issue but this is a convenient place to test it.
func TestDuplicateGlobalAsmSymbols(t *testing.T) {
if runtime.GOARCH != "386" && runtime.GOARCH != "amd64" {
t.Skipf("skipping test on %s", runtime.GOARCH)
}
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
asm := `
#include "textflag.h"
DATA sym<>+0x0(SB)/8,$0
GLOBL sym<>(SB),(NOPTR+RODATA),$8
TEXT ·Data(SB),NOSPLIT,$0
MOVB sym<>(SB), AX
MOVB AX, ret+0(FP)
RET
`
tg.tempFile("go/src/a/a.s", asm)
tg.tempFile("go/src/a/a.go", `package a; func Data() uint8`)
tg.tempFile("go/src/b/b.s", asm)
tg.tempFile("go/src/b/b.go", `package b; func Data() uint8`)
tg.tempFile("go/src/p/p.go", `
package main
import "a"
import "b"
import "C"
func main() {
_ = a.Data() + b.Data()
}
`)
tg.setenv("GOPATH", tg.path("go"))
exe := filepath.Join(tg.tempdir, "p.exe")
tg.creatingTemp(exe)
tg.run("build", "-o", exe, "p")
}
func TestBuildTagsNoComma(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("go"))
tg.run("install", "-tags", "tag1 tag2", "math")
tg.runFail("install", "-tags", "tag1,tag2", "math")
tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
tg.runFail("build", "-tags", "tag1,tag2", "math")
tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
}
func copyFile(src, dst string, perm os.FileMode) error {
sf, err := os.Open(src)
if err != nil {
return err
}
defer sf.Close()
df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
_, err = io.Copy(df, sf)
err2 := df.Close()
if err != nil {
return err
}
return err2
}
func TestExecutableGOROOT(t *testing.T) {
if runtime.GOOS == "openbsd" {
t.Skipf("test case does not work on %s, missing os.Executable", runtime.GOOS)
}
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.tempDir("newgoroot/bin")
newGoTool := tg.path("newgoroot/bin/go" + exeSuffix)
err := copyFile(tg.goTool(), newGoTool, 0775)
if err != nil {
t.Fatalf("error copying go tool %v", err)
}
goroot := func(goTool string) string {
cmd := exec.Command(goTool, "env", "GOROOT")
cmd.Env = os.Environ()
for i, val := range cmd.Env {
if strings.HasPrefix(val, "GOROOT=") {
cmd.Env = append(cmd.Env[:i], cmd.Env[i+1:]...)
break
}
}
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("copied go tool failed %v: %s", err, out)
}
root := strings.TrimSpace(string(out))
resolved, err := filepath.EvalSymlinks(root)
if err != nil {
t.Fatalf("EvalSymlinks(%q) failed: %v", root, err)
}
return resolved
}
// Filenames are case insensitive on Windows.
// There should probably be a path/filepath function for this.
equal := func(a, b string) bool { return a == b }
if runtime.GOOS == "windows" {
equal = strings.EqualFold
}
// macOS uses a symlink for /tmp.
resolvedTestGOROOT, err := filepath.EvalSymlinks(testGOROOT)
if err != nil {
t.Fatalf("could not eval testgoroot symlinks: %v", err)
}
// Missing GOROOT/pkg/tool, the go tool should fall back to
// its default path.
if got, want := goroot(newGoTool), resolvedTestGOROOT; !equal(got, want) {
t.Fatalf("%s env GOROOT = %q, want %q", newGoTool, got, want)
}
// Now the executable's path looks like a GOROOT.
tg.tempDir("newgoroot/pkg/tool")
resolvedNewGOROOT, err := filepath.EvalSymlinks(tg.path("newgoroot"))
if err != nil {
t.Fatalf("could not eval newgoroot symlinks: %v", err)
}
if got, want := goroot(newGoTool), resolvedNewGOROOT; !equal(got, want) {
t.Fatalf("%s env GOROOT = %q with pkg/tool, want %q", newGoTool, got, want)
}
testenv.MustHaveSymlink(t)
tg.tempDir("notgoroot/bin")
symGoTool := tg.path("notgoroot/bin/go" + exeSuffix)
tg.must(os.Symlink(newGoTool, symGoTool))
if got, want := goroot(symGoTool), resolvedNewGOROOT; !equal(got, want) {
t.Fatalf("%s env GOROOT = %q, want %q", symGoTool, got, want)
}
}
func TestNeedVersion(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("goversion.go", `package main; func main() {}`)
path := tg.path("goversion.go")
tg.setenv("TESTGO_VERSION", "go1.testgo")
tg.runFail("run", path)
tg.grepStderr("compile", "does not match go tool version")
}
// Test that user can override default code generation flags.
func TestUserOverrideFlags(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
if runtime.GOOS != "linux" {
// We are testing platform-independent code, so it's
// OK to skip cases that work differently.
t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS)
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("override.go", `package main
import "C"
//export GoFunc
func GoFunc() {}
func main() {}`)
tg.creatingTemp("override.a")
tg.creatingTemp("override.h")
tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=-shared=false", tg.path("override.go"))
tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag")
}
func TestCgoFlagContainsSpace(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
ccName := filepath.Base(testCC)
tg.tempFile(fmt.Sprintf("src/%s/main.go", ccName), fmt.Sprintf(`package main
import (
"os"
"os/exec"
)
func main() {
cmd := exec.Command(%q, os.Args[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
panic(err)
}
if os.Args[len(os.Args)-1] == "trivial.c" {
return
}
var success bool
for _, arg := range os.Args {
switch arg {
case "-Ic flags":
if success {
panic("duplicate CFLAGS")
}
success = true
case "-Lld flags":
if success {
panic("duplicate LDFLAGS")
}
success = true
}
}
if !success {
panic("args should contains '-Ic flags' or '-Lld flags'")
}
}
`, testCC))
tg.cd(tg.path(fmt.Sprintf("src/%s", ccName)))
tg.run("build")
tg.setenv("CC", tg.path(fmt.Sprintf("src/%s/%s", ccName, ccName)))
tg.tempFile("src/cgo/main.go", `package main
// #cgo CFLAGS: -I"c flags"
// #cgo LDFLAGS: -L"ld flags"
import "C"
func main() {}
`)
tg.cd(tg.path("src/cgo"))
tg.run("run", "main.go")
}
// Issue #20435.
func TestGoTestRaceCoverModeFailures(t *testing.T) {
if !canRace {
t.Skip("skipping because race detector not supported")
}
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "testrace")
tg.runFail("test", "-race", "-covermode=set", "testrace")
tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed")
tg.grepBothNot("PASS", "something passed")
}
// Issue 9737: verify that GOARM and GO386 affect the computed build ID.
func TestBuildIDContainsArchModeEnv(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
var tg *testgoData
testWith := func(before, after func()) func(*testing.T) {
return func(t *testing.T) {
tg = testgo(t)
defer tg.cleanup()
tg.tempFile("src/mycmd/x.go", `package main
func main() {}`)
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src/mycmd"))
tg.setenv("GOOS", "linux")
before()
tg.run("install", "mycmd")
after()
tg.wantStale("mycmd", "build ID mismatch", "should be stale after environment variable change")
}
}
t.Run("386", testWith(func() {
tg.setenv("GOARCH", "386")
tg.setenv("GO386", "387")
}, func() {
tg.setenv("GO386", "sse2")
}))
t.Run("arm", testWith(func() {
tg.setenv("GOARCH", "arm")
tg.setenv("GOARM", "5")
}, func() {
tg.setenv("GOARM", "7")
}))
}
|
[
"\"HOME\"",
"\"CCACHE_DIR\"",
"\"PATH\"",
"\"GOPATH\"",
"\"TERM\"",
"\"TERM\""
] |
[] |
[
"CCACHE_DIR",
"GOPATH",
"TERM",
"HOME",
"PATH"
] |
[]
|
["CCACHE_DIR", "GOPATH", "TERM", "HOME", "PATH"]
|
go
| 5 | 0 | |
manage.py
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "quickUrls.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
main.go
|
package main
import (
"flag"
"log"
"os"
"sync"
"time"
// Autoload .env files
"github.com/jbuchbinder/cadmonitor/monitor"
_ "github.com/joho/godotenv/autoload"
)
var (
baseURL = flag.String("baseUrl", "http://cadview.qvec.org/", "Base URL")
monitorType = flag.String("monitorType", "aegis", "Type of CAD system being monitored")
pollInterval = flag.Int("poll-interval", 5, "Poll interval in seconds")
inactivityMin = flag.Int("inactivity", 10, "Inactivity in minutes before culling")
suffix = flag.String("suffix", "", "Unit suffix to restrict polling to (i.e. 63 for STA63 units)")
fdid = flag.String("fdid", "04042", "FDID for agency")
mutex sync.Mutex
activeCalls map[string]monitor.CallStatus
)
func main() {
flag.Parse()
cadbrowser, err := monitor.InstantiateCadMonitor(*monitorType)
if err != nil {
panic(err)
}
err = cadbrowser.ConfigureFromValues(map[string]string{
"baseUrl": *baseURL,
"suffix": *suffix,
"fdid": *fdid,
})
if err != nil {
panic(err)
}
log.Printf("Logging into CAD interface")
err = cadbrowser.Login(os.Getenv("CADUSER"), os.Getenv("CADPASS"))
if err != nil {
panic(err)
}
log.Printf("Starting main loop")
activeCalls = map[string]monitor.CallStatus{}
// Cull active calls every poll interval x 4
go func() {
log.Printf("Culling loop started")
for {
log.Printf("Culling job running")
mutex.Lock()
for k := range activeCalls {
if time.Since(activeCalls[k].LastUpdated) > (time.Duration(*inactivityMin) * time.Minute) {
log.Printf("Removing call %s due to inactivity", k)
delete(activeCalls, k)
}
}
mutex.Unlock()
for iter := 0; iter < *pollInterval*2; iter++ {
time.Sleep(time.Second)
if cadbrowser.TerminateMonitor() {
log.Printf("Terminating culling thread")
break
}
}
}
}()
cadbrowser.Monitor(func(call monitor.CallStatus) error {
mutex.Lock()
defer mutex.Unlock()
log.Printf("Callback triggered with ID : %s", call.ID)
// Check to see if it's in the active map
if _, ok := activeCalls[call.ID]; !ok {
// Store new copy, act accordingly
activeCalls[call.ID] = call
// Notify that there's a new call
return notifyNewCall(call)
}
if call.District != activeCalls[call.ID].District {
// Update if district has been updated
err := notifyCallDifferences(activeCalls[call.ID], call)
activeCalls[call.ID] = call
return err
}
// See if there are any differences
if len(call.Units) != len(activeCalls[call.ID].Units) {
err := notifyUnitDifferences(activeCalls[call.ID], call)
activeCalls[call.ID] = call
return err
}
// Update last updated to keep it frosty
activeCalls[call.ID] = call
log.Printf("Status: %#v", call)
return nil
}, *pollInterval)
}
func notifyNewCall(call monitor.CallStatus) error {
log.Printf("notifyNewCall: %#v", call)
return nil
}
func notifyCallDifferences(orig monitor.CallStatus, updated monitor.CallStatus) error {
log.Printf("notifyCallDifferences: %#v -> %#v", orig, updated)
return nil
}
func notifyUnitDifferences(orig monitor.CallStatus, updated monitor.CallStatus) error {
log.Printf("notifyUnitDifferences: %#v -> %#v", orig, updated)
return nil
}
|
[
"\"CADUSER\"",
"\"CADPASS\""
] |
[] |
[
"CADPASS",
"CADUSER"
] |
[]
|
["CADPASS", "CADUSER"]
|
go
| 2 | 0 | |
PenBallWizard/PenBallWizard.roboFontExt/lib/filterObjects/jitterPen.py
|
#coding=utf-8
from __future__ import division
from fontTools.pens.basePen import BasePen
import math
import random
def distance((x1, y1), (x2, y2)):
dx = x2 - x1
dy = y2 - y1
return math.hypot(dy, dx)
def interpolate((x1, y1), (x2, y2), factor):
x = x1 + ((x2 - x1) * factor)
y = y1 + ((y2 - y1) * factor)
return x, y
def pointOnACurve((x1, y1), (cx1, cy1), (cx2, cy2), (x2, y2), value):
dx = x1
cx = (cx1 - dx) * 3.0
bx = (cx2 - cx1) * 3.0 - cx
ax = x2 - dx - cx - bx
dy = y1
cy = (cy1 - dy) * 3.0
by = (cy2 - cy1) * 3.0 - cy
ay = y2 - dy - cy - by
mx = ax*(value)**3 + bx*(value)**2 + cx*(value) + dx
my = ay*(value)**3 + by*(value)**2 + cy*(value) + dy
return mx, my
def curveLength(pt1, pt2, pt3, pt4, precision=20):
flatCurvePoints = [pointOnACurve(pt1, pt2, pt3, pt4, i/precision) for i in range(precision)]
length = 0
for i in range(1, len(flatCurvePoints)):
previousPoint = flatCurvePoints[i-1]
point = flatCurvePoints[i]
length += distance(previousPoint, point)
return length
class JitterPen(BasePen):
def __init__(self, pen, jitterPace=10, deviation=10):
self.pen = pen
self.previousPoint = None
self.pace = jitterPace
if self.pace < 1:
self.pace = 1
self.deviation = deviation
self.started = False
def _moveTo(self, pt):
self.previousPoint = pt
self.started = True
def _lineTo(self, pt):
pt0 = self.previousPoint
if self.started == True:
self.pen.moveTo(pt0)
self.started = False
pt1 = pt
d = distance(pt0, pt1)
steps = int(d/self.pace)
deviation = self.deviation
for i in range(steps):
x, y = interpolate(pt0, pt1, i/steps)
nx = self.deviate(x)
ny = self.deviate(y)
self.pen.lineTo((nx, ny))
self.previousPoint = pt1
def _curveToOne(self, pt1, pt2, pt3):
pt0 = self.previousPoint
if self.started == True:
self.pen.moveTo(pt0)
self.started = False
d = curveLength(pt0, pt1, pt2, pt3)
steps = int(d/self.pace)
deviation = self.deviation
for i in range(steps):
x, y = pointOnACurve(pt0, pt1, pt2, pt3, i/steps)
nx = self.deviate(x)
ny = self.deviate(y)
self.pen.lineTo((nx, ny))
self.previousPoint = pt3
def endPath(self):
if self.started == False:
self.pen.endPath()
def closePath(self):
if self.started == False:
self.pen.closePath()
def addComponent(self, baseGlyphName, transformations):
pass
def deviate(self, value):
return random.gauss(value, self.deviation)
|
[] |
[] |
[] |
[]
|
[]
|
python
| null | null | null |
game.py
|
#!/usr/bin/python3
#################################################################################
#
# Copyright (c) 2016 Eric Samuelson
# RpiPin by Eric Samuelson
# Currently in extreme beta/experimentation stages
# I wouldn't expect this to be used by anyone, but if so, please let me know
# on github!
#
# 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.
#
#################################################################################
# Imports
import os
os.environ['SDL_VIDEODRIVER'] = 'dummy'
import smbus
import pygame
import curses
import signal
import sys
import picamera
import time as gtime
#################################################################################
# Definitions and Classes
#################################################################################
# Custom definitions and classes
#################################################################################
# Score class
#################################################################################
class Score:
def __init__(self, init_score, init_mul, init_paddles):
self.val = init_score
self.mul = init_mul
self.pad = init_paddles
def modscore(self, amount):
"Modifies score with respect to the current multiplier"
self.val += (amount * self.mul)
if self.val > 99999999: self.val = 0
def setmul(self, mul):
"Sets the multiplier"
self.mul = mul
def highscore(self):
"Sets a new high score if applicable"
pass
def get_highscore(self):
"Returns a list of the high scores"
pass
#################################################################################
# Clean exit sigint handler
#################################################################################
def signal_handler(signal, frame):
"Signal handler for Ctrl-C and related things"
clean_exit("SIGINT detected. Closing program.")
def catch_uncaught(type, value, traceback):
clean_exit(str(type) + " " + str(value) + " " + str(traceback))
#################################################################################
# Cleans up pin outputs and curses junk
#################################################################################
def clean_exit(message=""):
"Tries to make for a clean exit since curses doesn't make for a nice one by default"
try:
sevSegL.clear()
sevSegL.write_display()
sevSegR.clear()
sevSegR.write_display()
io.cleanup()
except:
pass
# Clean up screen
leds.clear()
curses.nocbreak()
screen.keypad(False)
curses.echo()
curses.endwin()
if(message): print(message)
# Bye :)
sys.exit(0)
#################################################################################
# Stops all animations
#################################################################################
def stopAnimations(dontStop=""):
"Stops all animations excluding the one in dontStop"
for obj in animList:
if obj == dontStop: continue
exec(obj + ".stop()")
#################################################################################
# Media Volume Settings
#################################################################################
def modVolume(modval):
flag = "+"
if modval < 0:
flag = "-"
modval = abs(modval)
call(["amixer", "-q", "sset", "PCM", str(modval)+"%"+flag])
#################################################################################
# Initialization
#################################################################################
# Custom Imports
from HT16K33 import *
from led import *
#from hmc5883l import *
from mcp23017 import *
from media import *
from servo import *
from subprocess import call
# In the beginning...
time = 0
lastScore = -12345
playlistPos = 0
playlistPath = "audio/music/"
# Currently using pygame for sound and music and frame-rate control
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.init()
pygame.display.set_mode((1,1))
clock = pygame.time.Clock()
pygame.mixer.init(44100, -16,2,2048)
# Curses Initialization for game status (curses import)
screen = curses.initscr()
curses.noecho()
curses.curs_set(0)
screen.keypad(1)
screen.nodelay(1)
# Clean up nicely when sigint
signal.signal(signal.SIGINT, signal_handler)
#sys.excepthook = catch_uncaught
#################################################################################
# Init losercam
#camera = picamera.PiCamera()
#################################################################################
#################################################################################
# Init Music
# TODO: Playlist
#################################################################################
try:
playlist = ['Powerup.mp3', 'Stardrive.mp3', 'Turn_Up_Let_s_Go.mp3']
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.load(playlistPath + playlist[playlistPos])
pygame.mixer.music.play(-1)
except:
clean_exit(message="Error initializing audio!\n")
#################################################################################
# Init score: start score, multiplier, paddlings
#################################################################################
score = Score(0, 1, 0)
#################################################################################
# Init i2c bus (smbus)
# Use i2cdetect -y 1 to see what devices are on the bus
#################################################################################
smbus = smbus.SMBus(1)
#################################################################################
# Initialize i2c I/O Driver
# Init bus: smbus, start_addr, count, out_dir_reg,
# in_dir_reg, out_reg, in_reg, pup_reg, pol_reg, debounce_time
#################################################################################
try:
io = mcp23017(smbus, 0x20, 1, 0x00, 0x01, 0x14, 0x13, 0x0D, 0x03, 50)
except:
clean_exit(message="Failed loading I2C IO!\n")
#################################################################################
# I2C Arduino WS2812 LED Controller
#################################################################################
leds = ledStrip(smbus, address=0x10)
#################################################################################
# 7Seg Display Initialization
# Uses left and right for a total of 8 digits
#################################################################################
try:
sevSegL = SevenSegment(address=0x71, busnum=1, i2c=smbus)
sevSegR = SevenSegment(address=0x70, busnum=1, i2c=smbus)
sevSegL.begin()
sevSegR.begin()
sevSegL.set_invert(1)
sevSegR.set_invert(1)
sevSegL.set_brightness(15)
sevSegR.set_brightness(15)
sevSegL.clear()
sevSegR.clear()
sevSegL.write_display()
sevSegR.write_display()
except:
clean_exit(message="Failed initializing i2c 7-Segment display\n")
#################################################################################
# Init hmc5883l
# Magnetic tilt sensor, not to be used in proximity of solenoids.....
# Look for accelerometer instead?
#################################################################################
#axis = hmc5883l(smbus, 0x1E, 300)
x = y = z = 0
#################################################################################
# Init Servo Library for 50Hz servos
#################################################################################
#servoBoard = servo(smbus, address=0x40)
#servoBoard.setPWMFreq(50)
#ufoServo = twoAxisServo(servoBoard, 0, 1)
#################################################################################
# Animations and Scripts
#################################################################################
animList = ['loadBall', 'solenoid', 'catapult'] #, 'ufoFly']
for obj in animList:
exec(obj + "= tEvent()")
# Set up drop target with 5 targets from pin 1 to pin 5. Reset pin is 1.
dt1 = dropTarget(1, 5, 1, pygame, solenoid, score, io, leds)
#################################################################################
# Main Game Loop
#################################################################################
errors = 0
while 1:
try:
#io.time =
io_string = "["
time = pygame.time.get_ticks()
event = screen.getch()
for pin in range(1, 8):
if io.getpin(pin, time):
io_string += "1"
else:
io_string += "0"
io_string += "]"
if event == ord("q"): break
if io.getpin(6, time):
io.pinout(1, True)
else:
io.pinout(1, False)
if event == ord("1") or solenoid.started == "1":
solenoid.triggerSolenoid(time, io, 1, duration=80, tag="1")
if event == ord("2") or catapult.started == "2":
catapult.triggerSolenoid(time, io, 2, duration=80, tag="2")
if event == ord("3"):
score.modscore(1)
if event == ord("4"):
score.modscore(10)
if event == ord("5"):
score.modscore(100)
if event == ord("6"):
score.modscore(1000)
if event == ord("7"):
score.modscore(10000)
if event == ord("8"):
score.modscore(100000)
if event == ord("9"):
score.modscore(1000000)
# Change music around
if event == ord("m"):
playlistPos += 1
if playlistPos >= len(playlist):
playlistPos = 0
pygame.mixer.music.load(playlistPath + playlist[playlistPos])
pygame.mixer.music.play(-1)
if event == ord("s"):
play_sound(pygame, "arugh")
if event == ord("r"):
stopAnimations()
if event == ord("-"):
modVolume(-10)
if event == ord("+"):
modVolume(10)
#if event == curses.KEY_LEFT:
# ufoServo.modX(-1)
#if event == curses.KEY_RIGHT:
# ufoServo.modX(1)
#if event == curses.KEY_DOWN:
# ufoServo.modY(-1)
#if event == curses.KEY_UP:
# ufoServo.modY(1)
#if event == ord("/") or ufoFly.started == "1":
# ufoFly.ufoFly(time, ufoServo, duration=5000)
#if event == ord("j") or solenoid.started == "Motor":
# solenoid.triggerPWM(time, io, 9, duration=1000, tag="Motor", dutyCycle=12, dutyLength=4)
if event == ord("z"):
leds.colorWipe(10, 255, 0, 0)
if event == ord("x"):
leds.colorWipe(10, 0, 255, 0)
if event == ord("c"):
leds.colorWipe(10, 0, 0, 255)
if event == ord("v"):
leds.rainbowCycle(20)
if event == ord("b"):
leds.theaterChase(50, 255, 255, 255)
if event == ord("n"):
leds.setLed(2, 127, 0, 127, 100, 1)
if event == ord("o"):
leds.setLed(2, 127, 127, 0, 0, 0)
if event == ord("a"):
leds.setLedRange(5, 17, 128, 255, 128, 50, 1)
if event == ord("s"):
leds.setBright(16)
if event == ord("d"):
leds.setBright(255)
if event == ord(";"):
leds.restoreState()
if event == ord(","):
leds.clear()
if event == ord("f"):
leds.flashInf(50, 255, 255, 255)
if event == ord("g"):
leds.flashAlt(50, 255, 255, 255)
if event == ord("h"):
leds.sparkle(100, 255, 255, 255)
if event == ord("j"):
leds.flame(15)
if event == ord("k"):
leds.sparkleFade(15, 15, 255, 255, 255)
if event == ord("l"):
leds.glow(1)
#if event == ord("."):
# camera.capture('/var/www/html/snaps/' + str(gtime.time()) + '.jpg')
dt1.check(time)
except OSError:
errors += 1
pass
#################################################################################
# Seven Segment Score Display
#################################################################################
if lastScore != score.val:
sevSegL.clear()
sevSegR.clear()
strString = str(score.val)
lStrString = strString[:-4]
rStrString = strString[-4:]
if rStrString is '': rStrString = '0'
sevSegL.print_number_str(lStrString)
if score.val > 9999: rStrString = rStrString.zfill(4)
sevSegR.print_number_str(rStrString)
sevSegL.write_display()
sevSegR.write_display()
lastScore = score.val
# Debug Information
screen.addstr(12, 12, "Super Pinball 3000! Ticks thus far: " + str(time).ljust(20," "))
screen.addstr(14, 12, "SCORE: " + str(score.val).ljust(20," "))
screen.addstr(15, 12, "IO STATUS: " + io_string.ljust(20," "))
screen.addstr(16, 12, "Deb reg: " + str(io.bouncereg[0]).ljust(20," "))
screen.addstr(17, 12, "Deb time: " + str(io.debtime[0]).ljust(20," "))
#screen.addstr(17, 12, "Temp: " + str(ufoServo.calc).ljust(20," "))
screen.addstr(18, 12, "OSErrors: " + str(errors).ljust(20," "))
#screen.addstr(17, 12, "Step: " + str(countAnim.step).ljust(20," "))
#screen.addstr(18, 12, "Debug: " + str(debugString).ljust(20," "))
#if(time % 2 == 0): axis.update()
#screen.addstr(17, 12, "XYZ T: " + str(axis.valX).ljust(6," ") + " " + \
# str(axis.valY).ljust(6," ") + " " + \
# str(axis.valZ).ljust(6," ") + " " + \
# str(axis.tilt_delta).ljust(20," "))
#screen.addstr(18, 12, "Tilted: " + str(axis.tilted).ljust(20," "))
clock.tick(150)
#################################################################################
# END Main Game Loop
#################################################################################
clean_exit(message="Exited normally")
|
[] |
[] |
[
"SDL_VIDEODRIVER"
] |
[]
|
["SDL_VIDEODRIVER"]
|
python
| 1 | 0 | |
src/test/java/org/kohsuke/github/GitHubConnectionTest.java
|
package org.kohsuke.github;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
/**
* Unit test for {@link GitHub}.
*/
public class GitHubConnectionTest extends AbstractGitHubWireMockTest {
public GitHubConnectionTest() {
useDefaultGitHub = false;
}
@Test
public void testOffline() throws Exception {
GitHub hub = GitHub.offline();
assertEquals("https://api.github.invalid/test", hub.getApiURL("/test").toString());
assertTrue(hub.isAnonymous());
try {
hub.getRateLimit();
fail("Offline instance should always fail");
} catch (IOException e) {
assertEquals("Offline", e.getMessage());
}
}
@Test
public void testGitHubServerWithHttp() throws Exception {
GitHub hub = GitHub.connectToEnterprise("http://enterprise.kohsuke.org/api/v3", "bogus", "bogus");
assertEquals("http://enterprise.kohsuke.org/api/v3/test", hub.getApiURL("/test").toString());
}
@Test
public void testGitHubServerWithHttps() throws Exception {
GitHub hub = GitHub.connectToEnterprise("https://enterprise.kohsuke.org/api/v3", "bogus", "bogus");
assertEquals("https://enterprise.kohsuke.org/api/v3/test", hub.getApiURL("/test").toString());
}
@Test
public void testGitHubServerWithoutServer() throws Exception {
GitHub hub = GitHub.connectUsingPassword("kohsuke", "bogus");
assertEquals("https://api.github.com/test", hub.getApiURL("/test").toString());
}
@Test
public void testGitHubBuilderFromEnvironment() throws IOException {
Map<String, String> props = new HashMap<String, String>();
props.put("login", "bogus");
props.put("oauth", "bogus");
props.put("password", "bogus");
props.put("jwt", "bogus");
setupEnvironment(props);
GitHubBuilder builder = GitHubBuilder.fromEnvironment();
assertEquals("bogus", builder.user);
assertEquals("bogus", builder.oauthToken);
assertEquals("bogus", builder.password);
assertEquals("bogus", builder.jwtToken);
}
@Test
public void testGitHubBuilderFromCustomEnvironment() throws IOException {
Map<String, String> props = new HashMap<String, String>();
props.put("customLogin", "bogusLogin");
props.put("customOauth", "bogusOauth");
props.put("customPassword", "bogusPassword");
props.put("customEndpoint", "bogusEndpoint");
setupEnvironment(props);
GitHubBuilder builder = GitHubBuilder
.fromEnvironment("customLogin", "customPassword", "customOauth", "customEndpoint");
assertEquals("bogusLogin", builder.user);
assertEquals("bogusOauth", builder.oauthToken);
assertEquals("bogusPassword", builder.password);
assertEquals("bogusEndpoint", builder.endpoint);
}
@Test
public void testGithubBuilderWithAppInstallationToken() throws Exception {
GitHubBuilder builder = new GitHubBuilder().withAppInstallationToken("bogus");
assertEquals("bogus", builder.oauthToken);
assertEquals("", builder.user);
// test authorization header is set as in the RFC6749
GitHub github = builder.build();
assertEquals("token bogus", github.encodedAuthorization);
assertEquals("", github.login);
}
@Ignore
@Test
public void testGitHubIsApiUrlValid() throws IOException {
GitHub hub = GitHub.connectAnonymously();
// GitHub hub = GitHub.connectToEnterpriseAnonymously(mockGitHub.apiServer().baseUrl());
try {
hub.checkApiUrlValidity();
} catch (IOException ioe) {
assertTrue(ioe.getMessage().contains("private mode enabled"));
}
}
/*
* Copied from StackOverflow: http://stackoverflow.com/a/7201825/2336755
*
* This allows changing the in memory process environment.
*
* Its used to wire in values for the github credentials to test that the GitHubBuilder works properly to resolve
* them.
*/
private void setupEnvironment(Map<String, String> newenv) {
try {
Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
env.putAll(newenv);
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
cienv.putAll(newenv);
} catch (NoSuchFieldException e) {
try {
Class[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for (Class cl : classes) {
if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
Map<String, String> map = (Map<String, String>) obj;
map.clear();
map.putAll(newenv);
}
}
} catch (Exception e2) {
e2.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
|
[] |
[] |
[] |
[]
|
[]
|
java
| 0 | 0 | |
src/cmd/compile/internal/gc/main.go
|
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run mkbuiltin.go
package gc
import (
"bufio"
"bytes"
"cmd/compile/internal/ssa"
"cmd/compile/internal/types"
"cmd/internal/bio"
"cmd/internal/dwarf"
"cmd/internal/obj"
"cmd/internal/objabi"
"cmd/internal/src"
"cmd/internal/sys"
"flag"
"fmt"
"internal/goversion"
"io"
"io/ioutil"
"log"
"os"
"path"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
)
var imported_unsafe bool
var (
buildid string
)
var (
Debug_append int
Debug_closure int
Debug_compilelater int
debug_dclstack int
Debug_panic int
Debug_slice int
Debug_vlog bool
Debug_wb int
Debug_pctab string
Debug_locationlist int
Debug_typecheckinl int
Debug_gendwarfinl int
Debug_softfloat int
)
// Debug arguments.
// These can be specified with the -d flag, as in "-d nil"
// to set the debug_checknil variable.
// Multiple options can be comma-separated.
// Each option accepts an optional argument, as in "gcprog=2"
var debugtab = []struct {
name string
help string
val interface{} // must be *int or *string
}{
{"append", "print information about append compilation", &Debug_append},
{"closure", "print information about closure compilation", &Debug_closure},
{"compilelater", "compile functions as late as possible", &Debug_compilelater},
{"disablenil", "disable nil checks", &disable_checknil},
{"dclstack", "run internal dclstack check", &debug_dclstack},
{"gcprog", "print dump of GC programs", &Debug_gcprog},
{"nil", "print information about nil checks", &Debug_checknil},
{"panic", "do not hide any compiler panic", &Debug_panic},
{"slice", "print information about slice compilation", &Debug_slice},
{"typeassert", "print information about type assertion inlining", &Debug_typeassert},
{"wb", "print information about write barriers", &Debug_wb},
{"export", "print export data", &Debug_export},
{"pctab", "print named pc-value table", &Debug_pctab},
{"locationlists", "print information about DWARF location list creation", &Debug_locationlist},
{"typecheckinl", "eager typechecking of inline function bodies", &Debug_typecheckinl},
{"dwarfinl", "print information about DWARF inlined function creation", &Debug_gendwarfinl},
{"softfloat", "force compiler to emit soft-float code", &Debug_softfloat},
}
const debugHelpHeader = `usage: -d arg[,arg]* and arg is <key>[=<value>]
<key> is one of:
`
const debugHelpFooter = `
<value> is key-specific.
Key "pctab" supports values:
"pctospadj", "pctofile", "pctoline", "pctoinline", "pctopcdata"
`
func usage() {
fmt.Fprintf(os.Stderr, "usage: compile [options] file.go...\n")
objabi.Flagprint(os.Stderr)
Exit(2)
}
func hidePanic() {
if Debug_panic == 0 && nsavederrors+nerrors > 0 {
// If we've already complained about things
// in the program, don't bother complaining
// about a panic too; let the user clean up
// the code and try again.
if err := recover(); err != nil {
errorexit()
}
}
}
// supportsDynlink reports whether or not the code generator for the given
// architecture supports the -shared and -dynlink flags.
func supportsDynlink(arch *sys.Arch) bool {
return arch.InFamily(sys.AMD64, sys.ARM, sys.ARM64, sys.I386, sys.PPC64, sys.S390X)
}
// timing data for compiler phases
var timings Timings
var benchfile string
var nowritebarrierrecCheck *nowritebarrierrecChecker
// Main parses flags and Go source files specified in the command-line
// arguments, type-checks the parsed Go package, compiles functions to machine
// code, and finally writes the compiled package definition to disk.
func Main(archInit func(*Arch)) {
timings.Start("fe", "init")
defer hidePanic()
archInit(&thearch)
Ctxt = obj.Linknew(thearch.LinkArch)
Ctxt.DiagFunc = yyerror
Ctxt.DiagFlush = flusherrors
Ctxt.Bso = bufio.NewWriter(os.Stdout)
// UseBASEntries is preferred because it shaves about 2% off build time, but LLDB, dsymutil, and dwarfdump
// on Darwin don't support it properly, especially since macOS 10.14 (Mojave). This is exposed as a flag
// to allow testing with LLVM tools on Linux, and to help with reporting this bug to the LLVM project.
// See bugs 31188 and 21945 (CLs 170638, 98075, 72371).
Ctxt.UseBASEntries = Ctxt.Headtype != objabi.Hdarwin
localpkg = types.NewPkg("", "")
localpkg.Prefix = "\"\""
// We won't know localpkg's height until after import
// processing. In the mean time, set to MaxPkgHeight to ensure
// height comparisons at least work until then.
localpkg.Height = types.MaxPkgHeight
// pseudo-package, for scoping
builtinpkg = types.NewPkg("go.builtin", "") // TODO(gri) name this package go.builtin?
builtinpkg.Prefix = "go.builtin" // not go%2ebuiltin
// pseudo-package, accessed by import "unsafe"
unsafepkg = types.NewPkg("unsafe", "unsafe")
// Pseudo-package that contains the compiler's builtin
// declarations for package runtime. These are declared in a
// separate package to avoid conflicts with package runtime's
// actual declarations, which may differ intentionally but
// insignificantly.
Runtimepkg = types.NewPkg("go.runtime", "runtime")
Runtimepkg.Prefix = "runtime"
// pseudo-packages used in symbol tables
itabpkg = types.NewPkg("go.itab", "go.itab")
itabpkg.Prefix = "go.itab" // not go%2eitab
itablinkpkg = types.NewPkg("go.itablink", "go.itablink")
itablinkpkg.Prefix = "go.itablink" // not go%2eitablink
trackpkg = types.NewPkg("go.track", "go.track")
trackpkg.Prefix = "go.track" // not go%2etrack
// pseudo-package used for map zero values
mappkg = types.NewPkg("go.map", "go.map")
mappkg.Prefix = "go.map"
// pseudo-package used for methods with anonymous receivers
gopkg = types.NewPkg("go", "")
Nacl = objabi.GOOS == "nacl"
Wasm := objabi.GOARCH == "wasm"
// Whether the limit for stack-allocated objects is much smaller than normal.
// This can be helpful for diagnosing certain causes of GC latency. See #27732.
smallFrames := false
flag.BoolVar(&compiling_runtime, "+", false, "compiling runtime")
flag.BoolVar(&compiling_std, "std", false, "compiling standard library")
objabi.Flagcount("%", "debug non-static initializers", &Debug['%'])
objabi.Flagcount("B", "disable bounds checking", &Debug['B'])
objabi.Flagcount("C", "disable printing of columns in error messages", &Debug['C']) // TODO(gri) remove eventually
flag.StringVar(&localimport, "D", "", "set relative `path` for local imports")
objabi.Flagcount("E", "debug symbol export", &Debug['E'])
objabi.Flagfn1("I", "add `directory` to import search path", addidir)
objabi.Flagcount("K", "debug missing line numbers", &Debug['K'])
objabi.Flagcount("L", "show full file names in error messages", &Debug['L'])
objabi.Flagcount("N", "disable optimizations", &Debug['N'])
objabi.Flagcount("S", "print assembly listing", &Debug['S'])
objabi.AddVersionFlag() // -V
objabi.Flagcount("W", "debug parse tree after type checking", &Debug['W'])
flag.StringVar(&asmhdr, "asmhdr", "", "write assembly header to `file`")
flag.StringVar(&buildid, "buildid", "", "record `id` as the build id in the export metadata")
flag.IntVar(&nBackendWorkers, "c", 1, "concurrency during compilation, 1 means no concurrency")
flag.BoolVar(&pure_go, "complete", false, "compiling complete package (no C or assembly)")
flag.StringVar(&debugstr, "d", "", "print debug information about items in `list`; try -d help")
flag.BoolVar(&flagDWARF, "dwarf", !Wasm, "generate DWARF symbols")
flag.BoolVar(&Ctxt.Flag_locationlists, "dwarflocationlists", true, "add location lists to DWARF in optimized mode")
flag.IntVar(&genDwarfInline, "gendwarfinl", 2, "generate DWARF inline info records")
objabi.Flagcount("e", "no limit on number of errors reported", &Debug['e'])
objabi.Flagcount("h", "halt on error", &Debug['h'])
objabi.Flagfn1("importmap", "add `definition` of the form source=actual to import map", addImportMap)
objabi.Flagfn1("importcfg", "read import configuration from `file`", readImportCfg)
flag.StringVar(&flag_installsuffix, "installsuffix", "", "set pkg directory `suffix`")
objabi.Flagcount("j", "debug runtime-initialized variables", &Debug['j'])
objabi.Flagcount("l", "disable inlining", &Debug['l'])
flag.StringVar(&flag_lang, "lang", "", "release to compile for")
flag.StringVar(&linkobj, "linkobj", "", "write linker-specific object to `file`")
objabi.Flagcount("live", "debug liveness analysis", &debuglive)
objabi.Flagcount("m", "print optimization decisions", &Debug['m'])
if sys.MSanSupported(objabi.GOOS, objabi.GOARCH) {
flag.BoolVar(&flag_msan, "msan", false, "build code compatible with C/C++ memory sanitizer")
}
flag.BoolVar(&nolocalimports, "nolocalimports", false, "reject local (relative) imports")
flag.StringVar(&outfile, "o", "", "write output to `file`")
flag.StringVar(&myimportpath, "p", "", "set expected package import `path`")
flag.BoolVar(&writearchive, "pack", false, "write to file.a instead of file.o")
objabi.Flagcount("r", "debug generated wrappers", &Debug['r'])
if sys.RaceDetectorSupported(objabi.GOOS, objabi.GOARCH) {
flag.BoolVar(&flag_race, "race", false, "enable race detector")
}
if enableTrace {
flag.BoolVar(&trace, "t", false, "trace type-checking")
}
flag.StringVar(&pathPrefix, "trimpath", "", "remove `prefix` from recorded source file paths")
flag.BoolVar(&Debug_vlog, "v", false, "increase debug verbosity")
objabi.Flagcount("w", "debug type checking", &Debug['w'])
flag.BoolVar(&use_writebarrier, "wb", true, "enable write barrier")
var flag_shared bool
var flag_dynlink bool
if supportsDynlink(thearch.LinkArch.Arch) {
flag.BoolVar(&flag_shared, "shared", false, "generate code that can be linked into a shared library")
flag.BoolVar(&flag_dynlink, "dynlink", false, "support references to Go symbols defined in other shared libraries")
}
flag.StringVar(&cpuprofile, "cpuprofile", "", "write cpu profile to `file`")
flag.StringVar(&memprofile, "memprofile", "", "write memory profile to `file`")
flag.Int64Var(&memprofilerate, "memprofilerate", 0, "set runtime.MemProfileRate to `rate`")
var goversion string
flag.StringVar(&goversion, "goversion", "", "required version of the runtime")
var symabisPath string
flag.StringVar(&symabisPath, "symabis", "", "read symbol ABIs from `file`")
flag.StringVar(&traceprofile, "traceprofile", "", "write an execution trace to `file`")
flag.StringVar(&blockprofile, "blockprofile", "", "write block profile to `file`")
flag.StringVar(&mutexprofile, "mutexprofile", "", "write mutex profile to `file`")
flag.StringVar(&benchfile, "bench", "", "append benchmark times to `file`")
flag.BoolVar(&smallFrames, "smallframes", false, "reduce the size limit for stack allocated objects")
flag.BoolVar(&Ctxt.UseBASEntries, "dwarfbasentries", Ctxt.UseBASEntries, "use base address selection entries in DWARF")
objabi.Flagparse(usage)
// Record flags that affect the build result. (And don't
// record flags that don't, since that would cause spurious
// changes in the binary.)
recordFlags("B", "N", "l", "msan", "race", "shared", "dynlink", "dwarflocationlists", "dwarfbasentries", "smallframes")
if smallFrames {
maxStackVarSize = 128 * 1024
maxImplicitStackVarSize = 16 * 1024
}
Ctxt.Flag_shared = flag_dynlink || flag_shared
Ctxt.Flag_dynlink = flag_dynlink
Ctxt.Flag_optimize = Debug['N'] == 0
Ctxt.Debugasm = Debug['S']
Ctxt.Debugvlog = Debug_vlog
if flagDWARF {
Ctxt.DebugInfo = debuginfo
Ctxt.GenAbstractFunc = genAbstractFunc
Ctxt.DwFixups = obj.NewDwarfFixupTable(Ctxt)
} else {
// turn off inline generation if no dwarf at all
genDwarfInline = 0
Ctxt.Flag_locationlists = false
}
if flag.NArg() < 1 && debugstr != "help" && debugstr != "ssa/help" {
usage()
}
if goversion != "" && goversion != runtime.Version() {
fmt.Printf("compile: version %q does not match go tool version %q\n", runtime.Version(), goversion)
Exit(2)
}
checkLang()
if symabisPath != "" {
readSymABIs(symabisPath, myimportpath)
}
thearch.LinkArch.Init(Ctxt)
if outfile == "" {
p := flag.Arg(0)
if i := strings.LastIndex(p, "/"); i >= 0 {
p = p[i+1:]
}
if runtime.GOOS == "windows" {
if i := strings.LastIndex(p, `\`); i >= 0 {
p = p[i+1:]
}
}
if i := strings.LastIndex(p, "."); i >= 0 {
p = p[:i]
}
suffix := ".o"
if writearchive {
suffix = ".a"
}
outfile = p + suffix
}
startProfile()
if flag_race && flag_msan {
log.Fatal("cannot use both -race and -msan")
}
if ispkgin(omit_pkgs) {
flag_race = false
flag_msan = false
}
if flag_race {
racepkg = types.NewPkg("runtime/race", "")
}
if flag_msan {
msanpkg = types.NewPkg("runtime/msan", "")
}
if flag_race || flag_msan {
instrumenting = true
}
if compiling_runtime && Debug['N'] != 0 {
log.Fatal("cannot disable optimizations while compiling runtime")
}
if nBackendWorkers < 1 {
log.Fatalf("-c must be at least 1, got %d", nBackendWorkers)
}
if nBackendWorkers > 1 && !concurrentBackendAllowed() {
log.Fatalf("cannot use concurrent backend compilation with provided flags; invoked as %v", os.Args)
}
if Ctxt.Flag_locationlists && len(Ctxt.Arch.DWARFRegisters) == 0 {
log.Fatalf("location lists requested but register mapping not available on %v", Ctxt.Arch.Name)
}
// parse -d argument
if debugstr != "" {
Split:
for _, name := range strings.Split(debugstr, ",") {
if name == "" {
continue
}
// display help about the -d option itself and quit
if name == "help" {
fmt.Print(debugHelpHeader)
maxLen := len("ssa/help")
for _, t := range debugtab {
if len(t.name) > maxLen {
maxLen = len(t.name)
}
}
for _, t := range debugtab {
fmt.Printf("\t%-*s\t%s\n", maxLen, t.name, t.help)
}
// ssa options have their own help
fmt.Printf("\t%-*s\t%s\n", maxLen, "ssa/help", "print help about SSA debugging")
fmt.Print(debugHelpFooter)
os.Exit(0)
}
val, valstring, haveInt := 1, "", true
if i := strings.IndexAny(name, "=:"); i >= 0 {
var err error
name, valstring = name[:i], name[i+1:]
val, err = strconv.Atoi(valstring)
if err != nil {
val, haveInt = 1, false
}
}
for _, t := range debugtab {
if t.name != name {
continue
}
switch vp := t.val.(type) {
case nil:
// Ignore
case *string:
*vp = valstring
case *int:
if !haveInt {
log.Fatalf("invalid debug value %v", name)
}
*vp = val
default:
panic("bad debugtab type")
}
continue Split
}
// special case for ssa for now
if strings.HasPrefix(name, "ssa/") {
// expect form ssa/phase/flag
// e.g. -d=ssa/generic_cse/time
// _ in phase name also matches space
phase := name[4:]
flag := "debug" // default flag is debug
if i := strings.Index(phase, "/"); i >= 0 {
flag = phase[i+1:]
phase = phase[:i]
}
err := ssa.PhaseOption(phase, flag, val, valstring)
if err != "" {
log.Fatalf(err)
}
continue Split
}
log.Fatalf("unknown debug key -d %s\n", name)
}
}
// set via a -d flag
Ctxt.Debugpcln = Debug_pctab
if flagDWARF {
dwarf.EnableLogging(Debug_gendwarfinl != 0)
}
if Debug_softfloat != 0 {
thearch.SoftFloat = true
}
// enable inlining. for now:
// default: inlining on. (debug['l'] == 1)
// -l: inlining off (debug['l'] == 0)
// -l=2, -l=3: inlining on again, with extra debugging (debug['l'] > 1)
if Debug['l'] <= 1 {
Debug['l'] = 1 - Debug['l']
}
ssaDump = os.Getenv("GOSSAFUNC")
if ssaDump != "" {
if strings.HasSuffix(ssaDump, "+") {
ssaDump = ssaDump[:len(ssaDump)-1]
ssaDumpStdout = true
}
spl := strings.Split(ssaDump, ":")
if len(spl) > 1 {
ssaDump = spl[0]
ssaDumpCFG = spl[1]
}
}
trackScopes = flagDWARF
Widthptr = thearch.LinkArch.PtrSize
Widthreg = thearch.LinkArch.RegSize
// initialize types package
// (we need to do this to break dependencies that otherwise
// would lead to import cycles)
types.Widthptr = Widthptr
types.Dowidth = dowidth
types.Fatalf = Fatalf
types.Sconv = func(s *types.Sym, flag, mode int) string {
return sconv(s, FmtFlag(flag), fmtMode(mode))
}
types.Tconv = func(t *types.Type, flag, mode, depth int) string {
return tconv(t, FmtFlag(flag), fmtMode(mode), depth)
}
types.FormatSym = func(sym *types.Sym, s fmt.State, verb rune, mode int) {
symFormat(sym, s, verb, fmtMode(mode))
}
types.FormatType = func(t *types.Type, s fmt.State, verb rune, mode int) {
typeFormat(t, s, verb, fmtMode(mode))
}
types.TypeLinkSym = func(t *types.Type) *obj.LSym {
return typenamesym(t).Linksym()
}
types.FmtLeft = int(FmtLeft)
types.FmtUnsigned = int(FmtUnsigned)
types.FErr = FErr
types.Ctxt = Ctxt
initUniverse()
dclcontext = PEXTERN
nerrors = 0
autogeneratedPos = makePos(src.NewFileBase("<autogenerated>", "<autogenerated>"), 1, 0)
timings.Start("fe", "loadsys")
loadsys()
timings.Start("fe", "parse")
lines := parseFiles(flag.Args())
timings.Stop()
timings.AddEvent(int64(lines), "lines")
finishUniverse()
recordPackageName()
typecheckok = true
// Process top-level declarations in phases.
// Phase 1: const, type, and names and types of funcs.
// This will gather all the information about types
// and methods but doesn't depend on any of it.
//
// We also defer type alias declarations until phase 2
// to avoid cycles like #18640.
// TODO(gri) Remove this again once we have a fix for #25838.
// Don't use range--typecheck can add closures to xtop.
timings.Start("fe", "typecheck", "top1")
for i := 0; i < len(xtop); i++ {
n := xtop[i]
if op := n.Op; op != ODCL && op != OAS && op != OAS2 && (op != ODCLTYPE || !n.Left.Name.Param.Alias) {
xtop[i] = typecheck(n, ctxStmt)
}
}
// Phase 2: Variable assignments.
// To check interface assignments, depends on phase 1.
// Don't use range--typecheck can add closures to xtop.
timings.Start("fe", "typecheck", "top2")
for i := 0; i < len(xtop); i++ {
n := xtop[i]
if op := n.Op; op == ODCL || op == OAS || op == OAS2 || op == ODCLTYPE && n.Left.Name.Param.Alias {
xtop[i] = typecheck(n, ctxStmt)
}
}
// Phase 3: Type check function bodies.
// Don't use range--typecheck can add closures to xtop.
timings.Start("fe", "typecheck", "func")
var fcount int64
for i := 0; i < len(xtop); i++ {
n := xtop[i]
if op := n.Op; op == ODCLFUNC || op == OCLOSURE {
Curfn = n
decldepth = 1
saveerrors()
typecheckslice(Curfn.Nbody.Slice(), ctxStmt)
checkreturn(Curfn)
if nerrors != 0 {
Curfn.Nbody.Set(nil) // type errors; do not compile
}
// Now that we've checked whether n terminates,
// we can eliminate some obviously dead code.
deadcode(Curfn)
fcount++
}
}
// With all types checked, it's now safe to verify map keys. One single
// check past phase 9 isn't sufficient, as we may exit with other errors
// before then, thus skipping map key errors.
checkMapKeys()
timings.AddEvent(fcount, "funcs")
if nsavederrors+nerrors != 0 {
errorexit()
}
// Phase 4: Decide how to capture closed variables.
// This needs to run before escape analysis,
// because variables captured by value do not escape.
timings.Start("fe", "capturevars")
for _, n := range xtop {
if n.Op == ODCLFUNC && n.Func.Closure != nil {
Curfn = n
capturevars(n)
}
}
capturevarscomplete = true
Curfn = nil
if nsavederrors+nerrors != 0 {
errorexit()
}
// Phase 5: Inlining
timings.Start("fe", "inlining")
if Debug_typecheckinl != 0 {
// Typecheck imported function bodies if debug['l'] > 1,
// otherwise lazily when used or re-exported.
for _, n := range importlist {
if n.Func.Inl != nil {
saveerrors()
typecheckinl(n)
}
}
if nsavederrors+nerrors != 0 {
errorexit()
}
}
if Debug['l'] != 0 {
// Find functions that can be inlined and clone them before walk expands them.
visitBottomUp(xtop, func(list []*Node, recursive bool) {
for _, n := range list {
if !recursive {
caninl(n)
} else {
if Debug['m'] > 1 {
fmt.Printf("%v: cannot inline %v: recursive\n", n.Line(), n.Func.Nname)
}
}
inlcalls(n)
}
})
}
// Phase 6: Escape analysis.
// Required for moving heap allocations onto stack,
// which in turn is required by the closure implementation,
// which stores the addresses of stack variables into the closure.
// If the closure does not escape, it needs to be on the stack
// or else the stack copier will not update it.
// Large values are also moved off stack in escape analysis;
// because large values may contain pointers, it must happen early.
timings.Start("fe", "escapes")
escapes(xtop)
// Collect information for go:nowritebarrierrec
// checking. This must happen before transformclosure.
// We'll do the final check after write barriers are
// inserted.
if compiling_runtime {
nowritebarrierrecCheck = newNowritebarrierrecChecker()
}
// Phase 7: Transform closure bodies to properly reference captured variables.
// This needs to happen before walk, because closures must be transformed
// before walk reaches a call of a closure.
timings.Start("fe", "xclosures")
for _, n := range xtop {
if n.Op == ODCLFUNC && n.Func.Closure != nil {
Curfn = n
transformclosure(n)
}
}
// Prepare for SSA compilation.
// This must be before peekitabs, because peekitabs
// can trigger function compilation.
initssaconfig()
// Just before compilation, compile itabs found on
// the right side of OCONVIFACE so that methods
// can be de-virtualized during compilation.
Curfn = nil
peekitabs()
// Phase 8: Compile top level functions.
// Don't use range--walk can add functions to xtop.
timings.Start("be", "compilefuncs")
fcount = 0
for i := 0; i < len(xtop); i++ {
n := xtop[i]
if n.Op == ODCLFUNC {
funccompile(n)
fcount++
}
}
timings.AddEvent(fcount, "funcs")
if nsavederrors+nerrors == 0 {
fninit(xtop)
}
compileFunctions()
if nowritebarrierrecCheck != nil {
// Write barriers are now known. Check the
// call graph.
nowritebarrierrecCheck.check()
nowritebarrierrecCheck = nil
}
// Finalize DWARF inline routine DIEs, then explicitly turn off
// DWARF inlining gen so as to avoid problems with generated
// method wrappers.
if Ctxt.DwFixups != nil {
Ctxt.DwFixups.Finalize(myimportpath, Debug_gendwarfinl != 0)
Ctxt.DwFixups = nil
genDwarfInline = 0
}
// Phase 9: Check external declarations.
timings.Start("be", "externaldcls")
for i, n := range externdcl {
if n.Op == ONAME {
externdcl[i] = typecheck(externdcl[i], ctxExpr)
}
}
// Check the map keys again, since we typechecked the external
// declarations.
checkMapKeys()
if nerrors+nsavederrors != 0 {
errorexit()
}
// Write object data to disk.
timings.Start("be", "dumpobj")
dumpobj()
if asmhdr != "" {
dumpasmhdr()
}
// Check whether any of the functions we have compiled have gigantic stack frames.
sort.Slice(largeStackFrames, func(i, j int) bool {
return largeStackFrames[i].pos.Before(largeStackFrames[j].pos)
})
for _, large := range largeStackFrames {
if large.callee != 0 {
yyerrorl(large.pos, "stack frame too large (>1GB): %d MB locals + %d MB args + %d MB callee", large.locals>>20, large.args>>20, large.callee>>20)
} else {
yyerrorl(large.pos, "stack frame too large (>1GB): %d MB locals + %d MB args", large.locals>>20, large.args>>20)
}
}
if len(compilequeue) != 0 {
Fatalf("%d uncompiled functions", len(compilequeue))
}
if nerrors+nsavederrors != 0 {
errorexit()
}
flusherrors()
timings.Stop()
if benchfile != "" {
if err := writebench(benchfile); err != nil {
log.Fatalf("cannot write benchmark data: %v", err)
}
}
}
func writebench(filename string) error {
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
return err
}
var buf bytes.Buffer
fmt.Fprintln(&buf, "commit:", objabi.Version)
fmt.Fprintln(&buf, "goos:", runtime.GOOS)
fmt.Fprintln(&buf, "goarch:", runtime.GOARCH)
timings.Write(&buf, "BenchmarkCompile:"+myimportpath+":")
n, err := f.Write(buf.Bytes())
if err != nil {
return err
}
if n != buf.Len() {
panic("bad writer")
}
return f.Close()
}
var (
importMap = map[string]string{}
packageFile map[string]string // nil means not in use
)
func addImportMap(s string) {
if strings.Count(s, "=") != 1 {
log.Fatal("-importmap argument must be of the form source=actual")
}
i := strings.Index(s, "=")
source, actual := s[:i], s[i+1:]
if source == "" || actual == "" {
log.Fatal("-importmap argument must be of the form source=actual; source and actual must be non-empty")
}
importMap[source] = actual
}
func readImportCfg(file string) {
packageFile = map[string]string{}
data, err := ioutil.ReadFile(file)
if err != nil {
log.Fatalf("-importcfg: %v", err)
}
for lineNum, line := range strings.Split(string(data), "\n") {
lineNum++ // 1-based
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
var verb, args string
if i := strings.Index(line, " "); i < 0 {
verb = line
} else {
verb, args = line[:i], strings.TrimSpace(line[i+1:])
}
var before, after string
if i := strings.Index(args, "="); i >= 0 {
before, after = args[:i], args[i+1:]
}
switch verb {
default:
log.Fatalf("%s:%d: unknown directive %q", file, lineNum, verb)
case "importmap":
if before == "" || after == "" {
log.Fatalf(`%s:%d: invalid importmap: syntax is "importmap old=new"`, file, lineNum)
}
importMap[before] = after
case "packagefile":
if before == "" || after == "" {
log.Fatalf(`%s:%d: invalid packagefile: syntax is "packagefile path=filename"`, file, lineNum)
}
packageFile[before] = after
}
}
}
// symabiDefs and symabiRefs record the defined and referenced ABIs of
// symbols required by non-Go code. These are keyed by link symbol
// name, where the local package prefix is always `"".`
var symabiDefs, symabiRefs map[string]obj.ABI
// readSymABIs reads a symabis file that specifies definitions and
// references of text symbols by ABI.
//
// The symabis format is a set of lines, where each line is a sequence
// of whitespace-separated fields. The first field is a verb and is
// either "def" for defining a symbol ABI or "ref" for referencing a
// symbol using an ABI. For both "def" and "ref", the second field is
// the symbol name and the third field is the ABI name, as one of the
// named cmd/internal/obj.ABI constants.
func readSymABIs(file, myimportpath string) {
data, err := ioutil.ReadFile(file)
if err != nil {
log.Fatalf("-symabis: %v", err)
}
symabiDefs = make(map[string]obj.ABI)
symabiRefs = make(map[string]obj.ABI)
localPrefix := ""
if myimportpath != "" {
// Symbols in this package may be written either as
// "".X or with the package's import path already in
// the symbol.
localPrefix = objabi.PathToPrefix(myimportpath) + "."
}
for lineNum, line := range strings.Split(string(data), "\n") {
lineNum++ // 1-based
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.Fields(line)
switch parts[0] {
case "def", "ref":
// Parse line.
if len(parts) != 3 {
log.Fatalf(`%s:%d: invalid symabi: syntax is "%s sym abi"`, file, lineNum, parts[0])
}
sym, abi := parts[1], parts[2]
if abi != "ABI0" { // Only supported external ABI right now
log.Fatalf(`%s:%d: invalid symabi: unknown abi "%s"`, file, lineNum, abi)
}
// If the symbol is already prefixed with
// myimportpath, rewrite it to start with ""
// so it matches the compiler's internal
// symbol names.
if localPrefix != "" && strings.HasPrefix(sym, localPrefix) {
sym = `"".` + sym[len(localPrefix):]
}
// Record for later.
if parts[0] == "def" {
symabiDefs[sym] = obj.ABI0
} else {
symabiRefs[sym] = obj.ABI0
}
default:
log.Fatalf(`%s:%d: invalid symabi type "%s"`, file, lineNum, parts[0])
}
}
}
func saveerrors() {
nsavederrors += nerrors
nerrors = 0
}
func arsize(b *bufio.Reader, name string) int {
var buf [ArhdrSize]byte
if _, err := io.ReadFull(b, buf[:]); err != nil {
return -1
}
aname := strings.Trim(string(buf[0:16]), " ")
if !strings.HasPrefix(aname, name) {
return -1
}
asize := strings.Trim(string(buf[48:58]), " ")
i, _ := strconv.Atoi(asize)
return i
}
var idirs []string
func addidir(dir string) {
if dir != "" {
idirs = append(idirs, dir)
}
}
func isDriveLetter(b byte) bool {
return 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z'
}
// is this path a local name? begins with ./ or ../ or /
func islocalname(name string) bool {
return strings.HasPrefix(name, "/") ||
runtime.GOOS == "windows" && len(name) >= 3 && isDriveLetter(name[0]) && name[1] == ':' && name[2] == '/' ||
strings.HasPrefix(name, "./") || name == "." ||
strings.HasPrefix(name, "../") || name == ".."
}
func findpkg(name string) (file string, ok bool) {
if islocalname(name) {
if nolocalimports {
return "", false
}
if packageFile != nil {
file, ok = packageFile[name]
return file, ok
}
// try .a before .6. important for building libraries:
// if there is an array.6 in the array.a library,
// want to find all of array.a, not just array.6.
file = fmt.Sprintf("%s.a", name)
if _, err := os.Stat(file); err == nil {
return file, true
}
file = fmt.Sprintf("%s.o", name)
if _, err := os.Stat(file); err == nil {
return file, true
}
return "", false
}
// local imports should be canonicalized already.
// don't want to see "encoding/../encoding/base64"
// as different from "encoding/base64".
if q := path.Clean(name); q != name {
yyerror("non-canonical import path %q (should be %q)", name, q)
return "", false
}
if packageFile != nil {
file, ok = packageFile[name]
return file, ok
}
for _, dir := range idirs {
file = fmt.Sprintf("%s/%s.a", dir, name)
if _, err := os.Stat(file); err == nil {
return file, true
}
file = fmt.Sprintf("%s/%s.o", dir, name)
if _, err := os.Stat(file); err == nil {
return file, true
}
}
if objabi.GOROOT != "" {
suffix := ""
suffixsep := ""
if flag_installsuffix != "" {
suffixsep = "_"
suffix = flag_installsuffix
} else if flag_race {
suffixsep = "_"
suffix = "race"
} else if flag_msan {
suffixsep = "_"
suffix = "msan"
}
file = fmt.Sprintf("%s/pkg/%s_%s%s%s/%s.a", objabi.GOROOT, objabi.GOOS, objabi.GOARCH, suffixsep, suffix, name)
if _, err := os.Stat(file); err == nil {
return file, true
}
file = fmt.Sprintf("%s/pkg/%s_%s%s%s/%s.o", objabi.GOROOT, objabi.GOOS, objabi.GOARCH, suffixsep, suffix, name)
if _, err := os.Stat(file); err == nil {
return file, true
}
}
return "", false
}
// loadsys loads the definitions for the low-level runtime functions,
// so that the compiler can generate calls to them,
// but does not make them visible to user code.
func loadsys() {
types.Block = 1
inimport = true
typecheckok = true
typs := runtimeTypes()
for _, d := range runtimeDecls {
sym := Runtimepkg.Lookup(d.name)
typ := typs[d.typ]
switch d.tag {
case funcTag:
importfunc(Runtimepkg, src.NoXPos, sym, typ)
case varTag:
importvar(Runtimepkg, src.NoXPos, sym, typ)
default:
Fatalf("unhandled declaration tag %v", d.tag)
}
}
typecheckok = false
inimport = false
}
// myheight tracks the local package's height based on packages
// imported so far.
var myheight int
func importfile(f *Val) *types.Pkg {
path_, ok := f.U.(string)
if !ok {
yyerror("import path must be a string")
return nil
}
if len(path_) == 0 {
yyerror("import path is empty")
return nil
}
if isbadimport(path_, false) {
return nil
}
// The package name main is no longer reserved,
// but we reserve the import path "main" to identify
// the main package, just as we reserve the import
// path "math" to identify the standard math package.
if path_ == "main" {
yyerror("cannot import \"main\"")
errorexit()
}
if myimportpath != "" && path_ == myimportpath {
yyerror("import %q while compiling that package (import cycle)", path_)
errorexit()
}
if mapped, ok := importMap[path_]; ok {
path_ = mapped
}
if path_ == "unsafe" {
imported_unsafe = true
return unsafepkg
}
if islocalname(path_) {
if path_[0] == '/' {
yyerror("import path cannot be absolute path")
return nil
}
prefix := Ctxt.Pathname
if localimport != "" {
prefix = localimport
}
path_ = path.Join(prefix, path_)
if isbadimport(path_, true) {
return nil
}
}
file, found := findpkg(path_)
if !found {
yyerror("can't find import: %q", path_)
errorexit()
}
importpkg := types.NewPkg(path_, "")
if importpkg.Imported {
return importpkg
}
importpkg.Imported = true
imp, err := bio.Open(file)
if err != nil {
yyerror("can't open import: %q: %v", path_, err)
errorexit()
}
defer imp.Close()
// check object header
p, err := imp.ReadString('\n')
if err != nil {
yyerror("import %s: reading input: %v", file, err)
errorexit()
}
if p == "!<arch>\n" { // package archive
// package export block should be first
sz := arsize(imp.Reader, "__.PKGDEF")
if sz <= 0 {
yyerror("import %s: not a package file", file)
errorexit()
}
p, err = imp.ReadString('\n')
if err != nil {
yyerror("import %s: reading input: %v", file, err)
errorexit()
}
}
if !strings.HasPrefix(p, "go object ") {
yyerror("import %s: not a go object file: %s", file, p)
errorexit()
}
q := fmt.Sprintf("%s %s %s %s\n", objabi.GOOS, objabi.GOARCH, objabi.Version, objabi.Expstring())
if p[10:] != q {
yyerror("import %s: object is [%s] expected [%s]", file, p[10:], q)
errorexit()
}
// process header lines
for {
p, err = imp.ReadString('\n')
if err != nil {
yyerror("import %s: reading input: %v", file, err)
errorexit()
}
if p == "\n" {
break // header ends with blank line
}
}
// assume files move (get installed) so don't record the full path
if packageFile != nil {
// If using a packageFile map, assume path_ can be recorded directly.
Ctxt.AddImport(path_)
} else {
// For file "/Users/foo/go/pkg/darwin_amd64/math.a" record "math.a".
Ctxt.AddImport(file[len(file)-len(path_)-len(".a"):])
}
// In the importfile, if we find:
// $$\n (textual format): not supported anymore
// $$B\n (binary format) : import directly, then feed the lexer a dummy statement
// look for $$
var c byte
for {
c, err = imp.ReadByte()
if err != nil {
break
}
if c == '$' {
c, err = imp.ReadByte()
if c == '$' || err != nil {
break
}
}
}
// get character after $$
if err == nil {
c, _ = imp.ReadByte()
}
switch c {
case '\n':
yyerror("cannot import %s: old export format no longer supported (recompile library)", path_)
return nil
case 'B':
if Debug_export != 0 {
fmt.Printf("importing %s (%s)\n", path_, file)
}
imp.ReadByte() // skip \n after $$B
c, err = imp.ReadByte()
if err != nil {
yyerror("import %s: reading input: %v", file, err)
errorexit()
}
// Indexed format is distinguished by an 'i' byte,
// whereas previous export formats started with 'c', 'd', or 'v'.
if c != 'i' {
yyerror("import %s: unexpected package format byte: %v", file, c)
errorexit()
}
iimport(importpkg, imp)
default:
yyerror("no import in %q", path_)
errorexit()
}
if importpkg.Height >= myheight {
myheight = importpkg.Height + 1
}
return importpkg
}
func pkgnotused(lineno src.XPos, path string, name string) {
// If the package was imported with a name other than the final
// import path element, show it explicitly in the error message.
// Note that this handles both renamed imports and imports of
// packages containing unconventional package declarations.
// Note that this uses / always, even on Windows, because Go import
// paths always use forward slashes.
elem := path
if i := strings.LastIndex(elem, "/"); i >= 0 {
elem = elem[i+1:]
}
if name == "" || elem == name {
yyerrorl(lineno, "imported and not used: %q", path)
} else {
yyerrorl(lineno, "imported and not used: %q as %s", path, name)
}
}
func mkpackage(pkgname string) {
if localpkg.Name == "" {
if pkgname == "_" {
yyerror("invalid package name _")
}
localpkg.Name = pkgname
} else {
if pkgname != localpkg.Name {
yyerror("package %s; expected %s", pkgname, localpkg.Name)
}
}
}
func clearImports() {
type importedPkg struct {
pos src.XPos
path string
name string
}
var unused []importedPkg
for _, s := range localpkg.Syms {
n := asNode(s.Def)
if n == nil {
continue
}
if n.Op == OPACK {
// throw away top-level package name left over
// from previous file.
// leave s->block set to cause redeclaration
// errors if a conflicting top-level name is
// introduced by a different file.
if !n.Name.Used() && nsyntaxerrors == 0 {
unused = append(unused, importedPkg{n.Pos, n.Name.Pkg.Path, s.Name})
}
s.Def = nil
continue
}
if IsAlias(s) {
// throw away top-level name left over
// from previous import . "x"
if n.Name != nil && n.Name.Pack != nil && !n.Name.Pack.Name.Used() && nsyntaxerrors == 0 {
unused = append(unused, importedPkg{n.Name.Pack.Pos, n.Name.Pack.Name.Pkg.Path, ""})
n.Name.Pack.Name.SetUsed(true)
}
s.Def = nil
continue
}
}
sort.Slice(unused, func(i, j int) bool { return unused[i].pos.Before(unused[j].pos) })
for _, pkg := range unused {
pkgnotused(pkg.pos, pkg.path, pkg.name)
}
}
func IsAlias(sym *types.Sym) bool {
return sym.Def != nil && asNode(sym.Def).Sym != sym
}
// By default, assume any debug flags are incompatible with concurrent compilation.
// A few are safe and potentially in common use for normal compiles, though; mark them as such here.
var concurrentFlagOK = [256]bool{
'B': true, // disabled bounds checking
'C': true, // disable printing of columns in error messages
'e': true, // no limit on errors; errors all come from non-concurrent code
'I': true, // add `directory` to import search path
'N': true, // disable optimizations
'l': true, // disable inlining
'w': true, // all printing happens before compilation
'W': true, // all printing happens before compilation
'S': true, // printing disassembly happens at the end (but see concurrentBackendAllowed below)
}
func concurrentBackendAllowed() bool {
for i, x := range Debug {
if x != 0 && !concurrentFlagOK[i] {
return false
}
}
// Debug['S'] by itself is ok, because all printing occurs
// while writing the object file, and that is non-concurrent.
// Adding Debug_vlog, however, causes Debug['S'] to also print
// while flushing the plist, which happens concurrently.
if Debug_vlog || debugstr != "" || debuglive > 0 {
return false
}
// TODO: Test and delete this condition.
if objabi.Fieldtrack_enabled != 0 {
return false
}
// TODO: fix races and enable the following flags
if Ctxt.Flag_shared || Ctxt.Flag_dynlink || flag_race {
return false
}
return true
}
// recordFlags records the specified command-line flags to be placed
// in the DWARF info.
func recordFlags(flags ...string) {
if myimportpath == "" {
// We can't record the flags if we don't know what the
// package name is.
return
}
type BoolFlag interface {
IsBoolFlag() bool
}
type CountFlag interface {
IsCountFlag() bool
}
var cmd bytes.Buffer
for _, name := range flags {
f := flag.Lookup(name)
if f == nil {
continue
}
getter := f.Value.(flag.Getter)
if getter.String() == f.DefValue {
// Flag has default value, so omit it.
continue
}
if bf, ok := f.Value.(BoolFlag); ok && bf.IsBoolFlag() {
val, ok := getter.Get().(bool)
if ok && val {
fmt.Fprintf(&cmd, " -%s", f.Name)
continue
}
}
if cf, ok := f.Value.(CountFlag); ok && cf.IsCountFlag() {
val, ok := getter.Get().(int)
if ok && val == 1 {
fmt.Fprintf(&cmd, " -%s", f.Name)
continue
}
}
fmt.Fprintf(&cmd, " -%s=%v", f.Name, getter.Get())
}
if cmd.Len() == 0 {
return
}
s := Ctxt.Lookup(dwarf.CUInfoPrefix + "producer." + myimportpath)
s.Type = objabi.SDWARFINFO
// Sometimes (for example when building tests) we can link
// together two package main archives. So allow dups.
s.Set(obj.AttrDuplicateOK, true)
Ctxt.Data = append(Ctxt.Data, s)
s.P = cmd.Bytes()[1:]
}
// recordPackageName records the name of the package being
// compiled, so that the linker can save it in the compile unit's DIE.
func recordPackageName() {
s := Ctxt.Lookup(dwarf.CUInfoPrefix + "packagename." + myimportpath)
s.Type = objabi.SDWARFINFO
// Sometimes (for example when building tests) we can link
// together two package main archives. So allow dups.
s.Set(obj.AttrDuplicateOK, true)
Ctxt.Data = append(Ctxt.Data, s)
s.P = []byte(localpkg.Name)
}
// flag_lang is the language version we are compiling for, set by the -lang flag.
var flag_lang string
// currentLang returns the current language version.
func currentLang() string {
return fmt.Sprintf("go1.%d", goversion.Version)
}
// goVersionRE is a regular expression that matches the valid
// arguments to the -lang flag.
var goVersionRE = regexp.MustCompile(`^go([1-9][0-9]*)\.(0|[1-9][0-9]*)$`)
// A lang is a language version broken into major and minor numbers.
type lang struct {
major, minor int
}
// langWant is the desired language version set by the -lang flag.
// If the -lang flag is not set, this is the zero value, meaning that
// any language version is supported.
var langWant lang
// langSupported reports whether language version major.minor is supported.
func langSupported(major, minor int) bool {
if langWant.major == 0 && langWant.minor == 0 {
return true
}
return langWant.major > major || (langWant.major == major && langWant.minor >= minor)
}
// checkLang verifies that the -lang flag holds a valid value, and
// exits if not. It initializes data used by langSupported.
func checkLang() {
if flag_lang == "" {
return
}
var err error
langWant, err = parseLang(flag_lang)
if err != nil {
log.Fatalf("invalid value %q for -lang: %v", flag_lang, err)
}
if def := currentLang(); flag_lang != def {
defVers, err := parseLang(def)
if err != nil {
log.Fatalf("internal error parsing default lang %q: %v", def, err)
}
if langWant.major > defVers.major || (langWant.major == defVers.major && langWant.minor > defVers.minor) {
log.Fatalf("invalid value %q for -lang: max known version is %q", flag_lang, def)
}
}
}
// parseLang parses a -lang option into a langVer.
func parseLang(s string) (lang, error) {
matches := goVersionRE.FindStringSubmatch(s)
if matches == nil {
return lang{}, fmt.Errorf(`should be something like "go1.12"`)
}
major, err := strconv.Atoi(matches[1])
if err != nil {
return lang{}, err
}
minor, err := strconv.Atoi(matches[2])
if err != nil {
return lang{}, err
}
return lang{major: major, minor: minor}, nil
}
|
[
"\"GOSSAFUNC\""
] |
[] |
[
"GOSSAFUNC"
] |
[]
|
["GOSSAFUNC"]
|
go
| 1 | 0 | |
src/workshop/core/scoring/batch_score.py
|
import os
import tempfile
import logging
from azureml.core.model import Model
import pickle
import pandas as pd
from azureml.core import Run
import os
import mlflow
def init():
global model
model_dir =os.getenv('AZUREML_MODEL_DIR')
model_file = os.listdir(model_dir)[0]
model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), model_file)
model = mlflow.sklearn.load_model(model_path)
def run(mini_batch):
print(f"run method start: {__file__}, run({mini_batch})")
resultList = []
# Set up logging
for batch in mini_batch:
# prepare each image
data = pd.read_json(batch)
predictions = model.predict(data)
data["prediction"] =predictions
resultList.append(data)
result = pd.concat(resultList)
return result
|
[] |
[] |
[
"AZUREML_MODEL_DIR"
] |
[]
|
["AZUREML_MODEL_DIR"]
|
python
| 1 | 0 | |
lib/constants.py
|
"""
This file contains constants used throughout AppScale.
"""
import os
# The current version of AppScale.
APPSCALE_VERSION = "1.13.0"
# AppScale home directory.
APPSCALE_HOME = os.environ.get("APPSCALE_HOME", "/root/appscale")
# Location of PID files for processes and applications.
APP_PID_DIR = '/etc/appscale/'
# Location of Java AppServer.
JAVA_APPSERVER = APPSCALE_HOME + '/AppServer_Java'
# The location of the file which specifies the current private IP.
PRIVATE_IP_LOC = '/etc/appscale/my_private_ip'
# The location of the file which specifies the current public IP.
PUBLIC_IP_LOC = '/etc/appscale/my_public_ip'
# The location of the file which holds the AppScale secret key.
SECRET_LOC = '/etc/appscale/secret.key'
# The location of the file which contains information on the current DB.
DB_INFO_LOC = '/etc/appscale/database_info.yaml'
# The file location which has all taskqueue nodes listed.
TASKQUEUE_NODE_FILE = "/etc/appscale/taskqueue_nodes"
# The port of the datastore server.
DB_SERVER_PORT = 8888
# The port of the UserAppServer SOAP server.
UA_SERVER_PORT = 4343
# The port of the application manager soap server.
APP_MANAGER_PORT = 49934
# Python programs.
PYTHON = "python"
# Python2.7 programs.
PYTHON27 = "python27"
# Java programs.
JAVA = "java"
# Go programs.
GO = "go"
# PHP programs.
PHP = "php"
# Location where applications are stored.
APPS_PATH = "/var/apps/"
# Locations of ZooKeeper in json format.
ZK_LOCATIONS_JSON_FILE = "/etc/appscale/zookeeper_locations.json"
# Default location for connecting to ZooKeeper.
ZK_DEFAULT_CONNECTION_STR = "localhost:2181"
# Default location for the datastore master.
MASTERS_FILE_LOC = "/etc/appscale/masters"
# Application ID for AppScale Dashboard.
DASHBOARD_APP_ID = "appscaledashboard"
# Application ID for AppScale API Checker.
API_CHECKER_ID = "apichecker"
# Reserved application identifiers which are only internal for AppScale.
RESERVED_APP_IDS = [DASHBOARD_APP_ID, API_CHECKER_ID]
|
[] |
[] |
[
"APPSCALE_HOME"
] |
[]
|
["APPSCALE_HOME"]
|
python
| 1 | 0 | |
misc/cgo/testcshared/cshared_test.go
|
// Copyright 2017 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 cshared_test
import (
"bytes"
"debug/elf"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"unicode"
)
// C compiler with args (from $(go env CC) $(go env GOGCCFLAGS)).
var cc []string
// ".exe" on Windows.
var exeSuffix string
var GOOS, GOARCH, GOROOT string
var installdir, androiddir string
var libSuffix, libgoname string
func TestMain(m *testing.M) {
os.Exit(testMain(m))
}
func testMain(m *testing.M) int {
log.SetFlags(log.Lshortfile)
flag.Parse()
if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
fmt.Printf("SKIP - short mode and $GO_BUILDER_NAME not set\n")
os.Exit(0)
}
GOOS = goEnv("GOOS")
GOARCH = goEnv("GOARCH")
GOROOT = goEnv("GOROOT")
if _, err := os.Stat(GOROOT); os.IsNotExist(err) {
log.Fatalf("Unable able to find GOROOT at '%s'", GOROOT)
}
androiddir = fmt.Sprintf("/data/local/tmp/testcshared-%d", os.Getpid())
if runtime.GOOS != GOOS && GOOS == "android" {
args := append(adbCmd(), "exec-out", "mkdir", "-p", androiddir)
cmd := exec.Command(args[0], args[1:]...)
out, err := cmd.CombinedOutput()
if err != nil {
log.Fatalf("setupAndroid failed: %v\n%s\n", err, out)
}
defer cleanupAndroid()
}
cc = []string{goEnv("CC")}
out := goEnv("GOGCCFLAGS")
quote := '\000'
start := 0
lastSpace := true
backslash := false
s := string(out)
for i, c := range s {
if quote == '\000' && unicode.IsSpace(c) {
if !lastSpace {
cc = append(cc, s[start:i])
lastSpace = true
}
} else {
if lastSpace {
start = i
lastSpace = false
}
if quote == '\000' && !backslash && (c == '"' || c == '\'') {
quote = c
backslash = false
} else if !backslash && quote == c {
quote = '\000'
} else if (quote == '\000' || quote == '"') && !backslash && c == '\\' {
backslash = true
} else {
backslash = false
}
}
}
if !lastSpace {
cc = append(cc, s[start:])
}
switch GOOS {
case "darwin", "ios":
// For Darwin/ARM.
// TODO(crawshaw): can we do better?
cc = append(cc, []string{"-framework", "CoreFoundation", "-framework", "Foundation"}...)
case "android":
cc = append(cc, "-pie")
}
libgodir := GOOS + "_" + GOARCH
switch GOOS {
case "darwin", "ios":
if GOARCH == "arm64" {
libgodir += "_shared"
}
case "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "solaris", "illumos":
libgodir += "_shared"
}
cc = append(cc, "-I", filepath.Join("pkg", libgodir))
if GOOS == "windows" {
exeSuffix = ".exe"
}
// Copy testdata into GOPATH/src/testcshared, along with a go.mod file
// declaring the same path.
GOPATH, err := ioutil.TempDir("", "cshared_test")
if err != nil {
log.Panic(err)
}
defer os.RemoveAll(GOPATH)
os.Setenv("GOPATH", GOPATH)
modRoot := filepath.Join(GOPATH, "src", "testcshared")
if err := overlayDir(modRoot, "testdata"); err != nil {
log.Panic(err)
}
if err := os.Chdir(modRoot); err != nil {
log.Panic(err)
}
os.Setenv("PWD", modRoot)
if err := ioutil.WriteFile("go.mod", []byte("module testcshared\n"), 0666); err != nil {
log.Panic(err)
}
// Directory where cgo headers and outputs will be installed.
// The installation directory format varies depending on the platform.
output, err := exec.Command("go", "list",
"-buildmode=c-shared",
"-installsuffix", "testcshared",
"-f", "{{.Target}}",
"./libgo").CombinedOutput()
if err != nil {
log.Panicf("go list failed: %v\n%s", err, output)
}
target := string(bytes.TrimSpace(output))
libgoname = filepath.Base(target)
installdir = filepath.Dir(target)
libSuffix = strings.TrimPrefix(filepath.Ext(target), ".")
return m.Run()
}
func goEnv(key string) string {
out, err := exec.Command("go", "env", key).Output()
if err != nil {
log.Printf("go env %s failed:\n%s", key, err)
log.Panicf("%s", err.(*exec.ExitError).Stderr)
}
return strings.TrimSpace(string(out))
}
func cmdToRun(name string) string {
return "./" + name + exeSuffix
}
func adbCmd() []string {
cmd := []string{"adb"}
if flags := os.Getenv("GOANDROID_ADB_FLAGS"); flags != "" {
cmd = append(cmd, strings.Split(flags, " ")...)
}
return cmd
}
func adbPush(t *testing.T, filename string) {
if runtime.GOOS == GOOS || GOOS != "android" {
return
}
args := append(adbCmd(), "push", filename, fmt.Sprintf("%s/%s", androiddir, filename))
cmd := exec.Command(args[0], args[1:]...)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("adb command failed: %v\n%s\n", err, out)
}
}
func adbRun(t *testing.T, env []string, adbargs ...string) string {
if GOOS != "android" {
t.Fatalf("trying to run adb command when operating system is not android.")
}
args := append(adbCmd(), "exec-out")
// Propagate LD_LIBRARY_PATH to the adb shell invocation.
for _, e := range env {
if strings.Index(e, "LD_LIBRARY_PATH=") != -1 {
adbargs = append([]string{e}, adbargs...)
break
}
}
shellcmd := fmt.Sprintf("cd %s; %s", androiddir, strings.Join(adbargs, " "))
args = append(args, shellcmd)
cmd := exec.Command(args[0], args[1:]...)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("adb command failed: %v\n%s\n", err, out)
}
return strings.Replace(string(out), "\r", "", -1)
}
func run(t *testing.T, extraEnv []string, args ...string) string {
t.Helper()
cmd := exec.Command(args[0], args[1:]...)
if len(extraEnv) > 0 {
cmd.Env = append(os.Environ(), extraEnv...)
}
if GOOS != "windows" {
// TestUnexportedSymbols relies on file descriptor 30
// being closed when the program starts, so enforce
// that in all cases. (The first three descriptors are
// stdin/stdout/stderr, so we just need to make sure
// that cmd.ExtraFiles[27] exists and is nil.)
cmd.ExtraFiles = make([]*os.File, 28)
}
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("command failed: %v\n%v\n%s\n", args, err, out)
} else {
t.Logf("run: %v", args)
}
return string(out)
}
func runExe(t *testing.T, extraEnv []string, args ...string) string {
t.Helper()
if runtime.GOOS != GOOS && GOOS == "android" {
return adbRun(t, append(os.Environ(), extraEnv...), args...)
}
return run(t, extraEnv, args...)
}
func runCC(t *testing.T, args ...string) string {
t.Helper()
// This function is run in parallel, so append to a copy of cc
// rather than cc itself.
return run(t, nil, append(append([]string(nil), cc...), args...)...)
}
func createHeaders() error {
// The 'cgo' command generates a number of additional artifacts,
// but we're only interested in the header.
// Shunt the rest of the outputs to a temporary directory.
objDir, err := ioutil.TempDir("", "testcshared_obj")
if err != nil {
return err
}
defer os.RemoveAll(objDir)
// Generate a C header file for p, which is a non-main dependency
// of main package libgo.
//
// TODO(golang.org/issue/35715): This should be simpler.
args := []string{"go", "tool", "cgo",
"-objdir", objDir,
"-exportheader", "p.h",
filepath.Join(".", "p", "p.go")}
cmd := exec.Command(args[0], args[1:]...)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("command failed: %v\n%v\n%s\n", args, err, out)
}
// Generate a C header file for libgo itself.
args = []string{"go", "install", "-buildmode=c-shared",
"-installsuffix", "testcshared", "./libgo"}
cmd = exec.Command(args[0], args[1:]...)
out, err = cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("command failed: %v\n%v\n%s\n", args, err, out)
}
args = []string{"go", "build", "-buildmode=c-shared",
"-installsuffix", "testcshared",
"-o", libgoname,
filepath.Join(".", "libgo", "libgo.go")}
cmd = exec.Command(args[0], args[1:]...)
out, err = cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("command failed: %v\n%v\n%s\n", args, err, out)
}
if runtime.GOOS != GOOS && GOOS == "android" {
args = append(adbCmd(), "push", libgoname, fmt.Sprintf("%s/%s", androiddir, libgoname))
cmd = exec.Command(args[0], args[1:]...)
out, err = cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("adb command failed: %v\n%s\n", err, out)
}
}
return nil
}
var (
headersOnce sync.Once
headersErr error
)
func createHeadersOnce(t *testing.T) {
headersOnce.Do(func() {
headersErr = createHeaders()
})
if headersErr != nil {
t.Fatal(headersErr)
}
}
func cleanupAndroid() {
if GOOS != "android" {
return
}
args := append(adbCmd(), "exec-out", "rm", "-rf", androiddir)
cmd := exec.Command(args[0], args[1:]...)
out, err := cmd.CombinedOutput()
if err != nil {
log.Panicf("cleanupAndroid failed: %v\n%s\n", err, out)
}
}
// test0: exported symbols in shared lib are accessible.
func TestExportedSymbols(t *testing.T) {
t.Parallel()
cmd := "testp0"
bin := cmdToRun(cmd)
createHeadersOnce(t)
runCC(t, "-I", installdir, "-o", cmd, "main0.c", libgoname)
adbPush(t, cmd)
defer os.Remove(bin)
out := runExe(t, []string{"LD_LIBRARY_PATH=."}, bin)
if strings.TrimSpace(out) != "PASS" {
t.Error(out)
}
}
// test1: shared library can be dynamically loaded and exported symbols are accessible.
func TestExportedSymbolsWithDynamicLoad(t *testing.T) {
t.Parallel()
if GOOS == "windows" {
t.Logf("Skipping on %s", GOOS)
return
}
cmd := "testp1"
bin := cmdToRun(cmd)
createHeadersOnce(t)
if GOOS != "freebsd" {
runCC(t, "-o", cmd, "main1.c", "-ldl")
} else {
runCC(t, "-o", cmd, "main1.c")
}
adbPush(t, cmd)
defer os.Remove(bin)
out := runExe(t, nil, bin, "./"+libgoname)
if strings.TrimSpace(out) != "PASS" {
t.Error(out)
}
}
// test2: tests libgo2 which does not export any functions.
func TestUnexportedSymbols(t *testing.T) {
t.Parallel()
if GOOS == "windows" {
t.Logf("Skipping on %s", GOOS)
return
}
cmd := "testp2"
bin := cmdToRun(cmd)
libname := "libgo2." + libSuffix
run(t,
nil,
"go", "build",
"-buildmode=c-shared",
"-installsuffix", "testcshared",
"-o", libname, "./libgo2",
)
adbPush(t, libname)
linkFlags := "-Wl,--no-as-needed"
if GOOS == "darwin" || GOOS == "ios" {
linkFlags = ""
}
runCC(t, "-o", cmd, "main2.c", linkFlags, libname)
adbPush(t, cmd)
defer os.Remove(libname)
defer os.Remove(bin)
out := runExe(t, []string{"LD_LIBRARY_PATH=."}, bin)
if strings.TrimSpace(out) != "PASS" {
t.Error(out)
}
}
// test3: tests main.main is exported on android.
func TestMainExportedOnAndroid(t *testing.T) {
t.Parallel()
switch GOOS {
case "android":
break
default:
t.Logf("Skipping on %s", GOOS)
return
}
cmd := "testp3"
bin := cmdToRun(cmd)
createHeadersOnce(t)
runCC(t, "-o", cmd, "main3.c", "-ldl")
adbPush(t, cmd)
defer os.Remove(bin)
out := runExe(t, nil, bin, "./"+libgoname)
if strings.TrimSpace(out) != "PASS" {
t.Error(out)
}
}
func testSignalHandlers(t *testing.T, pkgname, cfile, cmd string) {
libname := pkgname + "." + libSuffix
run(t,
nil,
"go", "build",
"-buildmode=c-shared",
"-installsuffix", "testcshared",
"-o", libname, pkgname,
)
adbPush(t, libname)
if GOOS != "freebsd" {
runCC(t, "-pthread", "-o", cmd, cfile, "-ldl")
} else {
runCC(t, "-pthread", "-o", cmd, cfile)
}
adbPush(t, cmd)
bin := cmdToRun(cmd)
defer os.Remove(libname)
defer os.Remove(bin)
defer os.Remove(pkgname + ".h")
out := runExe(t, nil, bin, "./"+libname)
if strings.TrimSpace(out) != "PASS" {
t.Error(run(t, nil, bin, libname, "verbose"))
}
}
// test4: test signal handlers
func TestSignalHandlers(t *testing.T) {
t.Parallel()
if GOOS == "windows" {
t.Logf("Skipping on %s", GOOS)
return
}
testSignalHandlers(t, "./libgo4", "main4.c", "testp4")
}
// test5: test signal handlers with os/signal.Notify
func TestSignalHandlersWithNotify(t *testing.T) {
t.Parallel()
if GOOS == "windows" {
t.Logf("Skipping on %s", GOOS)
return
}
testSignalHandlers(t, "./libgo5", "main5.c", "testp5")
}
func TestPIE(t *testing.T) {
t.Parallel()
switch GOOS {
case "linux", "android":
break
default:
t.Logf("Skipping on %s", GOOS)
return
}
createHeadersOnce(t)
f, err := elf.Open(libgoname)
if err != nil {
t.Fatalf("elf.Open failed: %v", err)
}
defer f.Close()
ds := f.SectionByType(elf.SHT_DYNAMIC)
if ds == nil {
t.Fatalf("no SHT_DYNAMIC section")
}
d, err := ds.Data()
if err != nil {
t.Fatalf("can't read SHT_DYNAMIC contents: %v", err)
}
for len(d) > 0 {
var tag elf.DynTag
switch f.Class {
case elf.ELFCLASS32:
tag = elf.DynTag(f.ByteOrder.Uint32(d[:4]))
d = d[8:]
case elf.ELFCLASS64:
tag = elf.DynTag(f.ByteOrder.Uint64(d[:8]))
d = d[16:]
}
if tag == elf.DT_TEXTREL {
t.Fatalf("%s has DT_TEXTREL flag", libgoname)
}
}
}
// Test that installing a second time recreates the header file.
func TestCachedInstall(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "cshared")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
copyFile(t, filepath.Join(tmpdir, "src", "testcshared", "go.mod"), "go.mod")
copyFile(t, filepath.Join(tmpdir, "src", "testcshared", "libgo", "libgo.go"), filepath.Join("libgo", "libgo.go"))
copyFile(t, filepath.Join(tmpdir, "src", "testcshared", "p", "p.go"), filepath.Join("p", "p.go"))
env := append(os.Environ(), "GOPATH="+tmpdir, "GOBIN="+filepath.Join(tmpdir, "bin"))
buildcmd := []string{"go", "install", "-x", "-buildmode=c-shared", "-installsuffix", "testcshared", "./libgo"}
cmd := exec.Command(buildcmd[0], buildcmd[1:]...)
cmd.Dir = filepath.Join(tmpdir, "src", "testcshared")
cmd.Env = env
t.Log(buildcmd)
out, err := cmd.CombinedOutput()
t.Logf("%s", out)
if err != nil {
t.Fatal(err)
}
var libgoh, ph string
walker := func(path string, info os.FileInfo, err error) error {
if err != nil {
t.Fatal(err)
}
var ps *string
switch filepath.Base(path) {
case "libgo.h":
ps = &libgoh
case "p.h":
ps = &ph
}
if ps != nil {
if *ps != "" {
t.Fatalf("%s found again", *ps)
}
*ps = path
}
return nil
}
if err := filepath.Walk(tmpdir, walker); err != nil {
t.Fatal(err)
}
if libgoh == "" {
t.Fatal("libgo.h not installed")
}
if err := os.Remove(libgoh); err != nil {
t.Fatal(err)
}
cmd = exec.Command(buildcmd[0], buildcmd[1:]...)
cmd.Dir = filepath.Join(tmpdir, "src", "testcshared")
cmd.Env = env
t.Log(buildcmd)
out, err = cmd.CombinedOutput()
t.Logf("%s", out)
if err != nil {
t.Fatal(err)
}
if _, err := os.Stat(libgoh); err != nil {
t.Errorf("libgo.h not installed in second run: %v", err)
}
}
// copyFile copies src to dst.
func copyFile(t *testing.T, dst, src string) {
t.Helper()
data, err := ioutil.ReadFile(src)
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(dst), 0777); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(dst, data, 0666); err != nil {
t.Fatal(err)
}
}
func TestGo2C2Go(t *testing.T) {
switch GOOS {
case "darwin", "ios":
// Darwin shared libraries don't support the multiple
// copies of the runtime package implied by this test.
t.Skip("linking c-shared into Go programs not supported on Darwin; issue 29061")
case "android":
t.Skip("test fails on android; issue 29087")
}
t.Parallel()
tmpdir, err := ioutil.TempDir("", "cshared-TestGo2C2Go")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpdir)
lib := filepath.Join(tmpdir, "libtestgo2c2go."+libSuffix)
run(t, nil, "go", "build", "-buildmode=c-shared", "-o", lib, "./go2c2go/go")
cgoCflags := os.Getenv("CGO_CFLAGS")
if cgoCflags != "" {
cgoCflags += " "
}
cgoCflags += "-I" + tmpdir
cgoLdflags := os.Getenv("CGO_LDFLAGS")
if cgoLdflags != "" {
cgoLdflags += " "
}
cgoLdflags += "-L" + tmpdir + " -ltestgo2c2go"
goenv := []string{"CGO_CFLAGS=" + cgoCflags, "CGO_LDFLAGS=" + cgoLdflags}
ldLibPath := os.Getenv("LD_LIBRARY_PATH")
if ldLibPath != "" {
ldLibPath += ":"
}
ldLibPath += tmpdir
runenv := []string{"LD_LIBRARY_PATH=" + ldLibPath}
bin := filepath.Join(tmpdir, "m1") + exeSuffix
run(t, goenv, "go", "build", "-o", bin, "./go2c2go/m1")
runExe(t, runenv, bin)
bin = filepath.Join(tmpdir, "m2") + exeSuffix
run(t, goenv, "go", "build", "-o", bin, "./go2c2go/m2")
runExe(t, runenv, bin)
}
|
[
"\"GO_BUILDER_NAME\"",
"\"GOANDROID_ADB_FLAGS\"",
"\"CGO_CFLAGS\"",
"\"CGO_LDFLAGS\"",
"\"LD_LIBRARY_PATH\""
] |
[] |
[
"GOANDROID_ADB_FLAGS",
"GO_BUILDER_NAME",
"CGO_LDFLAGS",
"LD_LIBRARY_PATH",
"CGO_CFLAGS"
] |
[]
|
["GOANDROID_ADB_FLAGS", "GO_BUILDER_NAME", "CGO_LDFLAGS", "LD_LIBRARY_PATH", "CGO_CFLAGS"]
|
go
| 5 | 0 | |
pkg/sql/opt/testutils/testcat/create_table.go
|
// Copyright 2018 The Cockroach 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 testcat
import (
"fmt"
"github.com/cockroachdb/cockroach/pkg/sql/coltypes"
"github.com/cockroachdb/cockroach/pkg/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/types"
"github.com/cockroachdb/cockroach/pkg/util"
)
type indexType int
const (
primaryIndex indexType = iota
uniqueIndex
nonUniqueIndex
)
// CreateTable creates a test table from a parsed DDL statement and adds it to
// the catalog. This is intended for testing, and is not a complete (and
// probably not fully correct) implementation. It just has to be "good enough".
func (tc *Catalog) CreateTable(stmt *tree.CreateTable) *Table {
tn, err := stmt.Table.Normalize()
if err != nil {
panic(fmt.Errorf("%s", err))
}
// Update the table name to include catalog and schema if not provided.
tc.qualifyTableName(tn)
tab := &Table{Name: *tn}
// Add the columns.
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.ColumnTableDef:
tab.addColumn(def)
}
}
// Add the primary index (if there is one defined).
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.ColumnTableDef:
if def.PrimaryKey {
// Add the primary index over the single column.
tab.addPrimaryColumnIndex(string(def.Name))
}
case *tree.UniqueConstraintTableDef:
if def.PrimaryKey {
tab.addIndex(&def.IndexTableDef, primaryIndex)
}
}
}
// If there is no primary index, add the hidden rowid column.
if len(tab.Indexes) == 0 {
rowid := &Column{Name: "rowid", Type: types.Int, Hidden: true}
tab.Columns = append(tab.Columns, rowid)
tab.addPrimaryColumnIndex(rowid.Name)
}
// Search for other relevant definitions.
for _, def := range stmt.Defs {
switch def := def.(type) {
case *tree.UniqueConstraintTableDef:
if !def.PrimaryKey {
tab.addIndex(&def.IndexTableDef, uniqueIndex)
}
case *tree.IndexTableDef:
tab.addIndex(def, nonUniqueIndex)
}
// TODO(rytaft): In the future we will likely want to check for unique
// constraints, indexes, and foreign key constraints to determine
// nullability, uniqueness, etc.
}
// Add the new table to the catalog.
tc.AddTable(tab)
return tab
}
// qualifyTableName updates the given table name to include catalog and schema
// if not already included.
func (tc *Catalog) qualifyTableName(name *tree.TableName) {
if name.ExplicitSchema {
if name.ExplicitCatalog {
// Already 3 parts: nothing to do.
return
}
if name.SchemaName == tree.PublicSchemaName {
// Use the current database.
name.CatalogName = testDB
return
}
// Compatibility with CockroachDB v1.1: use D.public.T.
name.CatalogName = name.SchemaName
name.SchemaName = tree.PublicSchemaName
name.ExplicitCatalog = true
return
}
// Use the current database.
name.CatalogName = testDB
name.SchemaName = tree.PublicSchemaName
}
func (tt *Table) addColumn(def *tree.ColumnTableDef) {
nullable := !def.PrimaryKey && def.Nullable.Nullability != tree.NotNull
typ := coltypes.CastTargetToDatumType(def.Type)
col := &Column{Name: string(def.Name), Type: typ, Nullable: nullable}
tt.Columns = append(tt.Columns, col)
}
func (tt *Table) addIndex(def *tree.IndexTableDef, typ indexType) {
idx := &Index{Name: tt.makeIndexName(def.Name, typ)}
// Add explicit columns and mark key columns as not null.
for _, colDef := range def.Columns {
col := idx.addColumn(tt, string(colDef.Column), colDef.Direction, true /* makeUnique */)
if typ == primaryIndex {
col.Nullable = false
}
}
if typ == primaryIndex {
var pkOrdinals util.FastIntSet
for _, c := range idx.Columns {
pkOrdinals.Add(c.Ordinal)
}
// Add the rest of the columns in the table.
for i := range tt.Columns {
if !pkOrdinals.Contains(i) {
idx.addColumnByOrdinal(tt, i, tree.Ascending, false /* makeUnique */)
}
}
if len(tt.Indexes) != 0 {
panic("primary index should always be 0th index")
}
tt.Indexes = append(tt.Indexes, idx)
return
}
// Add implicit key columns from primary index.
pkCols := tt.Indexes[opt.PrimaryIndex].Columns[:tt.Indexes[opt.PrimaryIndex].Unique]
for _, pkCol := range pkCols {
// Only add columns that aren't already part of index.
found := false
for _, colDef := range def.Columns {
if pkCol.Column.ColName() == opt.ColumnName(colDef.Column) {
found = true
}
}
if !found {
// Implicit column is only part of the index's set of unique columns
// if the index *was not* declared as unique in the first place. The
// implicit columns are added to make the index unique (as well as
// to "cover" the primary index for lookups).
name := string(pkCol.Column.ColName())
makeUnique := typ != uniqueIndex
idx.addColumn(tt, name, tree.Ascending, makeUnique)
}
}
// Add storing columns.
for _, name := range def.Storing {
// Only add storing columns that weren't added as part of adding implicit
// key columns.
found := false
for _, pkCol := range pkCols {
if opt.ColumnName(name) == pkCol.Column.ColName() {
found = true
}
}
if !found {
idx.addColumn(tt, string(name), tree.Ascending, false /* makeUnique */)
}
}
tt.Indexes = append(tt.Indexes, idx)
}
func (tt *Table) makeIndexName(defName tree.Name, typ indexType) string {
name := string(defName)
if name == "" {
if typ == primaryIndex {
name = "primary"
} else {
name = "secondary"
}
}
return name
}
func (ti *Index) addColumn(
tt *Table, name string, direction tree.Direction, makeUnique bool,
) *Column {
return ti.addColumnByOrdinal(tt, tt.FindOrdinal(name), direction, makeUnique)
}
func (ti *Index) addColumnByOrdinal(
tt *Table, ord int, direction tree.Direction, makeUnique bool,
) *Column {
col := tt.Column(ord)
idxCol := opt.IndexColumn{
Column: col,
Ordinal: ord,
Descending: direction == tree.Descending,
}
ti.Columns = append(ti.Columns, idxCol)
if makeUnique {
// Need to add to the index's count of columns that are part of its
// unique key.
ti.Unique++
}
return col.(*Column)
}
func (tt *Table) addPrimaryColumnIndex(colName string) {
def := tree.IndexTableDef{
Columns: tree.IndexElemList{{Column: tree.Name(colName), Direction: tree.Ascending}},
}
tt.addIndex(&def, primaryIndex)
}
|
[] |
[] |
[] |
[]
|
[]
|
go
| null | null | null |
app02/config.py
|
import os
_basedir = os.path.abspath(os.path.dirname(__file__))
DEBUG = False
ENV = "production"
if "LOGLEVEL" in os.environ and os.environ.get("LOGLEVEL").upper() == "DEBUG":
DEBUG = True
if DEBUG:
ENV = "development"
|
[] |
[] |
[
"LOGLEVEL"
] |
[]
|
["LOGLEVEL"]
|
python
| 1 | 0 | |
cmd/common/url.go
|
package common
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
// GetGrafanaAPIURL returns the Grafan API URL defined by grafana-api-url
// commandline flag or by the GRAFANA_API_URL environment variable.
func GetGrafanaAPIURL(cmd *cobra.Command) (string, error) {
apiURL, err := cmd.Flags().GetString("grafana-api-url")
if err != nil {
return "", fmt.Errorf("failed to get grafana-api-url: %s", err)
}
if apiURL != "" {
return apiURL, nil
}
envURL := os.Getenv("GRAFANA_API_URL")
if envURL != "" {
return envURL, nil
}
return "", nil
}
|
[
"\"GRAFANA_API_URL\""
] |
[] |
[
"GRAFANA_API_URL"
] |
[]
|
["GRAFANA_API_URL"]
|
go
| 1 | 0 | |
Godeps/_workspace/src/github.com/jpillora/go-realtime/example/server.go
|
package main
import (
"log"
"net/http"
"os"
"time"
"github.com/jpillora/go-realtime"
)
type Foo struct {
realtime.Object //adds sync state and an Update() method
A, B int
C []int
D string
E Bar
}
type Bar struct {
X, Y int
}
func main() {
foo := &Foo{A: 21, B: 42, D: "0"}
//create a go-realtime (websockets) http.Handler
rt := realtime.NewHandler()
//register foo
rt.Add("foo", foo)
go func() {
i := 0
for {
//change foo
foo.A++
if i%2 == 0 {
foo.B--
}
i++
if i > 10 {
foo.C = foo.C[1:]
}
foo.C = append(foo.C, i)
if i%5 == 0 {
foo.E.Y++
}
//mark updated
foo.Update()
//do other stuff...
time.Sleep(250 * time.Millisecond)
}
}()
//realtime handlers
http.Handle("/realtime", rt)
//index handler
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write(indexhtml)
})
port := os.Getenv("PORT")
if port == "" {
port = "4000"
}
log.Printf("Listening on localhost:%s...", port)
http.ListenAndServe(":"+port, nil)
}
var indexhtml = []byte(`
<pre id="out"></pre>
<script src="/realtime"></script>
<script>
var foo = {};
var rt = realtime("/realtime");
//keep in sync with the server
rt.add("foo", foo, function onupdate() {
out.innerHTML = JSON.stringify(foo, null, 2);
});
</script>
`)
//NOTE: deltas are not sent in the example since the target object is too small
|
[
"\"PORT\""
] |
[] |
[
"PORT"
] |
[]
|
["PORT"]
|
go
| 1 | 0 | |
osxphotos/exiftool.py
|
""" Yet another simple exiftool wrapper
I rolled my own for following reasons:
1. I wanted something under MIT license (best alternative was licensed under GPL/BSD)
2. I wanted singleton behavior so only a single exiftool process was ever running
3. When used as a context manager, I wanted the operations to batch until exiting the context (improved performance)
If these aren't important to you, I highly recommend you use Sven Marnach's excellent
pyexiftool: https://github.com/smarnach/pyexiftool which provides more functionality """
import atexit
import html
import json
import logging
import os
import pathlib
import re
import shutil
import subprocess
from abc import ABC, abstractmethod
from functools import lru_cache # pylint: disable=syntax-error
__all__ = [
"escape_str",
"exiftool_can_write",
"ExifTool",
"ExifToolCaching",
"get_exiftool_path",
"terminate_exiftool",
"unescape_str",
]
# exiftool -stay_open commands outputs this EOF marker after command is run
EXIFTOOL_STAYOPEN_EOF = "{ready}"
EXIFTOOL_STAYOPEN_EOF_LEN = len(EXIFTOOL_STAYOPEN_EOF)
# list of exiftool processes to cleanup when exiting or when terminate is called
EXIFTOOL_PROCESSES = []
# exiftool supported file types, created by utils/exiftool_supported_types.py
EXIFTOOL_FILETYPES_JSON = "exiftool_filetypes.json"
with (pathlib.Path(__file__).parent / EXIFTOOL_FILETYPES_JSON).open("r") as f:
EXIFTOOL_SUPPORTED_FILETYPES = json.load(f)
def exiftool_can_write(suffix: str) -> bool:
"""Return True if exiftool supports writing to a file with the given suffix, otherwise False"""
if not suffix:
return False
suffix = suffix.lower()
if suffix[0] == ".":
suffix = suffix[1:]
return (
suffix in EXIFTOOL_SUPPORTED_FILETYPES
and EXIFTOOL_SUPPORTED_FILETYPES[suffix]["write"]
)
def escape_str(s):
"""escape string for use with exiftool -E"""
if type(s) != str:
return s
s = html.escape(s)
s = s.replace("\n", "
")
s = s.replace("\t", "	")
s = s.replace("\r", "
")
return s
def unescape_str(s):
"""unescape an HTML string returned by exiftool -E"""
if type(s) != str:
return s
# avoid " in values which result in json.loads() throwing an exception, #636
s = s.replace(""", '\\"')
return html.unescape(s)
@atexit.register
def terminate_exiftool():
"""Terminate any running ExifTool subprocesses; call this to cleanup when done using ExifTool"""
for proc in EXIFTOOL_PROCESSES:
proc._stop_proc()
@lru_cache(maxsize=1)
def get_exiftool_path():
"""return path of exiftool, cache result"""
if exiftool_path := shutil.which("exiftool"):
return exiftool_path.rstrip()
else:
raise FileNotFoundError(
"Could not find exiftool. Please download and install from "
"https://exiftool.org/"
)
class _ExifToolProc:
"""Runs exiftool in a subprocess via Popen
Creates a singleton object"""
def __new__(cls, *args, **kwargs):
"""create new object or return instance of already created singleton"""
if not hasattr(cls, "instance") or not cls.instance:
cls.instance = super().__new__(cls)
return cls.instance
def __init__(self, exiftool=None):
"""construct _ExifToolProc singleton object or return instance of already created object
exiftool: optional path to exiftool binary (if not provided, will search path to find it)
"""
if hasattr(self, "_process_running") and self._process_running:
# already running
if exiftool is not None and exiftool != self._exiftool:
logging.warning(
f"exiftool subprocess already running, "
f"ignoring exiftool={exiftool}"
)
return
self._process_running = False
self._exiftool = exiftool or get_exiftool_path()
self._start_proc()
@property
def process(self):
"""return the exiftool subprocess"""
if self._process_running:
return self._process
else:
self._start_proc()
return self._process
@property
def pid(self):
"""return process id (PID) of the exiftool process"""
return self._process.pid
@property
def exiftool(self):
"""return path to exiftool process"""
return self._exiftool
def _start_proc(self):
"""start exiftool in batch mode"""
if self._process_running:
logging.warning("exiftool already running: {self._process}")
return
# open exiftool process
# make sure /usr/bin at start of path so exiftool can find xattr (see #636)
env = os.environ.copy()
env["PATH"] = f'/usr/bin/:{env["PATH"]}'
self._process = subprocess.Popen(
[
self._exiftool,
"-stay_open", # keep process open in batch mode
"True", # -stay_open=True, keep process open in batch mode
"-@", # read command-line arguments from file
"-", # read from stdin
"-common_args", # specifies args common to all commands subsequently run
"-n", # no print conversion (e.g. print tag values in machine readable format)
"-P", # Preserve file modification date/time
"-G", # print group name for each tag
"-E", # escape tag values for HTML (allows use of HTML 
 for newlines)
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env,
)
self._process_running = True
EXIFTOOL_PROCESSES.append(self)
def _stop_proc(self):
"""stop the exiftool process if it's running, otherwise, do nothing"""
if not self._process_running:
return
try:
self._process.stdin.write(b"-stay_open\n")
self._process.stdin.write(b"False\n")
self._process.stdin.flush()
except Exception as e:
pass
try:
self._process.communicate(timeout=5)
except subprocess.TimeoutExpired:
self._process.kill()
self._process.communicate()
del self._process
self._process_running = False
class ExifTool:
"""Basic exiftool interface for reading and writing EXIF tags"""
def __init__(self, filepath, exiftool=None, overwrite=True, flags=None):
"""Create ExifTool object
Args:
file: path to image file
exiftool: path to exiftool, if not specified will look in path
overwrite: if True, will overwrite image file without creating backup, default=False
flags: optional list of exiftool flags to prepend to exiftool command when writing metadata (e.g. -m or -F)
Returns:
ExifTool instance
"""
self.file = filepath
self.overwrite = overwrite
self.flags = flags or []
self.data = {}
self.warning = None
self.error = None
# if running as a context manager, self._context_mgr will be True
self._context_mgr = False
self._exiftoolproc = _ExifToolProc(exiftool=exiftool)
self._read_exif()
@property
def _process(self):
return self._exiftoolproc.process
def setvalue(self, tag, value):
"""Set tag to value(s); if value is None, will delete tag
Args:
tag: str; name of tag to set
value: str; value to set tag to
Returns:
True if success otherwise False
If error generated by exiftool, returns False and sets self.error to error string
If warning generated by exiftool, returns True (unless there was also an error) and sets self.warning to warning string
If called in context manager, returns True (execution is delayed until exiting context manager)
"""
if value is None:
value = ""
value = escape_str(value)
command = [f"-{tag}={value}"]
if self.overwrite and not self._context_mgr:
command.append("-overwrite_original")
# avoid "Warning: Some character(s) could not be encoded in Latin" warning
command.append("-iptc:codedcharacterset=utf8")
if self._context_mgr:
self._commands.extend(command)
return True
else:
_, _, error = self.run_commands(*command)
return error == ""
def addvalues(self, tag, *values):
"""Add one or more value(s) to tag
If more than one value is passed, each value will be added to the tag
Args:
tag: str; tag to set
*values: str; one or more values to set
Returns:
True if success otherwise False
If error generated by exiftool, returns False and sets self.error to error string
If warning generated by exiftool, returns True (unless there was also an error) and sets self.warning to warning string
If called in context manager, returns True (execution is delayed until exiting context manager)
Notes: exiftool may add duplicate values for some tags so the caller must ensure
the values being added are not already in the EXIF data
For some tags, such as IPTC:Keywords, this will add a new value to the list of keywords,
but for others, such as EXIF:ISO, this will literally add a value to the existing value.
It's up to the caller to know what exiftool will do for each tag
If setvalue called before addvalues, exiftool does not appear to add duplicates,
but if addvalues called without first calling setvalue, exiftool will add duplicate values
"""
if not values:
raise ValueError("Must pass at least one value")
command = []
for value in values:
if value is None:
raise ValueError("Can't add None value to tag")
value = escape_str(value)
command.append(f"-{tag}+={value}")
if self.overwrite and not self._context_mgr:
command.append("-overwrite_original")
if self._context_mgr:
self._commands.extend(command)
return True
else:
_, _, error = self.run_commands(*command)
return error == ""
def run_commands(self, *commands, no_file=False):
"""Run commands in the exiftool process and return result.
Args:
*commands: exiftool commands to run
no_file: (bool) do not pass the filename to exiftool (default=False)
by default, all commands will be run against self.file
use no_file=True to run a command without passing the filename
Returns:
(output, warning, errror)
output: bytes is containing output of exiftool commands
warning: if exiftool generated warnings, string containing warning otherwise empty string
error: if exiftool generated errors, string containing otherwise empty string
Note: Also sets self.warning and self.error if warning or error generated.
"""
if not (hasattr(self, "_process") and self._process):
raise ValueError("exiftool process is not running")
if not commands:
raise TypeError("must provide one or more command to run")
if self._context_mgr and self.overwrite:
commands = list(commands)
commands.append("-overwrite_original")
filename = os.fsencode(self.file) if not no_file else b""
if self.flags:
# need to split flags, e.g. so "--ext AVI" becomes ["--ext", "AVI"]
flags = []
for f in self.flags:
flags.extend(f.split())
command_str = b"\n".join([f.encode("utf-8") for f in flags])
command_str += b"\n"
else:
command_str = b""
command_str += (
b"\n".join([c.encode("utf-8") for c in commands])
+ b"\n"
+ filename
+ b"\n"
+ b"-execute\n"
)
# send the command
self._process.stdin.write(command_str)
self._process.stdin.flush()
# read the output
output = b""
warning = b""
error = b""
while EXIFTOOL_STAYOPEN_EOF not in str(output):
line = self._process.stdout.readline()
if line.startswith(b"Warning"):
warning += line.strip()
elif line.startswith(b"Error"):
error += line.strip()
else:
output += line.strip()
warning = "" if warning == b"" else warning.decode("utf-8")
error = "" if error == b"" else error.decode("utf-8")
self.warning = warning
self.error = error
return output[:-EXIFTOOL_STAYOPEN_EOF_LEN], warning, error
@property
def pid(self):
"""return process id (PID) of the exiftool process"""
return self._process.pid
@property
def version(self):
"""returns exiftool version"""
ver, _, _ = self.run_commands("-ver", no_file=True)
return ver.decode("utf-8")
def asdict(self, tag_groups=True, normalized=False):
"""return dictionary of all EXIF tags and values from exiftool
returns empty dict if no tags
Args:
tag_groups: if True (default), dict keys have tag groups, e.g. "IPTC:Keywords"; if False, drops groups from keys, e.g. "Keywords"
normalized: if True, dict keys are all normalized to lower case (default is False)
"""
json_str, _, _ = self.run_commands("-json")
if not json_str:
return dict()
json_str = unescape_str(json_str.decode("utf-8"))
try:
exifdict = json.loads(json_str)
except Exception as e:
# will fail with some commands, e.g --ext AVI which produces
# 'No file with specified extension' instead of json
logging.warning(f"error loading json returned by exiftool: {e} {json_str}")
return dict()
exifdict = exifdict[0]
if not tag_groups:
# strip tag groups
exif_new = {}
for k, v in exifdict.items():
k = re.sub(r".*:", "", k)
exif_new[k] = v
exifdict = exif_new
if normalized:
exifdict = {k.lower(): v for (k, v) in exifdict.items()}
return exifdict
def json(self):
"""returns JSON string containing all EXIF tags and values from exiftool"""
json, _, _ = self.run_commands("-json")
json = unescape_str(json.decode("utf-8"))
return json
def _read_exif(self):
"""read exif data from file"""
data = self.asdict()
self.data = {k: v for k, v in data.items()}
def __str__(self):
return f"file: {self.file}\nexiftool: {self._exiftoolproc._exiftool}"
def __enter__(self):
self._context_mgr = True
self._commands = []
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
return False
elif self._commands:
# run_commands sets self.warning and self.error as needed
self.run_commands(*self._commands)
class ExifToolCaching(ExifTool):
"""Basic exiftool interface for reading and writing EXIF tags, with caching.
Use this only when you know the file's EXIF data will not be changed by any external process.
Creates a singleton cached ExifTool instance"""
_singletons = {}
def __new__(cls, filepath, exiftool=None):
"""create new object or return instance of already created singleton"""
if filepath not in cls._singletons:
cls._singletons[filepath] = _ExifToolCaching(filepath, exiftool=exiftool)
return cls._singletons[filepath]
class _ExifToolCaching(ExifTool):
def __init__(self, filepath, exiftool=None):
"""Create read-only ExifTool object that caches values
Args:
file: path to image file
exiftool: path to exiftool, if not specified will look in path
Returns:
ExifTool instance
"""
self._json_cache = None
self._asdict_cache = {}
super().__init__(filepath, exiftool=exiftool, overwrite=False, flags=None)
def run_commands(self, *commands, no_file=False):
if commands[0] not in ["-json", "-ver"]:
raise NotImplementedError(f"{self.__class__} is read-only")
return super().run_commands(*commands, no_file=no_file)
def setvalue(self, tag, value):
raise NotImplementedError(f"{self.__class__} is read-only")
def addvalues(self, tag, *values):
raise NotImplementedError(f"{self.__class__} is read-only")
def json(self):
if not self._json_cache:
self._json_cache = super().json()
return self._json_cache
def asdict(self, tag_groups=True, normalized=False):
"""return dictionary of all EXIF tags and values from exiftool
returns empty dict if no tags
Args:
tag_groups: if True (default), dict keys have tag groups, e.g. "IPTC:Keywords"; if False, drops groups from keys, e.g. "Keywords"
normalized: if True, dict keys are all normalized to lower case (default is False)
"""
try:
return self._asdict_cache[tag_groups][normalized]
except KeyError:
if tag_groups not in self._asdict_cache:
self._asdict_cache[tag_groups] = {}
self._asdict_cache[tag_groups][normalized] = super().asdict(
tag_groups=tag_groups, normalized=normalized
)
return self._asdict_cache[tag_groups][normalized]
def flush_cache(self):
"""Clear cached data so that calls to json or asdict return fresh data"""
self._json_cache = None
self._asdict_cache = {}
|
[] |
[] |
[] |
[]
|
[]
|
python
| 0 | 0 | |
mxnet/mxnet-engine/src/main/java/ai/djl/mxnet/jna/LibUtils.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl.mxnet.jna;
import ai.djl.util.Platform;
import ai.djl.util.Utils;
import com.sun.jna.Library;
import com.sun.jna.Native;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utilities for finding the MXNet Engine binary on the System.
*
* <p>The Engine will be searched for in a variety of locations in the following order:
*
* <ol>
* <li>In the path specified by the MXNET_LIBRARY_PATH environment variable
* <li>In a jar file location in the classpath. These jars can be created with the mxnet-native
* module.
* <li>In the python3 path. These can be installed using pip.
* <li>In the python path. These can be installed using pip.
* </ol>
*/
@SuppressWarnings("MissingJavadocMethod")
public final class LibUtils {
private static final Logger logger = LoggerFactory.getLogger(LibUtils.class);
private static final String LIB_NAME = "mxnet";
private static final Pattern VERSION_PATTERN =
Pattern.compile("(\\d+\\.\\d+\\.\\d+(-[a-z]+)?)(-SNAPSHOT)?(-\\d+)?");
private LibUtils() {}
public static MxnetLibrary loadLibrary() {
String libName = getLibName();
logger.debug("Loading mxnet library from: {}", libName);
if (System.getProperty("os.name").startsWith("Linux")) {
Map<String, Integer> options = new ConcurrentHashMap<>();
int rtld = 1; // Linux RTLD lazy + local
options.put(Library.OPTION_OPEN_FLAGS, rtld);
return Native.load(libName, MxnetLibrary.class, options);
}
return Native.load(libName, MxnetLibrary.class);
}
public static String getLibName() {
String libName = LibUtils.findOverrideLibrary();
if (libName == null) {
libName = LibUtils.findLibraryInClasspath();
if (libName == null) {
libName = LIB_NAME;
}
}
return libName;
}
private static String findOverrideLibrary() {
String libPath = System.getenv("MXNET_LIBRARY_PATH");
if (libPath != null) {
String libName = findLibraryInPath(libPath);
if (libName != null) {
return libName;
}
}
libPath = System.getProperty("java.library.path");
if (libPath != null) {
return findLibraryInPath(libPath);
}
return null;
}
private static synchronized String findLibraryInClasspath() {
Enumeration<URL> urls;
try {
urls =
Thread.currentThread()
.getContextClassLoader()
.getResources("native/lib/mxnet.properties");
} catch (IOException e) {
logger.warn("", e);
return null;
}
// No native jars
if (!urls.hasMoreElements()) {
logger.debug("mxnet.properties not found in class path.");
return null;
}
Platform systemPlatform = Platform.fromSystem();
try {
Platform matching = null;
Platform placeholder = null;
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
Platform platform = Platform.fromUrl(url);
if (platform.isPlaceholder()) {
placeholder = platform;
} else if (platform.matches(systemPlatform)) {
matching = platform;
break;
}
}
if (matching != null) {
return loadLibraryFromClasspath(matching);
}
if (placeholder != null) {
try {
return downloadMxnet(placeholder);
} catch (IOException e) {
throw new IllegalStateException("Failed to download MXNet native library", e);
}
}
} catch (IOException e) {
throw new IllegalStateException(
"Failed to read MXNet native library jar properties", e);
}
throw new IllegalStateException(
"Your MXNet native library jar does not match your operating system. Make sure that the Maven Dependency Classifier matches your system type.");
}
private static String loadLibraryFromClasspath(Platform platform) {
Path tmp = null;
try {
String libName = System.mapLibraryName(LIB_NAME);
Path cacheFolder = Utils.getEngineCacheDir("mxnet");
logger.debug("Using cache dir: {}", cacheFolder);
Path dir = cacheFolder.resolve(platform.getVersion() + platform.getClassifier());
Path path = dir.resolve(libName);
if (Files.exists(path)) {
return path.toAbsolutePath().toString();
}
Files.createDirectories(cacheFolder);
tmp = Files.createTempDirectory(cacheFolder, "tmp");
for (String file : platform.getLibraries()) {
String libPath = "/native/lib/" + file;
try (InputStream is = LibUtils.class.getResourceAsStream(libPath)) {
logger.info("Extracting {} to cache ...", file);
Files.copy(is, tmp.resolve(file), StandardCopyOption.REPLACE_EXISTING);
}
}
Utils.moveQuietly(tmp, dir);
return path.toAbsolutePath().toString();
} catch (IOException e) {
throw new IllegalStateException("Failed to extract MXNet native library", e);
} finally {
if (tmp != null) {
Utils.deleteQuietly(tmp);
}
}
}
private static String findLibraryInPath(String libPath) {
String[] paths = libPath.split(File.pathSeparator);
List<String> mappedLibNames;
if (com.sun.jna.Platform.isMac()) {
mappedLibNames = Arrays.asList("libmxnet.dylib", "libmxnet.jnilib", "libmxnet.so");
} else {
mappedLibNames = Collections.singletonList(System.mapLibraryName(LIB_NAME));
}
for (String path : paths) {
File p = new File(path);
if (!p.exists()) {
continue;
}
for (String name : mappedLibNames) {
if (p.isFile() && p.getName().endsWith(name)) {
return p.getAbsolutePath();
}
File file = new File(path, name);
if (file.exists() && file.isFile()) {
return file.getAbsolutePath();
}
}
}
return null;
}
private static String downloadMxnet(Platform platform) throws IOException {
String version = platform.getVersion();
String flavor = platform.getFlavor();
if (flavor.isEmpty()) {
flavor = "mkl";
} else if (!flavor.endsWith("mkl")) {
flavor += "mkl"; // NOPMD
}
String classifier = platform.getClassifier();
String cudaArch = platform.getCudaArch();
String os = platform.getOsPrefix();
String libName = System.mapLibraryName(LIB_NAME);
Path cacheFolder = Utils.getEngineCacheDir("mxnet");
logger.debug("Using cache dir: {}", cacheFolder);
Path dir = cacheFolder.resolve(version + '-' + flavor + '-' + classifier);
Path path = dir.resolve(libName);
if (Files.exists(path)) {
return path.toAbsolutePath().toString();
}
Files.createDirectories(cacheFolder);
Matcher matcher = VERSION_PATTERN.matcher(version);
if (!matcher.matches()) {
throw new IllegalArgumentException("Unexpected version: " + version);
}
Path tmp = Files.createTempDirectory(cacheFolder, "tmp");
String link = "https://publish.djl.ai/mxnet-" + matcher.group(1);
try (InputStream is = new URL(link + "/files.txt").openStream()) {
List<String> lines = Utils.readLines(is);
if (cudaArch != null) {
// has CUDA
if ("win".equals(os)) {
if (!lines.contains(os + '/' + flavor + "/mxnet_" + cudaArch + ".dll.gz")) {
logger.warn(
"No matching cuda flavor for {} found: {}/sm_{}.",
os,
flavor,
cudaArch);
// fallback to CPU
flavor = "mkl";
}
} else if ("linux".equals(os)) {
if (!lines.contains(os + '/' + flavor + "/libmxnet.so.gz")
|| notSupported(platform)) {
logger.warn(
"No matching cuda flavor for {} found: {}/sm_{}.",
os,
flavor,
cudaArch);
// fallback to CPU
flavor = "mkl";
}
} else {
throw new AssertionError("Unsupported GPU operating system: " + os);
}
// check again in case fallback to cpu
if ("mkl".equals(flavor)) {
dir = cacheFolder.resolve(version + '-' + flavor + '-' + classifier);
path = dir.resolve(libName);
if (Files.exists(path)) {
return path.toAbsolutePath().toString();
}
}
}
for (String line : lines) {
if (line.startsWith(os + "/common/") || line.startsWith(os + '/' + flavor + '/')) {
URL url = new URL(link + '/' + line);
String fileName = line.substring(line.lastIndexOf('/') + 1, line.length() - 3);
if ("win".equals(os)) {
if ("libmxnet.dll".equals(fileName)) {
fileName = "mxnet.dll";
} else if (fileName.startsWith("mxnet_")) {
if (!("mxnet_" + cudaArch + ".dll").equals(fileName)) {
continue;
}
fileName = "mxnet.dll"; // split CUDA build
}
}
logger.info("Downloading {} ...", fileName);
try (InputStream fis = new GZIPInputStream(url.openStream())) {
Files.copy(fis, tmp.resolve(fileName), StandardCopyOption.REPLACE_EXISTING);
}
}
}
Utils.moveQuietly(tmp, dir);
return path.toAbsolutePath().toString();
} finally {
Utils.deleteQuietly(tmp);
}
}
private static boolean notSupported(Platform platform) {
// mxnet-native-cu102mkl:1.8.0: 3.0, 5.0, 6.0, 7.0, 7.5
// mxnet-native-cu110mkl:1.8.0: 5.0, 6.0, 7.0, 8.0
if (platform.getVersion().startsWith("1.8.")) {
String flavor = platform.getFlavor();
String cudaArch = platform.getCudaArch();
if ("cu110".equals(flavor)) {
return !Arrays.asList("50", "60", "70", "80").contains(cudaArch);
} else if ("cu102".equals(flavor)) {
return !Arrays.asList("30", "50", "60", "70", "75").contains(cudaArch);
}
}
return false;
}
}
|
[
"\"MXNET_LIBRARY_PATH\""
] |
[] |
[
"MXNET_LIBRARY_PATH"
] |
[]
|
["MXNET_LIBRARY_PATH"]
|
java
| 1 | 0 | |
tests/conftest.py
|
import fnmatch
from functools import partial
import os
import shutil
import tarfile
from tempfile import mkdtemp
try:
from os import walk
except ImportError:
from scandir import walk
if os.environ.get('TRAVIS'):
# use agg backend on TRAVIS for testing so DISPLAY isn't required
import matplotlib as mpl
mpl.use('agg')
import numpy as np # noqa
import pandas as pd # noqa
import pytest # noqa
import yaml # noqa
here = os.path.dirname(__file__)
example_cachedir = os.path.join(here, 'data', 'cache')
example_cachefile = os.path.join(example_cachedir, 'yatsm_r0_n447_b8.npy.npz')
example_training = os.path.join(here, 'data', 'results',
'training_image_1995-06-01.gtif')
yaml_config = os.path.join(here, 'data', 'p035r032_config.yaml')
example_classify_config = 'RandomForest.yaml'
example_classify_pickle = 'train_rf.pkl'
# EXAMPLE DATASETS
@pytest.fixture(scope='session')
def example_timeseries(request):
""" Extract example timeseries returning a dictionary of dataset attributes
"""
path = mkdtemp('_yatsm')
tgz = os.path.join(here, 'data', 'p035r032_testdata.tar.gz')
with tarfile.open(tgz) as tgz:
tgz.extractall(path)
request.addfinalizer(partial(shutil.rmtree, path))
# Find data
subset_path = os.path.join(path, 'p035r032', 'images')
stack_images, stack_image_IDs = [], []
for root, dnames, fnames in walk(subset_path):
for fname in fnmatch.filter(fnames, 'L*stack.gtif'):
stack_images.append(os.path.join(root, fname))
stack_image_IDs.append(os.path.basename(root))
stack_images = np.asarray(stack_images)
stack_image_IDs = np.asarray(stack_image_IDs)
# Formulate "images.csv" input_file
input_file = os.path.join(path, 'images.csv')
dates = np.array([_d[9:16]for _d in stack_image_IDs]) # YYYYDOY
sensors = np.array([_id[0:3] for _id in stack_image_IDs]) # Landsat IDs
df = pd.DataFrame({
'date': dates,
'sensor': sensors,
'filename': stack_images
})
# Sort by date
pd_ver = pd.__version__.split('.')
if pd_ver[0] == '0' and int(pd_ver[1]) < 17:
df = df.sort(columns='date')
else:
df = df.sort_values(by='date')
df.to_csv(input_file, index=False)
# Copy configuration file
dest_config = os.path.join(path, os.path.basename(yaml_config))
config = yaml.load(open(yaml_config))
config['dataset']['input_file'] = input_file
config['dataset']['output'] = os.path.join(path, 'YATSM')
config['dataset']['cache_line_dir'] = os.path.join(path, 'cache')
config['classification']['training_image'] = example_training
yaml.dump(config, open(dest_config, 'w'))
return {
'path': subset_path,
'images': stack_images,
'image_IDs': stack_image_IDs,
'input_file': input_file,
'images.csv': df,
'config': dest_config,
}
@pytest.fixture(scope='function')
def example_results(request, tmpdir):
dst = os.path.join(tmpdir.mkdir('data').strpath, 'results')
shutil.copytree(os.path.join(here, 'data', 'results'), dst)
results = {
'root': dst,
'results_dir': os.path.join(dst, 'YATSM'),
'results_dir_classified': os.path.join(dst, 'YATSM_classified'),
'example_img': os.path.join(dst, 'example_image.gtif'),
'classify_config': os.path.join(dst, example_classify_config),
'example_classify_pickle': os.path.join(dst, example_classify_pickle)
}
return results
@pytest.fixture(scope='session')
def example_cache(request):
return np.load(example_cachefile)
# EXAMPLE CACHE DATA
@pytest.fixture(scope='function')
def cachedir(request):
return example_cachedir
@pytest.fixture(scope='function')
def cachefile(request):
return example_cachefile
# MISC
@pytest.fixture(scope='function')
def mkdir_permissions(request):
""" Fixture for creating dir with specific read/write permissions """
def make_mkdir(read=False, write=False):
if read and write:
mode = 0755
elif read and not write:
mode = 0555
elif not read and write:
mode = 0333
elif not read and not write:
mode = 0000
path = mkdtemp()
os.chmod(path, mode)
def fin():
os.chmod(path, 0755)
os.removedirs(path)
request.addfinalizer(fin)
return path
return make_mkdir
|
[] |
[] |
[
"TRAVIS"
] |
[]
|
["TRAVIS"]
|
python
| 1 | 0 | |
dropcopy/dropcopy.py
|
import dropcopy_config
import pyinotify
import pynotify
import shutil
import gobject
import gtk
import os
class Dropcopy(pyinotify.ProcessEvent):
# Main window properties
_WINDOW_HEIGHT = 300
_WINDOW_WIDTH = 100
# Buttons properties
_BUTTON_HEIGHT = 30
_BUTTON_WIDTH = 80
_FILE_CHOOSER_WIDTH = 16
# Icon
_icon_name = None
# Main window and container
_main_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
_fixed_container = gtk.Fixed()
_main_window.add(_fixed_container)
# Preference names
GNUCASH_PREFERENCE = 'gnucashfile'
DROPBOX_FOLDER_PREFERENCE = 'dropboxfolder'
_gnucash_file_chooser = None
_dropbox_file_chooser = None
_dropbox_folder = None
_gnucash_folder = None
_gnucash_file = None
def __init__(self):
self._load_icons()
self._build_system_tray()
self._build_window()
self._build_gnucash_file_chooser()
self._build_dropbox_file_chooser()
self._build_save_button()
self._build_cancel_button()
self._start_monitor()
gtk.main()
self.notifier.stop()
def _load_icons(self):
icon_name = 'dropcopy-logo'
theme = gtk.icon_theme_get_default()
if not theme.has_icon(icon_name):
theme.prepend_search_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".", "icons"))
if theme.has_icon(icon_name):
self._icon_name = icon_name
else:
self._icon_name = gtk.STOCK_NETWORK
def _start_monitor(self):
self._load_configuration()
watch_manager = pyinotify.WatchManager()
self.notifier = pyinotify.ThreadedNotifier(watch_manager, self)
when_saved = pyinotify.IN_CREATE
watch_manager.add_watch(self._gnucash_folder, when_saved, rec=True)
self.notifier.start()
def _restart_monitor(self):
self.notifier.stop()
self._start_monitor()
def _load_configuration(self):
config = dropcopy_config.DropcopyConfig()
gnucash_full_path = config.get_preference(self.GNUCASH_PREFERENCE)
self._dropbox_folder = config.get_preference(self.DROPBOX_FOLDER_PREFERENCE)
self._gnucash_folder, self._gnucash_file = os.path.split(gnucash_full_path)
# It seems that GnuCash only saves its file, it doesn't update
def process_IN_CREATE(self, event):
if event.name == self._gnucash_file:
shutil.copy(event.pathname, self._dropbox_folder + event.name)
self._show_notification('GnuCash file was copied to your local dropbox folder')
def _build_window(self):
self._main_window.set_resizable(False)
self._main_window.set_default_size(self._WINDOW_HEIGHT, self._WINDOW_WIDTH)
self._main_window.set_border_width(10)
self._main_window.set_title('DropCopy')
self._main_window.connect('destroy', self._destroy)
self._main_window.set_icon_name(self._icon_name)
def _build_gnucash_file_chooser(self):
gnucash_label = gtk.Label('GnuCash file:')
self._fixed_container.put(gnucash_label, 5, 10)
self._gnucash_file_chooser = gtk.FileChooserButton('Select the GnuCash file')
self._gnucash_file_chooser.set_current_folder(os.getenv('HOME'))
self._gnucash_file_chooser.set_width_chars(self._FILE_CHOOSER_WIDTH)
self._fixed_container.put(self._gnucash_file_chooser, 115, 1)
def _build_dropbox_file_chooser(self):
dropbox_label = gtk.Label('Dropbox folder:')
self._fixed_container.put(dropbox_label, 5, 50)
self._dropbox_file_chooser = gtk.FileChooserButton('Select the dropbox folder')
self._dropbox_file_chooser.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
self._dropbox_file_chooser.set_current_folder(os.getenv('HOME'))
self._dropbox_file_chooser.set_width_chars(self._FILE_CHOOSER_WIDTH)
self._fixed_container.put(self._dropbox_file_chooser, 115, 40)
def _build_save_button(self):
save_button = gtk.Button('Save')
save_button.set_size_request(self._BUTTON_WIDTH, self._BUTTON_HEIGHT)
save_button.connect('clicked', self._save_preferences)
self._fixed_container.put(save_button, 50, 80)
def _build_cancel_button(self):
cancel_button = gtk.Button('Cancel')
cancel_button.set_size_request(self._BUTTON_WIDTH, self._BUTTON_HEIGHT)
cancel_button.connect('clicked', self._hide_preferences)
self._fixed_container.put(cancel_button, 150, 80)
def _save_preferences(self, widget, data=None):
gnu_cash_file = self._gnucash_file_chooser.get_filename()
dropbox_folder = self._dropbox_file_chooser.get_filename() + os.sep
if gnu_cash_file != None:
config = dropcopy_config.DropcopyConfig()
config.save_preferences(gnu_cash_file, dropbox_folder)
self._show_dialog('Preferences saved.', gtk.MESSAGE_INFO)
self._restart_monitor()
self._hide_preferences()
else:
self._show_dialog('You have to choose a GnuCash file.', gtk.MESSAGE_ERROR)
def _show_dialog(self, error_message, message_type):
error_dialog = gtk.MessageDialog(self._main_window, gtk.DIALOG_DESTROY_WITH_PARENT, message_type, gtk.BUTTONS_CLOSE, error_message)
error_dialog.run()
error_dialog.destroy()
def _destroy(self, widget):
gtk.main_quit()
def _build_system_tray(self):
self.tray = gtk.StatusIcon()
self.tray.set_from_icon_name(self._icon_name)
self.tray.connect('popup-menu', self._show_menu)
self.tray.set_visible(True)
def _show_menu(self, data, event_button, event_time):
menu = gtk.Menu()
preferences_item = gtk.MenuItem('Preferences')
exit_item = gtk.MenuItem('Exit')
menu.append(preferences_item)
menu.append(exit_item)
preferences_item.connect_object('activate', self._show_preferences, 'Preferences')
preferences_item.show()
exit_item.connect_object('activate', self._destroy, 'Exit')
exit_item.show()
menu.popup(None, None, None, event_button, event_time)
def _show_preferences(self, data=None):
self._main_window.show_all()
def _hide_preferences(self, data=None):
self._main_window.hide()
def _show_notification(self, message):
pynotify.init('Dropcopy')
notification = pynotify.Notification('Dropcopy', message)
#notification.set_icon_from_pixbuf(gtk.gdk.pixbuf_new_from_file(self._icon_name))
notification.set_timeout(3000)
notification.show()
if __name__ == "__main__":
gobject.threads_init()
Dropcopy()
|
[] |
[] |
[
"HOME"
] |
[]
|
["HOME"]
|
python
| 1 | 0 | |
config/config.go
|
package config
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"github.com/BurntSushi/toml"
"github.com/pkg/errors"
)
type Self struct {
Data string `toml:"data"`
Config string `toml:"-"`
}
func (s Self) Defaults() Self {
return Self{Data: DefaultDataPath()}
}
func (s Self) Merge(from Self) (is Self) {
is = s
if len(is.Data) == 0 {
is.Data = from.Data
}
if len(is.Config) == 0 {
is.Config = from.Config
}
return
}
type Pub struct {
Host string `toml:"host"`
}
func (p Pub) Defaults() Pub {
return Pub{Host: "https://go-suru.github.io"}
}
func (p Pub) Merge(from Pub) (is Pub) {
is = p
if len(is.Host) == 0 {
is.Host = from.Host
}
return
}
type Topics struct{}
func (t Topics) Defaults() Topics {
return Topics{}
}
func (t Topics) Merge(from Topics) (is Topics) {
return is
}
type Config struct {
Self `toml:"self"`
Pub `toml:"pub,omitempty"`
Topics `toml:"topics,omitempty"`
}
func Defaults() Config {
return Config{
Self: Self{}.Defaults(),
Pub: Pub{}.Defaults(),
Topics: Topics{}.Defaults(),
}
}
// DefaultConfigPaths returns the default path to search for
// config.toml: $HOME/.config/suru (or %APPDATA%/suru on Windows.)
func DefaultConfigPath() string {
home, err := os.UserConfigDir()
if err != nil {
return ".suru"
}
// /home/user/.config/suru
return filepath.Join(home, "suru")
}
func DefaultDataPath() (is string) {
if runtime.GOOS == "windows" {
return filepath.Join(
os.Getenv("APPDATA"),
"suru",
)
}
if dh := os.Getenv("XDG_DATA_HOME"); len(dh) > 0 {
return filepath.Join(is, "suru")
}
home, err := os.UserHomeDir()
if err != nil {
return filepath.Join(".suru")
}
return filepath.Join(home, "suru")
}
// Load searches the given directories for config.toml and loads it into
// the given Config. If there is no config.toml found in any of the
// paths, it creates it in the first location. If no location is
// provided, it uses ".suru".
func Load(cfg *Config, hints ...string) (err error) {
if len(hints) == 0 {
hints = []string{".suru", DefaultConfigPath()}
}
var inf os.FileInfo
var p string
findFolder:
for _, p = range hints {
inf, err = os.Stat(p)
switch {
case os.IsNotExist(err):
continue
case err == nil && !inf.IsDir():
// That wasn't a folder!
return errors.Wrapf(err, "%s isn't a directory", p)
case err == nil:
// Found a folder, check here for config file.
_, err = os.Stat(filepath.Join(p, "config.toml"))
switch {
case os.IsNotExist(errors.Cause(err)):
// No config here, try another folder.
continue
case err == nil:
break findFolder
default:
return errors.Wrapf(err, "checking %s", p)
}
default:
return errors.Wrapf(err, "opening %s", p)
}
}
if os.IsNotExist(err) {
// The suru config wasn't found anywhere, so use the default
// config path.
if cfgPath := cfg.Config; len(cfgPath) > 0 {
// User wants it in a particular place.
p = cfgPath
} else {
p = DefaultConfigPath()
}
}
var f *os.File
p = filepath.Join(p, "config.toml")
// Try opening the config file.
f, err = os.Open(p)
switch {
case os.IsNotExist(err):
// Create and initialize the config file.
return Write(cfg.Merge(Defaults()), p)
case err == nil:
default:
return errors.Wrapf(err, "opening %s", p)
}
// If found, load and merge it.
var newCfg Config
if err := LoadFrom(f, &newCfg); err != nil {
return errors.Wrap(err, "loading config from file")
}
// Let the user know the path, even though it's omitted.
*cfg = cfg.Merge(newCfg)
cfg.Config = p
return nil
}
func (c Config) Merge(from Config) (is Config) {
is = c
is.Self = is.Self.Merge(from.Self)
is.Pub = is.Pub.Merge(from.Pub)
is.Topics = is.Topics.Merge(from.Topics)
return
}
func LoadFrom(r io.Reader, into *Config) error {
bs, err := ioutil.ReadAll(r)
if err != nil {
return errors.Wrap(err, "reading")
}
return errors.Wrap(toml.Unmarshal(bs, into), "decoding TOML")
}
func Write(cfg Config, path string) (err error) {
_, err = os.Stat(filepath.Dir(path))
switch {
case os.IsNotExist(err):
if err = os.MkdirAll(path, 0744); err != nil {
return errors.Wrapf(err, "making %s", path)
}
case err == nil:
default:
return errors.Wrapf(err, "checking %s", path)
}
var f *os.File
if f, err = os.Create(path); err != nil {
return errors.Wrapf(err, "creating %s", path)
}
defer f.Close()
err = toml.NewEncoder(f).Encode(cfg)
return errors.Wrapf(err, "encoding config to %s", path)
}
|
[
"\"APPDATA\"",
"\"XDG_DATA_HOME\""
] |
[] |
[
"APPDATA",
"XDG_DATA_HOME"
] |
[]
|
["APPDATA", "XDG_DATA_HOME"]
|
go
| 2 | 0 | |
molecule/shared/tests/test_default.py
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# def test_hosts_file(host):
# f = host.file('/etc/hosts')
#
# assert f.exists
# assert f.user == 'root'
# assert f.group == 'root'
|
[] |
[] |
[
"MOLECULE_INVENTORY_FILE"
] |
[]
|
["MOLECULE_INVENTORY_FILE"]
|
python
| 1 | 0 | |
MachineLearningHelper/LSTMHelper.py
|
# import os
# from random import randint
#
# from matplotlib import pyplot
# from numpy import array
# from numpy import argmax
# from pandas import DataFrame
# from pandas import concat
# from keras.models import Sequential
# from keras.layers import LSTM
# from keras.layers import Dense
# from keras.layers import TimeDistributed
# from keras.layers import RepeatVector
# import tensorflow as tf
#
# from time import time
# start_time = time()
#
# os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
# config = tf.ConfigProto(intra_op_parallelism_threads=0,
# inter_op_parallelism_threads=0,
# allow_soft_placement=True)
# session = tf.Session(config=config)
#
# numberRange = 100
# listLen = 25
#
#
# # generate a sequence of random numbers in [0, 99]
# def generate_sequence(length=listLen):
# # return [randint(0, numberRange - 1) for _ in range(length)]
# first5 = [randint(0, 5) for _ in range(5)]
# result = first5
# for i in range(5, length):
# currence = sum(result[i-3: i-1]) - result[i-1]
# if currence < 0 or currence >= 100:
# currence = result[i-1]
# result.append(currence)
# return result
#
#
# # one hot encode sequence
# def one_hot_encode(sequence, n_unique=numberRange):
# encoding = list()
# for value in sequence:
# vector = [0 for _ in range(n_unique)]
# vector[value] = 1
# encoding.append(vector)
# return array(encoding)
#
#
# # decode a one hot encoded string
# def one_hot_decode(encoded_seq):
# return [argmax(vector) for vector in encoded_seq]
#
#
# # convert encoded sequence to supervised learning
# def to_supervised(sequence, n_in, n_out):
# # create lag copies of the sequence
# df = DataFrame(sequence)
#
# dfX = concat([df.shift(i) for i in range(n_in, 0, -1)], axis=1)
# dfy = concat([df.shift(-(n_in + i)) for i in range(0, n_out)], axis=1)
# # drop rows with missing values
# dfX.dropna(inplace=True)
# dfy.dropna(inplace=True)
# # specify columns for input and output pairs
# valuesX, valuesy = dfX.values, dfy.values
#
# X = valuesX.reshape(len(valuesX), n_in, -1)
# y = valuesy.reshape(len(valuesy), n_out, -1)
# # (len(X) - len(y) => redundance input. No output
# X = X[0:len(y)]
# return X, y
#
#
# # convert encoded sequence to supervised learning
# def to_supervised_old(sequence, n_in, n_out):
# # create lag copies of the sequence
# df = DataFrame(sequence)
# df = concat([df.shift(n_in - i - 1) for i in range(n_in)], axis=1)
# # drop rows with missing values
# df.dropna(inplace=True)
# # specify columns for input and output pairs
# values = df.values
# width = sequence.shape[1]
# X = values.reshape(len(values), n_in, width)
# y = values[:, 0:(n_out * width)].reshape(len(values), n_out, width)
# return X, y
#
#
# # prepare data for the LSTM
# def get_data(n_in, n_out):
# # generate random sequence
# sequence = generate_sequence()
# # one hot encode
# encoded = one_hot_encode(sequence)
# # convert to X,y pairs
# X, y = to_supervised(encoded, n_in, n_out)
# return X, y
#
#
#
# # define LSTM
# n_in = 6
# n_out = 2
# encoded_length = 100
# batch_size = 6
# model = Sequential()
# model.add(LSTM(150, batch_input_shape=(batch_size, n_in, encoded_length), stateful=True))
# model.add(RepeatVector(n_out))
# model.add(LSTM(150, return_sequences=True, stateful=True))
# model.add(TimeDistributed(Dense(encoded_length, activation='softmax')))
# model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# print(model.summary())
# # train LSTM
# for epoch in range(500):
# # generate new random sequence
# X, y = get_data(n_in, n_out)
# print("------------------------------Sequence: ", epoch, "-------------------------")
# # fit model for one epoch on this sequence
# model.fit(X, y, epochs=15, batch_size=batch_size, verbose=2, shuffle=False)
# model.reset_states()
#
# end_time = time()
# time_taken = end_time - start_time # time_taken is in seconds
# hours, rest = divmod(time_taken, 3600)
# minutes, seconds = divmod(rest, 60)
# print("Total time: ", hours, minutes, int(seconds))
# # evaluate LSTM
# while True:
# X, y = get_data(n_in, n_out)
# yhat = model.predict(X, batch_size=batch_size, verbose=0)
# # decode all pairs
# percent = [1 if one_hot_decode(y[i]) == one_hot_decode(yhat[i]) else 0 for i in range(len(X))]
# print("Ti le du doan dung: ", sum(percent)/len(X))
# for i in range(len(X)):
# print('Input: ', one_hot_decode(X[i]))
# print('Expected: ', one_hot_decode(y[i]))
# print('Predicted:', one_hot_decode(yhat[i]))
|
[] |
[] |
[
"KMP_DUPLICATE_LIB_OK"
] |
[]
|
["KMP_DUPLICATE_LIB_OK"]
|
python
| 1 | 0 | |
commands/pull_request.go
|
package commands
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/github/hub/git"
"github.com/github/hub/github"
"github.com/github/hub/ui"
"github.com/github/hub/utils"
)
var cmdPullRequest = &Command{
Run: pullRequest,
Usage: `
pull-request [-focp] [-b <BASE>] [-h <HEAD>] [-r <REVIEWERS> ] [-a <ASSIGNEES>] [-M <MILESTONE>] [-l <LABELS>]
pull-request -m <MESSAGE>
pull-request -F <FILE> [--edit]
pull-request -i <ISSUE>
`,
Long: `Create a GitHub pull request.
## Options:
-f, --force
Skip the check for unpushed commits.
-m, --message <MESSAGE>
Use the first line of <MESSAGE> as pull request title, and the rest as pull
request description.
-F, --file <FILE>
Read the pull request title and description from <FILE>.
-e, --edit
Further edit the contents of <FILE> in a text editor before submitting.
-i, --issue <ISSUE>, <ISSUE-URL>
(Deprecated) Convert <ISSUE> to a pull request.
-o, --browse
Open the new pull request in a web browser.
-c, --copy
Put the URL of the new pull request to clipboard instead of printing it.
-p, --push
Push the current branch to <HEAD> before creating the pull request.
-b, --base <BASE>
The base branch in "[OWNER:]BRANCH" format. Defaults to the default branch
(usually "master").
-h, --head <HEAD>
The head branch in "[OWNER:]BRANCH" format. Defaults to the current branch.
-r, --reviewer <USERS>
A comma-separated list of GitHub handles to request a review from.
-a, --assign <USERS>
A comma-separated list of GitHub handles to assign to this pull request.
-M, --milestone <NAME>
The milestone name to add to this pull request. Passing the milestone number
is deprecated.
-l, --labels <LABELS>
Add a comma-separated list of labels to this pull request.
## Configuration:
HUB_RETRY_TIMEOUT=<SECONDS>
The maximum time to keep retrying after HTTP 422 on '--push' (default: 9).
## See also:
hub(1), hub-merge(1), hub-checkout(1)
`,
}
var (
flagPullRequestBase,
flagPullRequestHead,
flagPullRequestIssue,
flagPullRequestMessage,
flagPullRequestMilestone,
flagPullRequestFile string
flagPullRequestBrowse,
flagPullRequestCopy,
flagPullRequestEdit,
flagPullRequestPush,
flagPullRequestForce bool
flagPullRequestAssignees,
flagPullRequestReviewers,
flagPullRequestLabels listFlag
)
func init() {
cmdPullRequest.Flag.StringVarP(&flagPullRequestBase, "base", "b", "", "BASE")
cmdPullRequest.Flag.StringVarP(&flagPullRequestHead, "head", "h", "", "HEAD")
cmdPullRequest.Flag.StringVarP(&flagPullRequestIssue, "issue", "i", "", "ISSUE")
cmdPullRequest.Flag.BoolVarP(&flagPullRequestBrowse, "browse", "o", false, "BROWSE")
cmdPullRequest.Flag.BoolVarP(&flagPullRequestCopy, "copy", "c", false, "COPY")
cmdPullRequest.Flag.StringVarP(&flagPullRequestMessage, "message", "m", "", "MESSAGE")
cmdPullRequest.Flag.BoolVarP(&flagPullRequestEdit, "edit", "e", false, "EDIT")
cmdPullRequest.Flag.BoolVarP(&flagPullRequestPush, "push", "p", false, "PUSH")
cmdPullRequest.Flag.BoolVarP(&flagPullRequestForce, "force", "f", false, "FORCE")
cmdPullRequest.Flag.StringVarP(&flagPullRequestFile, "file", "F", "", "FILE")
cmdPullRequest.Flag.VarP(&flagPullRequestAssignees, "assign", "a", "USERS")
cmdPullRequest.Flag.VarP(&flagPullRequestReviewers, "reviewer", "r", "USERS")
cmdPullRequest.Flag.StringVarP(&flagPullRequestMilestone, "milestone", "M", "", "MILESTONE")
cmdPullRequest.Flag.VarP(&flagPullRequestLabels, "labels", "l", "LABELS")
CmdRunner.Use(cmdPullRequest)
}
func pullRequest(cmd *Command, args *Args) {
localRepo, err := github.LocalRepo()
utils.Check(err)
currentBranch, err := localRepo.CurrentBranch()
utils.Check(err)
baseProject, err := localRepo.MainProject()
utils.Check(err)
host, err := github.CurrentConfig().PromptForHost(baseProject.Host)
if err != nil {
utils.Check(github.FormatError("creating pull request", err))
}
client := github.NewClientWithHost(host)
trackedBranch, headProject, err := localRepo.RemoteBranchAndProject(host.User, false)
utils.Check(err)
var (
base, head string
force bool
)
force = flagPullRequestForce
if flagPullRequestBase != "" {
baseProject, base = parsePullRequestProject(baseProject, flagPullRequestBase)
}
if flagPullRequestHead != "" {
headProject, head = parsePullRequestProject(headProject, flagPullRequestHead)
}
if args.ParamsSize() == 1 {
arg := args.RemoveParam(0)
flagPullRequestIssue = parsePullRequestIssueNumber(arg)
}
if base == "" {
masterBranch := localRepo.MasterBranch()
base = masterBranch.ShortName()
}
if head == "" && trackedBranch != nil {
if !trackedBranch.IsRemote() {
// the current branch tracking another branch
// pretend there's no upstream at all
trackedBranch = nil
} else {
if baseProject.SameAs(headProject) && base == trackedBranch.ShortName() {
e := fmt.Errorf(`Aborted: head branch is the same as base ("%s")`, base)
e = fmt.Errorf("%s\n(use `-h <branch>` to specify an explicit pull request head)", e)
utils.Check(e)
}
}
}
if head == "" {
if trackedBranch == nil {
head = currentBranch.ShortName()
} else {
head = trackedBranch.ShortName()
}
}
if headRepo, err := client.Repository(headProject); err == nil {
headProject.Owner = headRepo.Owner.Login
headProject.Name = headRepo.Name
}
fullBase := fmt.Sprintf("%s:%s", baseProject.Owner, base)
fullHead := fmt.Sprintf("%s:%s", headProject.Owner, head)
if !force && trackedBranch != nil {
remoteCommits, _ := git.RefList(trackedBranch.LongName(), "")
if len(remoteCommits) > 0 {
err = fmt.Errorf("Aborted: %d commits are not yet pushed to %s", len(remoteCommits), trackedBranch.LongName())
err = fmt.Errorf("%s\n(use `-f` to force submit a pull request anyway)", err)
utils.Check(err)
}
}
messageBuilder := &github.MessageBuilder{
Filename: "PULLREQ_EDITMSG",
Title: "pull request",
}
baseTracking := base
headTracking := head
remote := gitRemoteForProject(baseProject)
if remote != nil {
baseTracking = fmt.Sprintf("%s/%s", remote.Name, base)
}
if remote == nil || !baseProject.SameAs(headProject) {
remote = gitRemoteForProject(headProject)
}
if remote != nil {
headTracking = fmt.Sprintf("%s/%s", remote.Name, head)
}
if flagPullRequestPush && remote == nil {
utils.Check(fmt.Errorf("Can't find remote for %s", head))
}
messageBuilder.AddCommentedSection(fmt.Sprintf(`Requesting a pull to %s from %s
Write a message for this pull request. The first block
of text is the title and the rest is the description.`, fullBase, fullHead))
if cmd.FlagPassed("message") {
messageBuilder.Message = flagPullRequestMessage
messageBuilder.Edit = flagPullRequestEdit
} else if cmd.FlagPassed("file") {
messageBuilder.Message, err = msgFromFile(flagPullRequestFile)
utils.Check(err)
messageBuilder.Edit = flagPullRequestEdit
} else if flagPullRequestIssue == "" {
messageBuilder.Edit = true
headForMessage := headTracking
if flagPullRequestPush {
headForMessage = head
}
message := ""
commitLogs := ""
commits, _ := git.RefList(baseTracking, headForMessage)
if len(commits) == 1 {
message, err = git.Show(commits[0])
utils.Check(err)
} else if len(commits) > 1 {
commitLogs, err = git.Log(baseTracking, headForMessage)
utils.Check(err)
}
if commitLogs != "" {
messageBuilder.AddCommentedSection("\nChanges:\n\n" + strings.TrimSpace(commitLogs))
}
workdir, _ := git.WorkdirName()
if workdir != "" {
template, _ := github.ReadTemplate(github.PullRequestTemplate, workdir)
if template != "" {
message = message + "\n\n" + template
}
}
messageBuilder.Message = message
}
title, body, err := messageBuilder.Extract()
utils.Check(err)
if title == "" && flagPullRequestIssue == "" {
utils.Check(fmt.Errorf("Aborting due to empty pull request title"))
}
if flagPullRequestPush {
if args.Noop {
args.Before(fmt.Sprintf("Would push to %s/%s", remote.Name, head), "")
} else {
err = git.Spawn("push", "--set-upstream", remote.Name, fmt.Sprintf("HEAD:%s", head))
utils.Check(err)
}
}
milestoneNumber := 0
if flagPullRequestMilestone != "" {
// BC: Don't try to resolve milestone name if it's an integer
milestoneNumber, err = strconv.Atoi(flagPullRequestMilestone)
if err != nil {
milestones, err := client.FetchMilestones(baseProject)
utils.Check(err)
milestoneNumber, err = findMilestoneNumber(milestones, flagPullRequestMilestone)
utils.Check(err)
}
}
var pullRequestURL string
if args.Noop {
args.Before(fmt.Sprintf("Would request a pull request to %s from %s", fullBase, fullHead), "")
pullRequestURL = "PULL_REQUEST_URL"
} else {
params := map[string]interface{}{
"base": base,
"head": fullHead,
}
if title != "" {
params["title"] = title
if body != "" {
params["body"] = body
}
} else {
issueNum, _ := strconv.Atoi(flagPullRequestIssue)
params["issue"] = issueNum
}
startedAt := time.Now()
numRetries := 0
retryDelay := 2
retryAllowance := 0
if flagPullRequestPush {
if allowanceFromEnv := os.Getenv("HUB_RETRY_TIMEOUT"); allowanceFromEnv != "" {
retryAllowance, err = strconv.Atoi(allowanceFromEnv)
utils.Check(err)
} else {
retryAllowance = 9
}
}
var pr *github.PullRequest
for {
pr, err = client.CreatePullRequest(baseProject, params)
if err != nil && strings.Contains(err.Error(), `Invalid value for "head"`) {
if retryAllowance > 0 {
retryAllowance -= retryDelay
time.Sleep(time.Duration(retryDelay) * time.Second)
retryDelay += 1
numRetries += 1
} else {
if numRetries > 0 {
duration := time.Now().Sub(startedAt)
err = fmt.Errorf("%s\nGiven up after retrying for %.1f seconds.", err, duration.Seconds())
}
break
}
} else {
break
}
}
if err == nil {
defer messageBuilder.Cleanup()
}
utils.Check(err)
pullRequestURL = pr.HtmlUrl
params = map[string]interface{}{}
if len(flagPullRequestLabels) > 0 {
params["labels"] = flagPullRequestLabels
}
if len(flagPullRequestAssignees) > 0 {
params["assignees"] = flagPullRequestAssignees
}
if milestoneNumber > 0 {
params["milestone"] = milestoneNumber
}
if len(params) > 0 {
err = client.UpdateIssue(baseProject, pr.Number, params)
utils.Check(err)
}
if len(flagPullRequestReviewers) > 0 {
userReviewers := []string{}
teamReviewers := []string{}
for _, reviewer := range flagPullRequestReviewers {
if strings.Contains(reviewer, "/") {
teamReviewers = append(teamReviewers, strings.SplitN(reviewer, "/", 2)[1])
} else {
userReviewers = append(userReviewers, reviewer)
}
}
err = client.RequestReview(baseProject, pr.Number, map[string]interface{}{
"reviewers": userReviewers,
"team_reviewers": teamReviewers,
})
utils.Check(err)
}
}
if flagPullRequestIssue != "" {
ui.Errorln("Warning: Issue to pull request conversion is deprecated and might not work in the future.")
}
args.NoForward()
printBrowseOrCopy(args, pullRequestURL, flagPullRequestBrowse, flagPullRequestCopy)
}
func parsePullRequestProject(context *github.Project, s string) (p *github.Project, ref string) {
p = context
ref = s
if strings.Contains(s, ":") {
split := strings.SplitN(s, ":", 2)
ref = split[1]
var name string
if !strings.Contains(split[0], "/") {
name = context.Name
}
p = github.NewProject(split[0], name, context.Host)
}
return
}
func parsePullRequestIssueNumber(url string) string {
u, e := github.ParseURL(url)
if e != nil {
return ""
}
r := regexp.MustCompile(`^issues\/(\d+)`)
p := u.ProjectPath()
if r.MatchString(p) {
return r.FindStringSubmatch(p)[1]
}
return ""
}
func findMilestoneNumber(milestones []github.Milestone, name string) (int, error) {
for _, milestone := range milestones {
if strings.EqualFold(milestone.Title, name) {
return milestone.Number, nil
}
}
return 0, fmt.Errorf("error: no milestone found with name '%s'", name)
}
|
[
"\"HUB_RETRY_TIMEOUT\""
] |
[] |
[
"HUB_RETRY_TIMEOUT"
] |
[]
|
["HUB_RETRY_TIMEOUT"]
|
go
| 1 | 0 | |
lib/secret.go
|
package lib
import (
"encoding/json"
"fmt"
"os"
"time"
"github.com/werf/lockgate"
"github.com/werf/lockgate/pkg/file_locker"
"github.com/zalando/go-keyring"
)
var lockDir = os.TempDir() + "/aws-clie-oidc-lock"
var locker lockgate.Locker
var lockResource = "aws-cli-oidc"
func init() {
var err error
locker, err = file_locker.NewFileLocker(lockDir)
if err != nil {
Writeln("Can't setup lock dir: %s", lockDir)
Exit(err)
}
Secret.AWSCredentials = make(map[string]string)
Secret.Load()
}
var secretService = "aws-cli-oidc"
var secretUser = os.Getenv("USER")
var Secret SecretStore
type SecretStore struct {
AWSCredentials map[string]string `json:"credentials"`
}
func (s *SecretStore) Load() {
acquired, lock, err := locker.Acquire(lockResource, lockgate.AcquireOptions{Shared: false, Timeout: 3 * time.Minute})
if err != nil {
Writeln("Can't load secret due to locked now")
Exit(err)
}
defer func() {
if acquired {
if err := locker.Release(lock); err != nil {
Writeln("Can't unlock")
Exit(err)
}
}
}()
if !acquired {
Writeln("Can't load secret due to locked now")
Exit(err)
}
jsonStr, err := keyring.Get(secretService, secretUser)
if err != nil {
if err == keyring.ErrNotFound {
return
}
Writeln("Can't load secret due to unexpected error: %v", err)
Exit(err)
}
if err := json.Unmarshal([]byte(jsonStr), &s); err != nil {
Writeln("Can't load secret due to broken data: %v", err)
Exit(err)
}
}
func (s *SecretStore) Save(roleArn, cred string) {
acquired, lock, err := locker.Acquire(lockResource, lockgate.AcquireOptions{Shared: false, Timeout: 3 * time.Minute})
if err != nil {
Writeln("Can't save secret due to locked now")
Exit(err)
}
defer func() {
if acquired {
if err := locker.Release(lock); err != nil {
Writeln("Can't unlock")
Exit(err)
}
}
}()
// Load the latest credentials
jsonStr, err := keyring.Get(secretService, secretUser)
if err != nil {
if err != keyring.ErrNotFound {
Writeln("Can't load secret due to unexpected error: %v", err)
Exit(err)
}
}
if jsonStr != "" {
if err := json.Unmarshal([]byte(jsonStr), &s); err != nil {
Writeln("Can't load secret due to broken data: %v", err)
Exit(err)
}
}
// Add/Update credential
s.AWSCredentials[roleArn] = cred
// Save
newJsonStr, err := json.Marshal(s)
if err != nil {
Writeln("Can't unlock: %v", err)
Exit(err)
}
if err := keyring.Set(secretService, secretUser, string(newJsonStr)); err != nil {
Writeln("Can't save secret: %v", err)
Exit(err)
}
}
func AWSCredential(roleArn string) (*AWSCredentials, error) {
Secret.Load()
jsonStr, ok := Secret.AWSCredentials[roleArn]
if !ok {
return nil, fmt.Errorf("Not found the credential for %s", roleArn)
}
Writeln("Got credential from OS secret store for %s", roleArn)
var cred AWSCredentials
err := json.Unmarshal([]byte(jsonStr), &cred)
if err != nil {
Writeln("Can't load secret due to the broken data")
Exit(err)
}
return &cred, nil
}
func SaveAWSCredential(roleArn string, cred *AWSCredentials) {
jsonStr, err := json.Marshal(cred)
if err != nil {
Writeln("Can't save secret due to the broken data")
Exit(err)
}
Secret.Save(roleArn, string(jsonStr))
Write("The AWS credentials has been saved in OS secret store")
}
func Clear() error {
return keyring.Delete(secretService, secretUser)
}
|
[
"\"USER\""
] |
[] |
[
"USER"
] |
[]
|
["USER"]
|
go
| 1 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.