repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/convert/convert_qwen3.go
convert/convert_qwen3.go
package convert import ( "slices" "strings" "github.com/ollama/ollama/fs/ggml" "github.com/pdevine/tensor" "github.com/pdevine/tensor/native" ) type qwen3Model struct { ModelParameters MaxPositionEmbeddings uint32 `json:"max_position_embeddings"` HiddenSize uint32 `json:"hidden_size"` HiddenLayers uint32 `json:"num_hidden_layers"` IntermediateSize uint32 `json:"intermediate_size"` NumAttentionHeads uint32 `json:"num_attention_heads"` NumKeyValueHeads uint32 `json:"num_key_value_heads"` HeadDim uint32 `json:"head_dim"` NumExperts uint32 `json:"num_experts"` NumExpertsPerToken uint32 `json:"num_experts_per_tok"` NormTopkProb bool `json:"norm_topk_prob"` RopeTheta float32 `json:"rope_theta"` RopeScaling struct { Type string `json:"type"` Factor ropeFactor `json:"factor"` OriginalMaxPositionEmbeddings uint32 `json:"original_max_position_embeddings"` MropeSection []int32 `json:"mrope_section"` } `json:"rope_scaling"` RMSNormEPS float32 `json:"rms_norm_eps"` } // KV implements ModelConverter. func (q *qwen3Model) KV(t *Tokenizer) ggml.KV { arch := "qwen3" if q.NumExperts > 0 { arch += "moe" } kv := q.ModelParameters.KV(t) kv["general.architecture"] = arch kv["block_count"] = q.HiddenLayers kv["context_length"] = q.MaxPositionEmbeddings kv["embedding_length"] = q.HiddenSize kv["feed_forward_length"] = q.IntermediateSize kv["attention.head_count"] = q.NumAttentionHeads kv["attention.head_count_kv"] = q.NumKeyValueHeads kv["attention.key_length"] = q.HeadDim kv["attention.value_length"] = q.HeadDim if q.NumExperts > 0 { kv["expert_count"] = q.NumExperts kv["expert_used_count"] = q.NumExpertsPerToken kv["norm_top_k_prob"] = q.NormTopkProb } kv["rope.freq_base"] = q.RopeTheta kv["attention.layer_norm_rms_epsilon"] = q.RMSNormEPS switch q.RopeScaling.Type { case "": // no scaling case "yarn": kv["rope.scaling.type"] = q.RopeScaling.Type kv["rope.scaling.factor"] = q.RopeScaling.Factor case "mrope", "default": kv["rope.mrope_section"] = q.RopeScaling.MropeSection default: panic("unknown rope scaling type") } return kv } // Tensors implements ModelConverter. func (q *qwen3Model) Tensors(ts []Tensor) []*ggml.Tensor { var out []*ggml.Tensor // TODO: handle split experts for _, t := range ts { switch { case strings.Contains(t.Name(), "ffn_gate_up_exps"): afterFunc := func(t tensor.Tensor) (tensor.Tensor, error) { return tensor.Transpose(t, 0, 2, 1) } for t := range splitDim(t, 2, split{Replacer: strings.NewReplacer("gate_up", "gate"), afterFunc: afterFunc}, split{Replacer: strings.NewReplacer("gate_up", "up"), afterFunc: afterFunc}, ) { t.Shape[1], t.Shape[2] = t.Shape[2], t.Shape[1] out = append(out, t) } case strings.Contains(t.Name(), "ffn_down_exps"): shape := slices.Clone(t.Shape()) shape[1], shape[2] = shape[2], shape[1] t.SetRepacker(func(_ string, data []float32, shape []uint64) ([]float32, error) { dims := make([]int, len(shape)) for i := range shape { dims[i] = int(shape[i]) } var tt tensor.Tensor = tensor.New(tensor.WithShape(dims...), tensor.WithBacking(data)) tt, err := tensor.Transpose(tt, 0, 2, 1) if err != nil { return nil, err } // flatten tensor so it can be written as a vector if err := tt.Reshape(tt.Shape().TotalSize()); err != nil { return nil, err } return native.VectorF32(tt.(*tensor.Dense)) }) out = append(out, &ggml.Tensor{ Name: t.Name(), Kind: t.Kind(), Shape: shape, WriterTo: t, }) default: out = append(out, &ggml.Tensor{ Name: t.Name(), Kind: t.Kind(), Shape: t.Shape(), WriterTo: t, }) } } return out } // Replacements implements ModelConverter. func (q *qwen3Model) Replacements() []string { return []string{ "lm_head", "output", "model.embed_tokens", "token_embd", "model.layers", "blk", "input_layernorm", "attn_norm", "self_attn.k_proj", "attn_k", "self_attn.k_norm", "attn_k_norm", "self_attn.v_proj", "attn_v", "self_attn.q_proj", "attn_q", "self_attn.q_norm", "attn_q_norm", "self_attn.o_proj", "attn_output", "mlp.down_proj", "ffn_down", "mlp.gate_proj", "ffn_gate", "mlp.up_proj", "ffn_up", "mlp.gate.weight", "ffn_gate_inp.weight", "mlp.experts.down_proj", "ffn_down_exps.weight", "mlp.experts.gate_up_proj", "ffn_gate_up_exps.weight", "post_attention_layernorm", "ffn_norm", "model.norm", "output_norm", } } var _ ModelConverter = (*qwen3Model)(nil)
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/convert/convert_bert.go
convert/convert_bert.go
package convert import ( "cmp" "encoding/json" "io/fs" "path/filepath" "slices" "strings" "github.com/ollama/ollama/fs/ggml" ) type bertModel struct { ModelParameters NLayers uint32 `json:"n_layers"` NumHiddenLayers uint32 `json:"num_hidden_layers"` NLayer uint32 `json:"n_layer"` MaxPositionEmbeddings uint32 `json:"max_position_embeddings"` NCtx uint32 `json:"n_ctx"` HiddenSize uint32 `json:"hidden_size"` NEmbd uint32 `json:"n_embd"` IntermediateSize uint32 `json:"intermediate_size"` NInner uint32 `json:"n_inner"` NumAttentionHeads uint32 `json:"num_attention_heads"` NHead uint32 `json:"n_head"` NumKeyValueHeads uint32 `json:"num_key_value_heads"` LayerNormEPS float32 `json:"layer_norm_eps"` LayerNormEpsilon float32 `json:"layer_norm_epsilon"` NormEpsilon float32 `json:"norm_epsilon"` normalizeEmbeddings bool PoolingType uint32 } var ( _ ModelConverter = (*bertModel)(nil) _ moreParser = (*bertModel)(nil) ) func (p *bertModel) parseMore(fsys fs.FS) error { bts, err := fs.ReadFile(fsys, "modules.json") if err != nil { return err } var modules []struct { Type string `json:"type"` Path string `json:"path"` } if err := json.Unmarshal(bts, &modules); err != nil { return err } var pooling string for _, m := range modules { switch m.Type { case "sentence_transformers.models.Pooling": pooling = m.Path case "sentence_transformers.models.Normalize": p.normalizeEmbeddings = true } } if pooling != "" { bts, err := fs.ReadFile(fsys, filepath.Join(pooling, "config.json")) if err != nil { return err } var pc struct { PoolingModeCLSToken bool `json:"pooling_mode_cls_token"` PoolingModeMeanTokens bool `json:"pooling_mode_mean_tokens"` } if err := json.Unmarshal(bts, &pc); err != nil { return err } if pc.PoolingModeMeanTokens { p.PoolingType = 1 } else if pc.PoolingModeCLSToken { p.PoolingType = 2 } } return nil } func (p *bertModel) KV(t *Tokenizer) ggml.KV { kv := p.ModelParameters.KV(t) kv["general.architecture"] = "bert" kv["bert.attention.causal"] = false kv["bert.pooling_type"] = p.PoolingType kv["bert.normalize_embeddings"] = p.normalizeEmbeddings kv["bert.block_count"] = cmp.Or(p.NLayers, p.NumHiddenLayers, p.NLayer) if contextLength := cmp.Or(p.MaxPositionEmbeddings, p.NCtx); contextLength > 0 { kv["bert.context_length"] = contextLength } if embeddingLength := cmp.Or(p.HiddenSize, p.NEmbd); embeddingLength > 0 { kv["bert.embedding_length"] = cmp.Or(p.HiddenSize, p.NEmbd) } if feedForwardLength := cmp.Or(p.IntermediateSize, p.NInner); feedForwardLength > 0 { kv["bert.feed_forward_length"] = cmp.Or(p.IntermediateSize, p.NInner) } if headCount := cmp.Or(p.NumAttentionHeads, p.NHead); headCount > 0 { kv["bert.attention.head_count"] = cmp.Or(p.NumAttentionHeads, p.NHead) } if layerNormEpsilon := cmp.Or(p.LayerNormEPS, p.LayerNormEpsilon, p.NormEpsilon); layerNormEpsilon > 0 { kv["bert.attention.layer_norm_epsilon"] = layerNormEpsilon } kv["tokenizer.ggml.model"] = "bert" kv["tokenizer.ggml.token_type_count"] = uint32(2) // convert to phantom space tokens for i, e := range t.Tokens { if strings.HasPrefix(e, "[") && strings.HasSuffix(e, "]") { // noop } else if strings.HasPrefix(e, "##") { t.Tokens[i] = e[2:] } else { t.Tokens[i] = "\u2581" + e } } kv["tokenizer.ggml.tokens"] = t.Tokens return kv } func (p *bertModel) Tensors(ts []Tensor) []*ggml.Tensor { var out []*ggml.Tensor for _, t := range ts { if slices.Contains([]string{ "embeddings.position_ids", "pooler.dense.weight", "pooler.dense.bias", }, t.Name()) { continue } out = append(out, &ggml.Tensor{ Name: t.Name(), Kind: t.Kind(), Shape: t.Shape(), WriterTo: t, }) } return out } func (bertModel) Replacements() []string { return []string{ "encoder.layer", "blk", "encoder.layers", "blk", "embeddings.word_embeddings", "token_embd", "embeddings.token_type_embeddings", "token_types", "embeddings.LayerNorm", "token_embd_norm", "embeddings.position_embeddings", "position_embd", "attention.self.query", "attn_q", "attention.self.key", "attn_k", "attention.self.value", "attn_v", "attention.output.dense", "attn_output", "attention.output.LayerNorm", "attn_output_norm", "intermediate.dense", "ffn_up", "output.dense", "ffn_down", "output.LayerNorm", "layer_output_norm", } }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/convert/convert_mistral_causal.go
convert/convert_mistral_causal.go
package convert import ( "cmp" "fmt" "strings" "github.com/pdevine/tensor" "github.com/pdevine/tensor/native" "github.com/ollama/ollama/fs/ggml" ) type mistral3CausalModel struct { ModelParameters NumHiddenLayers uint32 `json:"num_hidden_layers"` MaxPositionEmbeddings uint32 `json:"max_position_embeddings"` HiddenSize uint32 `json:"hidden_size"` IntermediateSize uint32 `json:"intermediate_size"` NumAttentionHeads uint32 `json:"num_attention_heads"` NumKeyValueHeads uint32 `json:"num_key_value_heads"` RopeTheta float32 `json:"rope_theta"` RMSNormEPS float32 `json:"rms_norm_eps"` HeadDim uint32 `json:"head_dim"` SlidingWindow *uint32 `json:"sliding_window"` HiddenAct string `json:"hidden_act"` VocabSize uint32 `json:"vocab_size"` RopeParameters struct { BetaFast float32 `json:"beta_fast"` BetaSlow float32 `json:"beta_slow"` Factor float32 `json:"factor"` Llama4ScalingBeta *float32 `json:"llama_4_scaling_beta"` OrigMaxPositionEmbeddings uint32 `json:"original_max_position_embeddings"` RopeType string `json:"rope_type"` RopeTheta float32 `json:"rope_theta"` Mscale *float32 `json:"mscale"` MscaleAllDim *float32 `json:"mscale_all_dim"` } `json:"rope_parameters"` } func (p *mistral3CausalModel) KV(t *Tokenizer) ggml.KV { kv := p.ModelParameters.KV(t) kv["general.architecture"] = "mistral3" kv["mistral3.vocab_size"] = p.VocabSize // Text configuration kv["mistral3.block_count"] = p.NumHiddenLayers kv["mistral3.context_length"] = p.MaxPositionEmbeddings kv["mistral3.embedding_length"] = p.HiddenSize kv["mistral3.feed_forward_length"] = p.IntermediateSize kv["mistral3.attention.head_count"] = p.NumAttentionHeads kv["mistral3.attention.head_count_kv"] = p.NumKeyValueHeads kv["mistral3.attention.layer_norm_rms_epsilon"] = p.RMSNormEPS kv["mistral3.attention.key_length"] = p.HeadDim kv["mistral3.attention.value_length"] = p.HeadDim kv["mistral3.rope.dimension_count"] = cmp.Or(p.HeadDim, p.HiddenSize/p.NumAttentionHeads) kv["mistral3.rope.freq_base"] = cmp.Or(p.RopeTheta, p.RopeParameters.RopeTheta) kv["mistral3.rope.scaling.factor"] = p.RopeParameters.Factor kv["mistral3.rope.scaling.type"] = p.RopeParameters.RopeType kv["mistral3.rope.scaling.beta_fast"] = p.RopeParameters.BetaFast kv["mistral3.rope.scaling.beta_slow"] = p.RopeParameters.BetaSlow if p.RopeParameters.Mscale != nil { kv["mistral3.rope.scaling.mscale"] = *p.RopeParameters.Mscale } if p.RopeParameters.MscaleAllDim != nil { kv["mistral3.rope.scaling.mscale_all_dim"] = *p.RopeParameters.MscaleAllDim } if p.RopeParameters.OrigMaxPositionEmbeddings > 0 { kv["mistral3.rope.scaling.original_context_length"] = p.RopeParameters.OrigMaxPositionEmbeddings kv["mistral3.rope.scaling_beta"] = *p.RopeParameters.Llama4ScalingBeta } if p.RopeParameters.Llama4ScalingBeta != nil { kv["mistral3.rope.scaling_beta"] = *p.RopeParameters.Llama4ScalingBeta } return kv } func (p *mistral3CausalModel) Tensors(ts []Tensor) []*ggml.Tensor { var out []*ggml.Tensor for _, t := range ts { if !strings.HasPrefix(t.Name(), "v.") { if strings.HasSuffix(t.Name(), ".attn_q.weight") || strings.HasSuffix(t.Name(), ".attn_k.weight") { t.SetRepacker(p.repack) } } out = append(out, &ggml.Tensor{ Name: t.Name(), Kind: t.Kind(), Shape: t.Shape(), WriterTo: t, }) } return out } func (p *mistral3CausalModel) Replacements() []string { return []string{ "model.norm", "output_norm", "model.", "", "layers", "blk", "transformer.layers", "blk", "vision_tower", "v", "ln_pre", "encoder_norm", "input_layernorm", "attn_norm", "post_attention_layernorm", "ffn_norm", "embed_tokens", "token_embd", "self_attn.q_proj", "attn_q", "self_attn.k_proj", "attn_k", "self_attn.v_proj", "attn_v", "self_attn.o_proj", "attn_output", "mlp.down_proj", "ffn_down", "mlp.gate_proj", "ffn_gate", "mlp.up_proj", "ffn_up", "attention.q_proj", "attn_q", "attention.k_proj", "attn_k", "attention.v_proj", "attn_v", "attention.o_proj", "attn_output", "attention_norm", "attn_norm", "feed_forward.gate_proj", "ffn_gate", "feed_forward.down_proj", "ffn_down", "feed_forward.up_proj", "ffn_up", "multi_modal_projector", "mm", "ffn_norm", "ffn_norm", "lm_head", "output", } } func (p *mistral3CausalModel) repack(name string, data []float32, shape []uint64) ([]float32, error) { var dims []int for _, dim := range shape { dims = append(dims, int(dim)) } var heads uint32 if strings.HasSuffix(name, ".attn_q.weight") { heads = p.NumAttentionHeads } else if strings.HasSuffix(name, ".attn_k.weight") { heads = cmp.Or(p.NumKeyValueHeads, p.NumAttentionHeads) } else { return nil, fmt.Errorf("unknown tensor for repack: %s", name) } n := tensor.New(tensor.WithShape(dims...), tensor.WithBacking(data)) if err := n.Reshape(append([]int{int(heads), 2, dims[0] / int(heads) / 2}, dims[1:]...)...); err != nil { return nil, err } if err := n.T(0, 2, 1, 3); err != nil { return nil, err } if err := n.Reshape(dims...); err != nil { return nil, err } if err := n.Transpose(); err != nil { return nil, err } ts, err := native.SelectF32(n, 1) if err != nil { return nil, err } var f32s []float32 for _, t := range ts { f32s = append(f32s, t...) } return f32s, nil }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/convert/convert_commandr.go
convert/convert_commandr.go
package convert import ( "cmp" "github.com/ollama/ollama/fs/ggml" ) type commandrModel struct { ModelParameters MaxPositionEmbeddings uint32 `json:"max_position_embeddings"` HiddenSize uint32 `json:"hidden_size"` HiddenLayers uint32 `json:"num_hidden_layers"` IntermediateSize uint32 `json:"intermediate_size"` NumAttentionHeads uint32 `json:"num_attention_heads"` NumKeyValueHeads uint32 `json:"num_key_value_heads"` LayerNormEPS float32 `json:"layer_norm_eps"` RopeTheta float32 `json:"rope_theta"` UseQKNorm bool `json:"use_qk_norm"` MaxLength uint32 `json:"model_max_length"` LogitScale float32 `json:"logit_scale"` NCtx uint32 `json:"n_ctx"` } var _ ModelConverter = (*commandrModel)(nil) func (p *commandrModel) KV(t *Tokenizer) ggml.KV { kv := p.ModelParameters.KV(t) kv["general.architecture"] = "command-r" kv["general.name"] = "command-r" kv["command-r.context_length"] = cmp.Or(p.MaxLength, p.MaxPositionEmbeddings, p.NCtx) kv["command-r.embedding_length"] = p.HiddenSize kv["command-r.block_count"] = p.HiddenLayers kv["command-r.feed_forward_length"] = p.IntermediateSize kv["command-r.attention.head_count"] = p.NumAttentionHeads kv["command-r.attention.head_count_kv"] = p.NumKeyValueHeads kv["command-r.attention.layer_norm_epsilon"] = p.LayerNormEPS kv["command-r.rope.freq_base"] = p.RopeTheta kv["command-r.max_position_embeddings"] = cmp.Or(p.MaxLength, p.MaxPositionEmbeddings) kv["command-r.logit_scale"] = p.LogitScale kv["command-r.rope.scaling.type"] = "none" return kv } func (p *commandrModel) Tensors(ts []Tensor) []*ggml.Tensor { var out []*ggml.Tensor for _, t := range ts { out = append(out, &ggml.Tensor{ Name: t.Name(), Kind: t.Kind(), Shape: t.Shape(), WriterTo: t, }) } return out } func (p *commandrModel) Replacements() []string { return []string{ "self_attn.q_norm", "attn_q_norm", "self_attn.k_norm", "attn_k_norm", "model.layers", "blk", "input_layernorm", "attn_norm", "mlp.down_proj", "ffn_down", "mlp.gate_proj", "ffn_gate", "mlp.up_proj", "ffn_up", "self_attn.k_proj", "attn_k", "self_attn.o_proj", "attn_output", "self_attn.q_proj", "attn_q", "self_attn.v_proj", "attn_v", "model.norm", "output_norm", "model.embed_tokens", "token_embd", } }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/convert/convert_llama_adapter.go
convert/convert_llama_adapter.go
package convert import ( "cmp" "strings" "github.com/pdevine/tensor" "github.com/pdevine/tensor/native" "github.com/ollama/ollama/fs/ggml" ) type llamaAdapter struct { AdapterParameters NumAttentionHeads uint32 `json:"num_attention_heads"` NumKeyValueHeads uint32 `json:"num_key_value_heads"` } var _ AdapterConverter = (*llamaAdapter)(nil) func (p *llamaAdapter) KV(baseKV ggml.KV) ggml.KV { kv := p.AdapterParameters.KV() kv["general.architecture"] = "llama" kv["llama.attention.head_count"] = baseKV["llama.attention.head_count"] kv["llama.attention.head_count_kv"] = baseKV["llama.attention.head_count_kv"] p.NumAttentionHeads = baseKV["llama.attention.head_count"].(uint32) return kv } func (p *llamaAdapter) Tensors(ts []Tensor) []*ggml.Tensor { var out []*ggml.Tensor for _, t := range ts { shape := t.Shape() if (strings.HasSuffix(t.Name(), "weight.lora_a") && shape[0] > shape[1]) || (strings.HasSuffix(t.Name(), "weight.lora_b") && shape[0] < shape[1]) { shape[0], shape[1] = shape[1], shape[0] t.SetRepacker(p.repackAndTranspose) } else { t.SetRepacker(p.repack) } out = append(out, &ggml.Tensor{ Name: t.Name(), Kind: t.Kind(), Shape: shape, WriterTo: t, }) } return out } func (p *llamaAdapter) Replacements() []string { return []string{ "base_model.model.", "", "model.layers", "blk", "self_attn.q_proj", "attn_q", "self_attn.k_proj", "attn_k", "self_attn.v_proj", "attn_v", "self_attn.o_proj", "attn_output", "mlp.gate_proj", "ffn_gate", "mlp.down_proj", "ffn_down", "mlp.up_proj", "ffn_up", "lora_A.weight", "weight.lora_a", "lora_B.weight", "weight.lora_b", "lora_a", "weight.lora_a", "lora_b", "weight.lora_b", } } func (p *llamaAdapter) repack(name string, data []float32, shape []uint64) ([]float32, error) { dims := []int{int(shape[1]), int(shape[0])} var heads uint32 if strings.HasSuffix(name, "attn_q.weight.lora_a") { heads = p.NumAttentionHeads } else if strings.HasSuffix(name, "attn_k.weight.lora_a") { heads = cmp.Or(p.NumKeyValueHeads, p.NumAttentionHeads) } else { return data, nil } n := tensor.New(tensor.WithShape(dims...), tensor.WithBacking(data)) if err := n.Reshape(append([]int{int(heads), 2, dims[0] / int(heads) / 2}, dims[1:]...)...); err != nil { return nil, err } if err := n.T(0, 2, 1, 3); err != nil { return nil, err } if err := n.Reshape(dims...); err != nil { return nil, err } if err := n.Transpose(); err != nil { return nil, err } ts, err := native.SelectF32(n, 1) if err != nil { return nil, err } var f32s []float32 for _, t := range ts { f32s = append(f32s, t...) } return f32s, nil } func (p *llamaAdapter) repackAndTranspose(name string, data []float32, shape []uint64) ([]float32, error) { dims := []int{int(shape[1]), int(shape[0])} n := tensor.New(tensor.WithShape(dims...), tensor.WithBacking(data)) var heads uint32 if strings.HasSuffix(name, "attn_q.weight.lora_a") { heads = p.NumAttentionHeads } else if strings.HasSuffix(name, "attn_k.weight.lora_a") { heads = cmp.Or(p.NumKeyValueHeads, p.NumAttentionHeads) } if heads > 0 { if err := n.Reshape(append([]int{int(heads), 2, dims[0] / int(heads) / 2}, dims[1:]...)...); err != nil { return nil, err } if err := n.T(0, 2, 1, 3); err != nil { return nil, err } if err := n.Reshape(dims...); err != nil { return nil, err } if err := n.Transpose(); err != nil { return nil, err } } if err := n.T(1, 0); err != nil { return nil, err } if err := n.Reshape(dims...); err != nil { return nil, err } if err := n.Transpose(); err != nil { return nil, err } ts, err := native.SelectF32(n, 1) if err != nil { return nil, err } var f32s []float32 for _, t := range ts { f32s = append(f32s, t...) } return f32s, nil }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/convert/convert_qwen2.go
convert/convert_qwen2.go
package convert import "github.com/ollama/ollama/fs/ggml" type qwen2Model struct { ModelParameters MaxPositionEmbeddings uint32 `json:"max_position_embeddings"` HiddenSize uint32 `json:"hidden_size"` HiddenLayers uint32 `json:"num_hidden_layers"` IntermediateSize uint32 `json:"intermediate_size"` NumAttentionHeads uint32 `json:"num_attention_heads"` NumKeyValueHeads uint32 `json:"num_key_value_heads"` RopeTheta float32 `json:"rope_theta"` RopeScaling struct { Type string `json:"type"` Factor ropeFactor `json:"factor"` OriginalMaxPositionEmbeddings uint32 `json:"original_max_position_embeddings"` MropeSection []int32 `json:"mrope_section"` } `json:"rope_scaling"` RMSNormEPS float32 `json:"rms_norm_eps"` } var _ ModelConverter = (*qwen2Model)(nil) func (q *qwen2Model) KV(t *Tokenizer) ggml.KV { kv := q.ModelParameters.KV(t) kv["general.architecture"] = "qwen2" kv["qwen2.block_count"] = q.HiddenLayers kv["qwen2.context_length"] = q.MaxPositionEmbeddings kv["qwen2.embedding_length"] = q.HiddenSize kv["qwen2.feed_forward_length"] = q.IntermediateSize kv["qwen2.attention.head_count"] = q.NumAttentionHeads kv["qwen2.attention.head_count_kv"] = q.NumKeyValueHeads kv["qwen2.rope.freq_base"] = q.RopeTheta kv["qwen2.attention.layer_norm_rms_epsilon"] = q.RMSNormEPS switch q.RopeScaling.Type { case "": // no scaling case "yarn": kv["qwen2.rope.scaling.type"] = q.RopeScaling.Type kv["qwen2.rope.scaling.factor"] = q.RopeScaling.Factor case "mrope", "default": kv["qwen2.rope.mrope_section"] = q.RopeScaling.MropeSection default: panic("unknown rope scaling type") } return kv } func (q *qwen2Model) Tensors(ts []Tensor) []*ggml.Tensor { var out []*ggml.Tensor for _, t := range ts { out = append(out, &ggml.Tensor{ Name: t.Name(), Kind: t.Kind(), Shape: t.Shape(), WriterTo: t, }) } return out } func (p *qwen2Model) Replacements() []string { return []string{ "lm_head", "output", "model.embed_tokens", "token_embd", "model.layers", "blk", "input_layernorm", "attn_norm", "self_attn.k_proj", "attn_k", "self_attn.v_proj", "attn_v", "self_attn.q_proj", "attn_q", "self_attn.o_proj", "attn_output", "mlp.down_proj", "ffn_down", "mlp.gate_proj", "ffn_gate", "mlp.up_proj", "ffn_up", "post_attention_layernorm", "ffn_norm", "model.norm", "output_norm", } }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/convert/convert_qwen3vl.go
convert/convert_qwen3vl.go
package convert import ( "cmp" "encoding/json" "io/fs" "slices" "strings" "github.com/ollama/ollama/fs/ggml" ) type qwen3VLModel struct { qwen3Model `json:"text_config"` VisionModel struct { Depth uint32 `json:"depth"` HiddenSize uint32 `json:"hidden_size"` NumHeads uint32 `json:"num_heads"` InChannels uint32 `json:"in_channels"` PatchSize uint32 `json:"patch_size"` SpatialMergeSize uint32 `json:"spatial_merge_size"` WindowSize uint32 `json:"window_size"` RMSNormEps float32 `json:"layer_norm_epsilon"` RopeTheta float32 `json:"rope_theta"` TemporalPatchSize uint32 `json:"temporal_patch_size"` DeepstackVisualIndexes []int32 `json:"deepstack_visual_indexes"` Size struct { ShortestEdge uint32 `json:"shortest_edge"` LongestEdge uint32 `json:"longest_edge"` } `json:"size"` ImageMean []float32 `json:"image_mean"` ImageStd []float32 `json:"image_std"` } `json:"vision_config"` } func (m *qwen3VLModel) parseMore(fsys fs.FS) error { bts, err := fs.ReadFile(fsys, "preprocessor_config.json") if err != nil { return err } return json.Unmarshal(bts, &m.VisionModel) } func (m *qwen3VLModel) KV(t *Tokenizer) ggml.KV { kv := m.qwen3Model.KV(t) arch := "qwen3vl" if m.NumExperts > 0 { arch += "moe" } // override architecture kv["general.architecture"] = arch kv["vision.block_count"] = cmp.Or(m.VisionModel.Depth, 32) kv["vision.embedding_length"] = m.VisionModel.HiddenSize kv["vision.attention.head_count"] = cmp.Or(m.VisionModel.NumHeads, 16) kv["vision.num_channels"] = m.VisionModel.InChannels kv["vision.patch_size"] = cmp.Or(m.VisionModel.PatchSize, 14) kv["vision.spatial_merge_size"] = cmp.Or(m.VisionModel.SpatialMergeSize, 2) kv["vision.attention.layer_norm_epsilon"] = cmp.Or(m.VisionModel.RMSNormEps, 1e-6) kv["vision.rope.freq_base"] = cmp.Or(m.VisionModel.RopeTheta, 1e4) kv["vision.temporal_patch_size"] = cmp.Or(m.VisionModel.TemporalPatchSize, 2) kv["vision.deepstack_visual_indexes"] = m.VisionModel.DeepstackVisualIndexes kv["vision.shortest_edge"] = m.VisionModel.Size.ShortestEdge kv["vision.longest_edge"] = m.VisionModel.Size.LongestEdge kv["vision.image_mean"] = m.VisionModel.ImageMean kv["vision.image_std"] = m.VisionModel.ImageStd return kv } func (m *qwen3VLModel) Tensors(ts []Tensor) []*ggml.Tensor { var rest []Tensor var out []*ggml.Tensor for _, t := range ts { switch { case strings.Contains(t.Name(), "attn_qkv"): out = append(out, slices.Collect(splitDim(t, 0, split{Replacer: strings.NewReplacer("attn_qkv", "attn_q")}, split{Replacer: strings.NewReplacer("attn_qkv", "attn_k")}, split{Replacer: strings.NewReplacer("attn_qkv", "attn_v")}, ))...) case strings.Contains(t.Name(), "patch_embed") && strings.HasSuffix(t.Name(), "weight"): shape := t.Shape() out = append(out, &ggml.Tensor{ Name: t.Name(), Kind: t.Kind(), Shape: append([]uint64{shape[0] * shape[1]}, shape[2:]...), WriterTo: t, }) default: rest = append(rest, t) } } return append(m.qwen3Model.Tensors(rest), out...) } func (m *qwen3VLModel) Replacements() []string { return append( m.qwen3Model.Replacements(), "model.language_", "", "model.visual", "v", "patch_embed.proj", "patch_embed", "blocks", "blk", "attn.qkv", "attn_qkv", "attn.proj", "attn_out", "deepstack_merger_list", "deepstack_merger", ) }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/convert/convert_qwen25vl.go
convert/convert_qwen25vl.go
package convert import ( "cmp" "slices" "strings" "github.com/ollama/ollama/fs/ggml" ) type qwen25VLModel struct { qwen2Model VisionModel struct { Depth uint32 `json:"depth"` HiddenSize uint32 `json:"hidden_size"` NumHeads uint32 `json:"num_heads"` InChannels uint32 `json:"in_chans"` PatchSize uint32 `json:"patch_size"` SpatialMergeSize uint32 `json:"spatial_merge_size"` SpatialPatchSize uint32 `json:"spatial_patch_size"` WindowSize uint32 `json:"window_size"` RMSNormEps float32 `json:"layer_norm_epsilon"` RopeTheta float32 `json:"rope_theta"` FullAttentionBlocks []int32 `json:"fullatt_block_indexes"` TemporalPatchSize uint32 `json:"temporal_patch_size"` } `json:"vision_config"` } var _ ModelConverter = (*qwen25VLModel)(nil) func (q *qwen25VLModel) KV(t *Tokenizer) ggml.KV { kv := q.ModelParameters.KV(t) kv["general.architecture"] = "qwen25vl" for k, v := range q.qwen2Model.KV(t) { if strings.HasPrefix(k, "qwen2.") { kv[strings.Replace(k, "qwen2.", "qwen25vl.", 1)] = v } } if q.VisionModel.FullAttentionBlocks == nil { kv["qwen25vl.vision.fullatt_block_indexes"] = []int32{7, 15, 23, 31} } kv["qwen25vl.vision.block_count"] = cmp.Or(q.VisionModel.Depth, 32) kv["qwen25vl.vision.embedding_length"] = q.VisionModel.HiddenSize kv["qwen25vl.vision.attention.head_count"] = cmp.Or(q.VisionModel.NumHeads, 16) kv["qwen25vl.vision.num_channels"] = q.VisionModel.InChannels kv["qwen25vl.vision.patch_size"] = cmp.Or(q.VisionModel.PatchSize, 14) kv["qwen25vl.vision.spatial_merge_size"] = cmp.Or(q.VisionModel.SpatialMergeSize, 2) kv["qwen25vl.vision.spatial_patch_size"] = q.VisionModel.SpatialPatchSize kv["qwen25vl.vision.window_size"] = cmp.Or(q.VisionModel.WindowSize, 112) kv["qwen25vl.vision.attention.layer_norm_epsilon"] = cmp.Or(q.VisionModel.RMSNormEps, 1e-6) kv["qwen25vl.vision.rope.freq_base"] = cmp.Or(q.VisionModel.RopeTheta, 1e4) kv["qwen25vl.vision.fullatt_block_indexes"] = q.VisionModel.FullAttentionBlocks kv["qwen25vl.vision.temporal_patch_size"] = cmp.Or(q.VisionModel.TemporalPatchSize, 2) return kv } func (q *qwen25VLModel) Tensors(ts []Tensor) []*ggml.Tensor { var out []*ggml.Tensor for _, t := range ts { if strings.Contains(t.Name(), "patch_embed.proj") { for t := range splitDim(t, 2, split{Replacer: strings.NewReplacer("patch_embed.proj", "patch_embd_0")}, split{Replacer: strings.NewReplacer("patch_embed.proj", "patch_embd_1")}, ) { t.Shape = slices.DeleteFunc(t.Shape, func(i uint64) bool { return i == 1 }) out = append(out, t) } } else if strings.Contains(t.Name(), "attn.qkv") { out = append(out, slices.Collect(splitDim(t, 0, split{Replacer: strings.NewReplacer("attn.qkv", "attn_q")}, split{Replacer: strings.NewReplacer("attn.qkv", "attn_k")}, split{Replacer: strings.NewReplacer("attn.qkv", "attn_v")}, ))...) } else { out = append(out, &ggml.Tensor{ Name: t.Name(), Kind: t.Kind(), Shape: t.Shape(), WriterTo: t, }) } } return out } func (p *qwen25VLModel) Replacements() []string { return append( p.qwen2Model.Replacements(), "visual", "v", "blocks", "blk", "attn.proj", "attn_out", "norm1", "ln1", "norm2", "ln2", ) }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/convert/convert_llama.go
convert/convert_llama.go
package convert import ( "cmp" "fmt" "math" "strings" "github.com/pdevine/tensor" "github.com/pdevine/tensor/native" "github.com/ollama/ollama/fs/ggml" ) type llamaModel struct { ModelParameters NLayers uint32 `json:"n_layers"` NumHiddenLayers uint32 `json:"num_hidden_layers"` NLayer uint32 `json:"n_layer"` MaxPositionEmbeddings uint32 `json:"max_position_embeddings"` NCtx uint32 `json:"n_ctx"` HiddenSize uint32 `json:"hidden_size"` NEmbd uint32 `json:"n_embd"` IntermediateSize uint32 `json:"intermediate_size"` NInner uint32 `json:"n_inner"` NumAttentionHeads uint32 `json:"num_attention_heads"` NHead uint32 `json:"n_head"` NumKeyValueHeads uint32 `json:"num_key_value_heads"` RopeTheta float32 `json:"rope_theta"` RopeScaling struct { Type string `json:"type"` RopeType string `json:"rope_type"` Factor float32 `json:"factor"` LowFrequencyFactor float32 `json:"low_freq_factor"` HighFrequencyFactor float32 `json:"high_freq_factor"` OriginalMaxPositionEmbeddings uint32 `json:"original_max_position_embeddings"` factors ropeFactor } `json:"rope_scaling"` RMSNormEPS float32 `json:"rms_norm_eps"` LayerNormEPS float32 `json:"layer_norm_eps"` LayerNormEpsilon float32 `json:"layer_norm_epsilon"` NormEpsilon float32 `json:"norm_epsilon"` HeadDim uint32 `json:"head_dim"` skipRepack bool } var _ ModelConverter = (*llamaModel)(nil) func (p *llamaModel) KV(t *Tokenizer) ggml.KV { kv := p.ModelParameters.KV(t) kv["general.architecture"] = "llama" kv["llama.vocab_size"] = p.VocabSize kv["llama.block_count"] = cmp.Or(p.NLayers, p.NumHiddenLayers, p.NLayer) if contextLength := cmp.Or(p.MaxPositionEmbeddings, p.NCtx); contextLength > 0 { kv["llama.context_length"] = contextLength } if embeddingLength := cmp.Or(p.HiddenSize, p.NEmbd); embeddingLength > 0 { kv["llama.embedding_length"] = cmp.Or(p.HiddenSize, p.NEmbd) } if feedForwardLength := cmp.Or(p.IntermediateSize, p.NInner); feedForwardLength > 0 { kv["llama.feed_forward_length"] = cmp.Or(p.IntermediateSize, p.NInner) } if headCount := cmp.Or(p.NumAttentionHeads, p.NHead); headCount > 0 { kv["llama.attention.head_count"] = cmp.Or(p.NumAttentionHeads, p.NHead) kv["llama.rope.dimension_count"] = p.HiddenSize / headCount } if p.HeadDim > 0 { kv["llama.attention.head_dim"] = p.HeadDim } if p.RopeTheta > 0 { kv["llama.rope.freq_base"] = p.RopeTheta } if p.RopeScaling.Type == "linear" { kv["llama.rope.scaling.type"] = p.RopeScaling.Type kv["llama.rope.scaling.factor"] = p.RopeScaling.Factor } else if p.RopeScaling.RopeType == "llama3" { dim := p.HiddenSize / p.NumAttentionHeads for i := uint32(0); i < dim; i += 2 { factor := cmp.Or(p.RopeScaling.Factor, 8.0) factorLow := cmp.Or(p.RopeScaling.LowFrequencyFactor, 1.0) factorHigh := cmp.Or(p.RopeScaling.HighFrequencyFactor, 4.0) original := cmp.Or(p.RopeScaling.OriginalMaxPositionEmbeddings, 8192) lambdaLow := float32(original) / factorLow lambdaHigh := float32(original) / factorHigh lambda := 2 * math.Pi * math.Pow(float64(p.RopeTheta), float64(i)/float64(dim)) if lambda < float64(lambdaHigh) { p.RopeScaling.factors = append(p.RopeScaling.factors, 1.0) } else if lambda > float64(lambdaLow) { p.RopeScaling.factors = append(p.RopeScaling.factors, factor) } else { smooth := (float32(original)/float32(lambda) - factorLow) / (factorHigh - factorLow) p.RopeScaling.factors = append(p.RopeScaling.factors, 1.0/((1-smooth)/factor+smooth)) } } } if p.NumKeyValueHeads > 0 { kv["llama.attention.head_count_kv"] = p.NumKeyValueHeads } if p.RMSNormEPS > 0 { kv["llama.attention.layer_norm_rms_epsilon"] = p.RMSNormEPS } if layerNormEpsilon := cmp.Or(p.LayerNormEPS, p.LayerNormEpsilon, p.NormEpsilon); layerNormEpsilon > 0 { kv["llama.attention.layer_norm_epsilon"] = layerNormEpsilon } if p.HeadDim > 0 { kv["llama.attention.key_length"] = p.HeadDim kv["llama.attention.value_length"] = p.HeadDim } return kv } func (p *llamaModel) Tensors(ts []Tensor) []*ggml.Tensor { var out []*ggml.Tensor if p.RopeScaling.factors != nil { out = append(out, &ggml.Tensor{ Name: "rope_freqs.weight", Kind: 0, Shape: []uint64{uint64(len(p.RopeScaling.factors))}, WriterTo: p.RopeScaling.factors, }) } for _, t := range ts { if strings.HasSuffix(t.Name(), "attn_q.weight") || strings.HasSuffix(t.Name(), "attn_k.weight") || strings.HasSuffix(t.Name(), "attn_q_proj.weight") || strings.HasSuffix(t.Name(), "attn_k_proj.weight") { if !p.skipRepack { t.SetRepacker(p.repack) } } out = append(out, &ggml.Tensor{ Name: t.Name(), Kind: t.Kind(), Shape: t.Shape(), WriterTo: t, }) } return out } func (p *llamaModel) Replacements() []string { return []string{ "lm_head", "output", "model.embed_tokens", "token_embd", "model.norm", "output_norm", "model.layers", "blk", "input_layernorm", "attn_norm", "self_attn.q_proj", "attn_q", "self_attn.k_proj", "attn_k", "self_attn.v_proj", "attn_v", "self_attn.o_proj", "attn_output", "mlp.gate_proj", "ffn_gate", "mlp.down_proj", "ffn_down", "mlp.up_proj", "ffn_up", "post_attention_layernorm", "ffn_norm", } } func (p *llamaModel) repack(name string, data []float32, shape []uint64) ([]float32, error) { var dims []int for _, dim := range shape { dims = append(dims, int(dim)) } var heads uint32 if strings.HasSuffix(name, "attn_q.weight") || strings.HasSuffix(name, "attn_q_proj.weight") { heads = p.NumAttentionHeads } else if strings.HasSuffix(name, "attn_k.weight") || strings.HasSuffix(name, "attn_k_proj.weight") { heads = cmp.Or(p.NumKeyValueHeads, p.NumAttentionHeads) } else { return nil, fmt.Errorf("unknown tensor for repack: %s", name) } n := tensor.New(tensor.WithShape(dims...), tensor.WithBacking(data)) if err := n.Reshape(append([]int{int(heads), 2, dims[0] / int(heads) / 2}, dims[1:]...)...); err != nil { return nil, err } if err := n.T(0, 2, 1, 3); err != nil { return nil, err } if err := n.Reshape(dims...); err != nil { return nil, err } if err := n.Transpose(); err != nil { return nil, err } ts, err := native.SelectF32(n, 1) if err != nil { return nil, err } var f32s []float32 for _, t := range ts { f32s = append(f32s, t...) } return f32s, nil }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/convert/sentencepiece/sentencepiece_model.pb.go
convert/sentencepiece/sentencepiece_model.pb.go
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.! // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.32.0 // protoc v4.25.2 // source: sentencepiece_model.proto package sentencepiece import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // Model type. only have UNIGRAM now. type TrainerSpec_ModelType int32 const ( TrainerSpec_UNIGRAM TrainerSpec_ModelType = 1 // Unigram language model with dynamic algorithm TrainerSpec_BPE TrainerSpec_ModelType = 2 // Byte Pair Encoding TrainerSpec_WORD TrainerSpec_ModelType = 3 // Delimitered by whitespace. TrainerSpec_CHAR TrainerSpec_ModelType = 4 // tokenizes into character sequence ) // Enum value maps for TrainerSpec_ModelType. var ( TrainerSpec_ModelType_name = map[int32]string{ 1: "UNIGRAM", 2: "BPE", 3: "WORD", 4: "CHAR", } TrainerSpec_ModelType_value = map[string]int32{ "UNIGRAM": 1, "BPE": 2, "WORD": 3, "CHAR": 4, } ) func (x TrainerSpec_ModelType) Enum() *TrainerSpec_ModelType { p := new(TrainerSpec_ModelType) *p = x return p } func (x TrainerSpec_ModelType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (TrainerSpec_ModelType) Descriptor() protoreflect.EnumDescriptor { return file_sentencepiece_model_proto_enumTypes[0].Descriptor() } func (TrainerSpec_ModelType) Type() protoreflect.EnumType { return &file_sentencepiece_model_proto_enumTypes[0] } func (x TrainerSpec_ModelType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *TrainerSpec_ModelType) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = TrainerSpec_ModelType(num) return nil } // Deprecated: Use TrainerSpec_ModelType.Descriptor instead. func (TrainerSpec_ModelType) EnumDescriptor() ([]byte, []int) { return file_sentencepiece_model_proto_rawDescGZIP(), []int{0, 0} } type ModelProto_SentencePiece_Type int32 const ( ModelProto_SentencePiece_NORMAL ModelProto_SentencePiece_Type = 1 // normal symbol ModelProto_SentencePiece_UNKNOWN ModelProto_SentencePiece_Type = 2 // unknown symbol. only <unk> for now. ModelProto_SentencePiece_CONTROL ModelProto_SentencePiece_Type = 3 // control symbols. </s>, <s>, <2ja> etc. ModelProto_SentencePiece_USER_DEFINED ModelProto_SentencePiece_Type = 4 // user defined symbols. // Typical usage of USER_DEFINED symbol // is placeholder. ModelProto_SentencePiece_BYTE ModelProto_SentencePiece_Type = 6 // byte symbols. Used when `byte_fallback` is true. ModelProto_SentencePiece_UNUSED ModelProto_SentencePiece_Type = 5 // this piece is not used. ) // Enum value maps for ModelProto_SentencePiece_Type. var ( ModelProto_SentencePiece_Type_name = map[int32]string{ 1: "NORMAL", 2: "UNKNOWN", 3: "CONTROL", 4: "USER_DEFINED", 6: "BYTE", 5: "UNUSED", } ModelProto_SentencePiece_Type_value = map[string]int32{ "NORMAL": 1, "UNKNOWN": 2, "CONTROL": 3, "USER_DEFINED": 4, "BYTE": 6, "UNUSED": 5, } ) func (x ModelProto_SentencePiece_Type) Enum() *ModelProto_SentencePiece_Type { p := new(ModelProto_SentencePiece_Type) *p = x return p } func (x ModelProto_SentencePiece_Type) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ModelProto_SentencePiece_Type) Descriptor() protoreflect.EnumDescriptor { return file_sentencepiece_model_proto_enumTypes[1].Descriptor() } func (ModelProto_SentencePiece_Type) Type() protoreflect.EnumType { return &file_sentencepiece_model_proto_enumTypes[1] } func (x ModelProto_SentencePiece_Type) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *ModelProto_SentencePiece_Type) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = ModelProto_SentencePiece_Type(num) return nil } // Deprecated: Use ModelProto_SentencePiece_Type.Descriptor instead. func (ModelProto_SentencePiece_Type) EnumDescriptor() ([]byte, []int) { return file_sentencepiece_model_proto_rawDescGZIP(), []int{3, 0, 0} } // TrainerSpec encodes a various parameters for SentencePiece training. // Next id: 55 type TrainerSpec struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields extensionFields protoimpl.ExtensionFields // ///////////////////////////////////////////////////////////////// // General parameters // // Input corpus files. // // Trainer accepts the following two formats: // A) Monolingual: plain text, one sentence per line. // B) Bilingual: TSV, source sentence <tab> target sentence // When bilingual data is passed, shared vocabulary model is built. // Note that the input file must be raw corpus, not a preprocessed corpus. // Trainer only loads the first `input_sentence_size` sentences specified // with this parameter. Input []string `protobuf:"bytes,1,rep,name=input" json:"input,omitempty"` // Input corpus format: // "text": one-sentence-per-line text format (default) // "tsv": sentence <tab> freq InputFormat *string `protobuf:"bytes,7,opt,name=input_format,json=inputFormat" json:"input_format,omitempty"` // Output model file prefix. // <model_prefix>.model and <model_prefix>.vocab are generated. ModelPrefix *string `protobuf:"bytes,2,opt,name=model_prefix,json=modelPrefix" json:"model_prefix,omitempty"` ModelType *TrainerSpec_ModelType `protobuf:"varint,3,opt,name=model_type,json=modelType,enum=sentencepiece.TrainerSpec_ModelType,def=1" json:"model_type,omitempty"` // Vocabulary size. 8k is the default size. VocabSize *int32 `protobuf:"varint,4,opt,name=vocab_size,json=vocabSize,def=8000" json:"vocab_size,omitempty"` // List of the languages this model can accept. // Since the model is language-agnostic, this field is used as a reference. AcceptLanguage []string `protobuf:"bytes,5,rep,name=accept_language,json=acceptLanguage" json:"accept_language,omitempty"` // Size of self-test samples, which are encoded in the model file. SelfTestSampleSize *int32 `protobuf:"varint,6,opt,name=self_test_sample_size,json=selfTestSampleSize,def=0" json:"self_test_sample_size,omitempty"` // Whether to use DP version of sentencepiece. Use it with TSV input format // (requires precomputed word tab counts to work). EnableDifferentialPrivacy *bool `protobuf:"varint,50,opt,name=enable_differential_privacy,json=enableDifferentialPrivacy,def=0" json:"enable_differential_privacy,omitempty"` // Set these parameters if you need DP version of sentencepiece. // std of noise to add. DifferentialPrivacyNoiseLevel *float32 `protobuf:"fixed32,51,opt,name=differential_privacy_noise_level,json=differentialPrivacyNoiseLevel,def=0" json:"differential_privacy_noise_level,omitempty"` // Clipping threshold to apply after adding noise. All the words with // frequency less than this value are dropped. DifferentialPrivacyClippingThreshold *uint64 `protobuf:"varint,52,opt,name=differential_privacy_clipping_threshold,json=differentialPrivacyClippingThreshold,def=0" json:"differential_privacy_clipping_threshold,omitempty"` // ///////////////////////////////////////////////////////////////// // Training parameters. // // Uses characters which cover the corpus with the ratio of `chars_coverage`. // This parameter determines the set of basic Alphabet of sentence piece. // 1.0 - `chars_coverage` characters are treated as UNK. // See also required_chars field. CharacterCoverage *float32 `protobuf:"fixed32,10,opt,name=character_coverage,json=characterCoverage,def=0.9995" json:"character_coverage,omitempty"` // Maximum size of sentences the trainer loads from `input` parameter. // Trainer simply loads the `input` files in sequence. // It is better to shuffle the input corpus randomly. InputSentenceSize *uint64 `protobuf:"varint,11,opt,name=input_sentence_size,json=inputSentenceSize,def=0" json:"input_sentence_size,omitempty"` ShuffleInputSentence *bool `protobuf:"varint,19,opt,name=shuffle_input_sentence,json=shuffleInputSentence,def=1" json:"shuffle_input_sentence,omitempty"` // Maximum size of sentences to make seed sentence pieces. // Extended suffix array is constructed to extract frequent // sub-strings from the corpus. This uses 20N working space, // where N is the size of corpus. // // Deprecated: Marked as deprecated in sentencepiece_model.proto. MiningSentenceSize *int32 `protobuf:"varint,12,opt,name=mining_sentence_size,json=miningSentenceSize" json:"mining_sentence_size,omitempty"` // Maximum size of sentences to train sentence pieces. // // Deprecated: Marked as deprecated in sentencepiece_model.proto. TrainingSentenceSize *int32 `protobuf:"varint,13,opt,name=training_sentence_size,json=trainingSentenceSize" json:"training_sentence_size,omitempty"` // The size of seed sentencepieces. // `seed_sentencepiece_size` must be larger than `vocab_size`. SeedSentencepieceSize *int32 `protobuf:"varint,14,opt,name=seed_sentencepiece_size,json=seedSentencepieceSize,def=1000000" json:"seed_sentencepiece_size,omitempty"` // In every EM sub-iterations, keeps top // `shrinking_factor` * `current sentencepieces size` with respect to // the loss of the sentence piece. This value should be smaller than 1.0. ShrinkingFactor *float32 `protobuf:"fixed32,15,opt,name=shrinking_factor,json=shrinkingFactor,def=0.75" json:"shrinking_factor,omitempty"` // The maximum sentence length in byte. The sentences with the length // larger than `max_sentence_length` is simply ignored. // Longer input tends to bring the following risks: // - Overflow during EM training (unigram language model only) // - Performance drop because of O(n log n) cost in BPE. MaxSentenceLength *int32 `protobuf:"varint,18,opt,name=max_sentence_length,json=maxSentenceLength,def=4192" json:"max_sentence_length,omitempty"` // Number of threads in the training. NumThreads *int32 `protobuf:"varint,16,opt,name=num_threads,json=numThreads,def=16" json:"num_threads,omitempty"` // Number of EM sub iterations. NumSubIterations *int32 `protobuf:"varint,17,opt,name=num_sub_iterations,json=numSubIterations,def=2" json:"num_sub_iterations,omitempty"` // ///////////////////////////////////////////////////////////////// // SentencePiece parameters which control the shapes of sentence piece. // // Maximum length of sentencepiece. MaxSentencepieceLength *int32 `protobuf:"varint,20,opt,name=max_sentencepiece_length,json=maxSentencepieceLength,def=16" json:"max_sentencepiece_length,omitempty"` // Uses Unicode script to split sentence pieces. // When `split_by_unicode_script` is true, we do not allow sentence piece to // include multiple Unicode scripts, e.g. "F1" is not a valid piece. // Exception: CJ characters (Hiragana/Katakana/Han) are all handled // as one script type, since Japanese word can consist of multiple scripts. // This exception is always applied regardless of the accept-language // parameter. SplitByUnicodeScript *bool `protobuf:"varint,21,opt,name=split_by_unicode_script,json=splitByUnicodeScript,def=1" json:"split_by_unicode_script,omitempty"` // When `split_by_number` is true, put a boundary between number and // non-number transition. If we want to treat "F1" is one token, set this flag // to be false. SplitByNumber *bool `protobuf:"varint,23,opt,name=split_by_number,json=splitByNumber,def=1" json:"split_by_number,omitempty"` // Use a white space to split sentence pieces. // When `split_by_whitespace` is false, we may have the piece containing // a white space in the middle. e.g., "in_the". SplitByWhitespace *bool `protobuf:"varint,22,opt,name=split_by_whitespace,json=splitByWhitespace,def=1" json:"split_by_whitespace,omitempty"` // Adds whitespace symbol (_) as a suffix instead of prefix. e.g., _hello => // hello_. When `treat_whitespace_as_suffix` is true, // NormalizerSpec::add_dummy_prefix will add the dummy whitespace to the end // of sentence. TreatWhitespaceAsSuffix *bool `protobuf:"varint,24,opt,name=treat_whitespace_as_suffix,json=treatWhitespaceAsSuffix,def=0" json:"treat_whitespace_as_suffix,omitempty"` // Allows pieces that only contain whitespaces instead of appearing only as // prefix or suffix of other pieces. AllowWhitespaceOnlyPieces *bool `protobuf:"varint,26,opt,name=allow_whitespace_only_pieces,json=allowWhitespaceOnlyPieces,def=0" json:"allow_whitespace_only_pieces,omitempty"` // Split all digits (0-9) into separate pieces. SplitDigits *bool `protobuf:"varint,25,opt,name=split_digits,json=splitDigits,def=0" json:"split_digits,omitempty"` // Defines the pre-tokenization delimiter. // When specified, no pieces crossing this delimiter is not included // in the vocab. Then the delimiter string is virtually ignored // during the training. This field can allows constraints on the vocabulary // selection. Note that this field is available on unigram mode. PretokenizationDelimiter *string `protobuf:"bytes,53,opt,name=pretokenization_delimiter,json=pretokenizationDelimiter,def=" json:"pretokenization_delimiter,omitempty"` // ///////////////////////////////////////////////////////////////// // Vocabulary management // // Defines control symbols used as an indicator to // change the behavior of the decoder. <s> and </s> are pre-defined. // We can use this field to encode various meta information, // including language indicator in multilingual model. // These symbols are not visible to users, but visible to // the decoder. Note that when the input sentence contains control symbols, // they are not treated as one token, but segmented into normal pieces. // Control symbols must be inserted independently from the segmentation. ControlSymbols []string `protobuf:"bytes,30,rep,name=control_symbols,json=controlSymbols" json:"control_symbols,omitempty"` // Defines user defined symbols. // These symbols are added with extremely high score // so they are always treated as one unique symbol in any context. // Typical usage of user_defined_symbols is placeholder for named entities. UserDefinedSymbols []string `protobuf:"bytes,31,rep,name=user_defined_symbols,json=userDefinedSymbols" json:"user_defined_symbols,omitempty"` // Defines required characters. Each UTF8 character in this string is included // in the character set regardless of character_coverage value. Unlike // user_defined_symbols, these characters have scores based on the frequency // on input sentences, and the model can form subwords using characters // in this field. RequiredChars *string `protobuf:"bytes,36,opt,name=required_chars,json=requiredChars" json:"required_chars,omitempty"` // Decomposes unknown pieces into UTF-8 bytes. ByteFallback *bool `protobuf:"varint,35,opt,name=byte_fallback,json=byteFallback,def=0" json:"byte_fallback,omitempty"` // When creating the vocabulary file, defines whether or not to additionally // output the score for each piece. VocabularyOutputPieceScore *bool `protobuf:"varint,32,opt,name=vocabulary_output_piece_score,json=vocabularyOutputPieceScore,def=1" json:"vocabulary_output_piece_score,omitempty"` // `vocab_size` is treated as hard limit. Crash if // the model can not produce the vocab of size `vocab_size`, // When `hard_vocab_limit` is false, vocab_size is treated // as soft limit. Note that when model_type=char, // always assumes hard_vocab_limit = false. HardVocabLimit *bool `protobuf:"varint,33,opt,name=hard_vocab_limit,json=hardVocabLimit,def=1" json:"hard_vocab_limit,omitempty"` // use all symbols for vocab extraction. This flag is valid // if model type is either CHAR or WORD UseAllVocab *bool `protobuf:"varint,34,opt,name=use_all_vocab,json=useAllVocab,def=0" json:"use_all_vocab,omitempty"` // ///////////////////////////////////////////////////////////////// // Reserved special meta tokens. // * -1 is not used. // * unk_id must not be -1. // Id must start with 0 and be contiguous. UnkId *int32 `protobuf:"varint,40,opt,name=unk_id,json=unkId,def=0" json:"unk_id,omitempty"` // <unk> BosId *int32 `protobuf:"varint,41,opt,name=bos_id,json=bosId,def=1" json:"bos_id,omitempty"` // <s> EosId *int32 `protobuf:"varint,42,opt,name=eos_id,json=eosId,def=2" json:"eos_id,omitempty"` // </s> PadId *int32 `protobuf:"varint,43,opt,name=pad_id,json=padId,def=-1" json:"pad_id,omitempty"` // <pad> (padding) UnkPiece *string `protobuf:"bytes,45,opt,name=unk_piece,json=unkPiece,def=<unk>" json:"unk_piece,omitempty"` BosPiece *string `protobuf:"bytes,46,opt,name=bos_piece,json=bosPiece,def=<s>" json:"bos_piece,omitempty"` EosPiece *string `protobuf:"bytes,47,opt,name=eos_piece,json=eosPiece,def=</s>" json:"eos_piece,omitempty"` PadPiece *string `protobuf:"bytes,48,opt,name=pad_piece,json=padPiece,def=<pad>" json:"pad_piece,omitempty"` // Encodes <unk> into U+2047 (DOUBLE QUESTION MARK), // since this character can be useful both for user and // developer. We can easily figure out that <unk> is emitted. UnkSurface *string `protobuf:"bytes,44,opt,name=unk_surface,json=unkSurface,def= ⁇ " json:"unk_surface,omitempty"` // Increase bit depth to allow unigram model training on large // (>10M sentences) corpora. A Side-effect of enabling this flag // is increased memory usage. TrainExtremelyLargeCorpus *bool `protobuf:"varint,49,opt,name=train_extremely_large_corpus,json=trainExtremelyLargeCorpus,def=0" json:"train_extremely_large_corpus,omitempty"` // Path to a seed sentencepieces file, with one tab-separated // seed sentencepiece <tab> frequency per line. SeedSentencepiecesFile *string `protobuf:"bytes,54,opt,name=seed_sentencepieces_file,json=seedSentencepiecesFile,def=" json:"seed_sentencepieces_file,omitempty"` } // Default values for TrainerSpec fields. const ( Default_TrainerSpec_ModelType = TrainerSpec_UNIGRAM Default_TrainerSpec_VocabSize = int32(8000) Default_TrainerSpec_SelfTestSampleSize = int32(0) Default_TrainerSpec_EnableDifferentialPrivacy = bool(false) Default_TrainerSpec_DifferentialPrivacyNoiseLevel = float32(0) Default_TrainerSpec_DifferentialPrivacyClippingThreshold = uint64(0) Default_TrainerSpec_CharacterCoverage = float32(0.9994999766349792) Default_TrainerSpec_InputSentenceSize = uint64(0) Default_TrainerSpec_ShuffleInputSentence = bool(true) Default_TrainerSpec_SeedSentencepieceSize = int32(1000000) Default_TrainerSpec_ShrinkingFactor = float32(0.75) Default_TrainerSpec_MaxSentenceLength = int32(4192) Default_TrainerSpec_NumThreads = int32(16) Default_TrainerSpec_NumSubIterations = int32(2) Default_TrainerSpec_MaxSentencepieceLength = int32(16) Default_TrainerSpec_SplitByUnicodeScript = bool(true) Default_TrainerSpec_SplitByNumber = bool(true) Default_TrainerSpec_SplitByWhitespace = bool(true) Default_TrainerSpec_TreatWhitespaceAsSuffix = bool(false) Default_TrainerSpec_AllowWhitespaceOnlyPieces = bool(false) Default_TrainerSpec_SplitDigits = bool(false) Default_TrainerSpec_PretokenizationDelimiter = string("") Default_TrainerSpec_ByteFallback = bool(false) Default_TrainerSpec_VocabularyOutputPieceScore = bool(true) Default_TrainerSpec_HardVocabLimit = bool(true) Default_TrainerSpec_UseAllVocab = bool(false) Default_TrainerSpec_UnkId = int32(0) Default_TrainerSpec_BosId = int32(1) Default_TrainerSpec_EosId = int32(2) Default_TrainerSpec_PadId = int32(-1) Default_TrainerSpec_UnkPiece = string("<unk>") Default_TrainerSpec_BosPiece = string("<s>") Default_TrainerSpec_EosPiece = string("</s>") Default_TrainerSpec_PadPiece = string("<pad>") Default_TrainerSpec_UnkSurface = string(" ⁇ ") Default_TrainerSpec_TrainExtremelyLargeCorpus = bool(false) Default_TrainerSpec_SeedSentencepiecesFile = string("") ) func (x *TrainerSpec) Reset() { *x = TrainerSpec{} if protoimpl.UnsafeEnabled { mi := &file_sentencepiece_model_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *TrainerSpec) String() string { return protoimpl.X.MessageStringOf(x) } func (*TrainerSpec) ProtoMessage() {} func (x *TrainerSpec) ProtoReflect() protoreflect.Message { mi := &file_sentencepiece_model_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use TrainerSpec.ProtoReflect.Descriptor instead. func (*TrainerSpec) Descriptor() ([]byte, []int) { return file_sentencepiece_model_proto_rawDescGZIP(), []int{0} } func (x *TrainerSpec) GetInput() []string { if x != nil { return x.Input } return nil } func (x *TrainerSpec) GetInputFormat() string { if x != nil && x.InputFormat != nil { return *x.InputFormat } return "" } func (x *TrainerSpec) GetModelPrefix() string { if x != nil && x.ModelPrefix != nil { return *x.ModelPrefix } return "" } func (x *TrainerSpec) GetModelType() TrainerSpec_ModelType { if x != nil && x.ModelType != nil { return *x.ModelType } return Default_TrainerSpec_ModelType } func (x *TrainerSpec) GetVocabSize() int32 { if x != nil && x.VocabSize != nil { return *x.VocabSize } return Default_TrainerSpec_VocabSize } func (x *TrainerSpec) GetAcceptLanguage() []string { if x != nil { return x.AcceptLanguage } return nil } func (x *TrainerSpec) GetSelfTestSampleSize() int32 { if x != nil && x.SelfTestSampleSize != nil { return *x.SelfTestSampleSize } return Default_TrainerSpec_SelfTestSampleSize } func (x *TrainerSpec) GetEnableDifferentialPrivacy() bool { if x != nil && x.EnableDifferentialPrivacy != nil { return *x.EnableDifferentialPrivacy } return Default_TrainerSpec_EnableDifferentialPrivacy } func (x *TrainerSpec) GetDifferentialPrivacyNoiseLevel() float32 { if x != nil && x.DifferentialPrivacyNoiseLevel != nil { return *x.DifferentialPrivacyNoiseLevel } return Default_TrainerSpec_DifferentialPrivacyNoiseLevel } func (x *TrainerSpec) GetDifferentialPrivacyClippingThreshold() uint64 { if x != nil && x.DifferentialPrivacyClippingThreshold != nil { return *x.DifferentialPrivacyClippingThreshold } return Default_TrainerSpec_DifferentialPrivacyClippingThreshold } func (x *TrainerSpec) GetCharacterCoverage() float32 { if x != nil && x.CharacterCoverage != nil { return *x.CharacterCoverage } return Default_TrainerSpec_CharacterCoverage } func (x *TrainerSpec) GetInputSentenceSize() uint64 { if x != nil && x.InputSentenceSize != nil { return *x.InputSentenceSize } return Default_TrainerSpec_InputSentenceSize } func (x *TrainerSpec) GetShuffleInputSentence() bool { if x != nil && x.ShuffleInputSentence != nil { return *x.ShuffleInputSentence } return Default_TrainerSpec_ShuffleInputSentence } // Deprecated: Marked as deprecated in sentencepiece_model.proto. func (x *TrainerSpec) GetMiningSentenceSize() int32 { if x != nil && x.MiningSentenceSize != nil { return *x.MiningSentenceSize } return 0 } // Deprecated: Marked as deprecated in sentencepiece_model.proto. func (x *TrainerSpec) GetTrainingSentenceSize() int32 { if x != nil && x.TrainingSentenceSize != nil { return *x.TrainingSentenceSize } return 0 } func (x *TrainerSpec) GetSeedSentencepieceSize() int32 { if x != nil && x.SeedSentencepieceSize != nil { return *x.SeedSentencepieceSize } return Default_TrainerSpec_SeedSentencepieceSize } func (x *TrainerSpec) GetShrinkingFactor() float32 { if x != nil && x.ShrinkingFactor != nil { return *x.ShrinkingFactor } return Default_TrainerSpec_ShrinkingFactor } func (x *TrainerSpec) GetMaxSentenceLength() int32 { if x != nil && x.MaxSentenceLength != nil { return *x.MaxSentenceLength } return Default_TrainerSpec_MaxSentenceLength } func (x *TrainerSpec) GetNumThreads() int32 { if x != nil && x.NumThreads != nil { return *x.NumThreads } return Default_TrainerSpec_NumThreads } func (x *TrainerSpec) GetNumSubIterations() int32 { if x != nil && x.NumSubIterations != nil { return *x.NumSubIterations } return Default_TrainerSpec_NumSubIterations } func (x *TrainerSpec) GetMaxSentencepieceLength() int32 { if x != nil && x.MaxSentencepieceLength != nil { return *x.MaxSentencepieceLength } return Default_TrainerSpec_MaxSentencepieceLength } func (x *TrainerSpec) GetSplitByUnicodeScript() bool { if x != nil && x.SplitByUnicodeScript != nil { return *x.SplitByUnicodeScript } return Default_TrainerSpec_SplitByUnicodeScript } func (x *TrainerSpec) GetSplitByNumber() bool { if x != nil && x.SplitByNumber != nil { return *x.SplitByNumber } return Default_TrainerSpec_SplitByNumber } func (x *TrainerSpec) GetSplitByWhitespace() bool { if x != nil && x.SplitByWhitespace != nil { return *x.SplitByWhitespace } return Default_TrainerSpec_SplitByWhitespace } func (x *TrainerSpec) GetTreatWhitespaceAsSuffix() bool { if x != nil && x.TreatWhitespaceAsSuffix != nil { return *x.TreatWhitespaceAsSuffix } return Default_TrainerSpec_TreatWhitespaceAsSuffix } func (x *TrainerSpec) GetAllowWhitespaceOnlyPieces() bool { if x != nil && x.AllowWhitespaceOnlyPieces != nil { return *x.AllowWhitespaceOnlyPieces } return Default_TrainerSpec_AllowWhitespaceOnlyPieces } func (x *TrainerSpec) GetSplitDigits() bool { if x != nil && x.SplitDigits != nil { return *x.SplitDigits } return Default_TrainerSpec_SplitDigits } func (x *TrainerSpec) GetPretokenizationDelimiter() string { if x != nil && x.PretokenizationDelimiter != nil { return *x.PretokenizationDelimiter } return Default_TrainerSpec_PretokenizationDelimiter } func (x *TrainerSpec) GetControlSymbols() []string { if x != nil { return x.ControlSymbols } return nil } func (x *TrainerSpec) GetUserDefinedSymbols() []string { if x != nil { return x.UserDefinedSymbols } return nil } func (x *TrainerSpec) GetRequiredChars() string { if x != nil && x.RequiredChars != nil { return *x.RequiredChars } return "" } func (x *TrainerSpec) GetByteFallback() bool { if x != nil && x.ByteFallback != nil { return *x.ByteFallback } return Default_TrainerSpec_ByteFallback } func (x *TrainerSpec) GetVocabularyOutputPieceScore() bool { if x != nil && x.VocabularyOutputPieceScore != nil { return *x.VocabularyOutputPieceScore } return Default_TrainerSpec_VocabularyOutputPieceScore } func (x *TrainerSpec) GetHardVocabLimit() bool { if x != nil && x.HardVocabLimit != nil { return *x.HardVocabLimit } return Default_TrainerSpec_HardVocabLimit } func (x *TrainerSpec) GetUseAllVocab() bool { if x != nil && x.UseAllVocab != nil { return *x.UseAllVocab } return Default_TrainerSpec_UseAllVocab } func (x *TrainerSpec) GetUnkId() int32 { if x != nil && x.UnkId != nil { return *x.UnkId } return Default_TrainerSpec_UnkId } func (x *TrainerSpec) GetBosId() int32 { if x != nil && x.BosId != nil { return *x.BosId } return Default_TrainerSpec_BosId } func (x *TrainerSpec) GetEosId() int32 { if x != nil && x.EosId != nil { return *x.EosId } return Default_TrainerSpec_EosId } func (x *TrainerSpec) GetPadId() int32 { if x != nil && x.PadId != nil { return *x.PadId } return Default_TrainerSpec_PadId } func (x *TrainerSpec) GetUnkPiece() string { if x != nil && x.UnkPiece != nil { return *x.UnkPiece } return Default_TrainerSpec_UnkPiece } func (x *TrainerSpec) GetBosPiece() string { if x != nil && x.BosPiece != nil { return *x.BosPiece } return Default_TrainerSpec_BosPiece } func (x *TrainerSpec) GetEosPiece() string { if x != nil && x.EosPiece != nil { return *x.EosPiece } return Default_TrainerSpec_EosPiece } func (x *TrainerSpec) GetPadPiece() string { if x != nil && x.PadPiece != nil { return *x.PadPiece } return Default_TrainerSpec_PadPiece } func (x *TrainerSpec) GetUnkSurface() string { if x != nil && x.UnkSurface != nil { return *x.UnkSurface } return Default_TrainerSpec_UnkSurface } func (x *TrainerSpec) GetTrainExtremelyLargeCorpus() bool { if x != nil && x.TrainExtremelyLargeCorpus != nil { return *x.TrainExtremelyLargeCorpus } return Default_TrainerSpec_TrainExtremelyLargeCorpus } func (x *TrainerSpec) GetSeedSentencepiecesFile() string { if x != nil && x.SeedSentencepiecesFile != nil { return *x.SeedSentencepiecesFile } return Default_TrainerSpec_SeedSentencepiecesFile } // NormalizerSpec encodes a various parameters for string normalizaiton type NormalizerSpec struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields extensionFields protoimpl.ExtensionFields // name of normalization rule. Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` // Pre-compiled normalization rule created by // Builder::GetPrecompiledCharsMap() or Builder::CompileCharsMap() method. // Usually this field is set by Builder::GetNormalizerSpec() method. PrecompiledCharsmap []byte `protobuf:"bytes,2,opt,name=precompiled_charsmap,json=precompiledCharsmap" json:"precompiled_charsmap,omitempty"` // Adds dummy whitespace at the beginning of text in order to // treat "world" in "world" and "hello world" in the same way. AddDummyPrefix *bool `protobuf:"varint,3,opt,name=add_dummy_prefix,json=addDummyPrefix,def=1" json:"add_dummy_prefix,omitempty"` // Removes leading, trailing, and duplicate internal whitespace. RemoveExtraWhitespaces *bool `protobuf:"varint,4,opt,name=remove_extra_whitespaces,json=removeExtraWhitespaces,def=1" json:"remove_extra_whitespaces,omitempty"` // Replaces whitespace with meta symbol. // This field must be true to train sentence piece model. EscapeWhitespaces *bool `protobuf:"varint,5,opt,name=escape_whitespaces,json=escapeWhitespaces,def=1" json:"escape_whitespaces,omitempty"` // Custom normalization rule file in TSV format. // https://github.com/google/sentencepiece/blob/master/doc/normalization.md // This field is only used in SentencePieceTrainer::Train() method, which // compiles the rule into the binary rule stored in `precompiled_charsmap`. NormalizationRuleTsv *string `protobuf:"bytes,6,opt,name=normalization_rule_tsv,json=normalizationRuleTsv" json:"normalization_rule_tsv,omitempty"` } // Default values for NormalizerSpec fields. const ( Default_NormalizerSpec_AddDummyPrefix = bool(true) Default_NormalizerSpec_RemoveExtraWhitespaces = bool(true) Default_NormalizerSpec_EscapeWhitespaces = bool(true) ) func (x *NormalizerSpec) Reset() { *x = NormalizerSpec{} if protoimpl.UnsafeEnabled { mi := &file_sentencepiece_model_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *NormalizerSpec) String() string { return protoimpl.X.MessageStringOf(x) } func (*NormalizerSpec) ProtoMessage() {} func (x *NormalizerSpec) ProtoReflect() protoreflect.Message { mi := &file_sentencepiece_model_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil {
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
true
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/sample/samplers.go
sample/samplers.go
package sample import ( "errors" "math" "math/rand/v2" "slices" "github.com/ollama/ollama/llama" "github.com/ollama/ollama/model" ) // token represents information about a single token during sampling type token struct { id int32 // The token's unique identifier value float32 // The raw logit or probability from the model } type Sampler struct { rng *rand.Rand topK int topP float32 minP float32 temperature float32 grammar *GrammarSampler } func (s *Sampler) Sample(logits []float32) (int32, error) { if len(logits) == 0 { return -1, errors.New("sample: no logits provided to sample") } tokens := make([]token, len(logits)) for i := range logits { tokens[i].id = int32(i) tokens[i].value = logits[i] } t, err := s.sample(tokens) if err != nil { return -1, err } if s.grammar != nil { // optimization: first check if the max logit is accepted by the grammar // if the max logit is rejected, apply the grammar to all logits (slower) top := []token{t} s.grammar.Apply(top) if !math.IsInf(float64(top[0].value), -1) { s.grammar.Accept(top[0].id) return top[0].id, nil } // since .sample has side effects of modifying the tokens // we need to reset them before applying the grammar and // sampling again for i := range logits { tokens[i].id = int32(i) tokens[i].value = logits[i] } s.grammar.Apply(tokens) t, err = s.sample(tokens) if err != nil { return -1, err } s.grammar.Accept(t.id) } return t.id, nil } // greedy returns the highest probability token from the tokens func greedy(tokens []token) token { max := tokens[0] for i := 1; i < len(tokens); i++ { if tokens[i].value > max.value { max = tokens[i] } } return max } // sample returns the highest probability token from the tokens // given sampler parameters. It also has side effects of modifying the tokens func (s *Sampler) sample(tokens []token) (token, error) { if s.temperature == 0 { return greedy(tokens), nil } // topK also sorts the tokens in descending order of logits tokens = topK(tokens, s.topK) // scale and normalize the tokens in place temperature(tokens, s.temperature) softmax(tokens) tokens = topP(tokens, s.topP) tokens = minP(tokens, s.minP) var r float32 if s.rng != nil { r = s.rng.Float32() } else { r = rand.Float32() } // Calculate cumulative sum of probabilities var sum float32 for i := range tokens { sum += tokens[i].value tokens[i].value = sum } r *= tokens[len(tokens)-1].value idx, _ := slices.BinarySearchFunc(tokens, r, func(token token, target float32) int { if token.value < target { return -1 } return 1 }) if math.IsNaN(float64(sum)) { return token{}, errors.New("sample: logits sum to NaN, check model output") } return tokens[idx], nil } // TODO(parthsareen): update sampler interface to use json unmarshal https://github.com/ollama/ollama/issues/9278 func NewSampler(temperature float32, topK int, topP float32, minP float32, seed int, grammar *GrammarSampler) Sampler { var rng *rand.Rand if seed != -1 { // PCG requires two parameters: sequence and stream // Use original seed for sequence sequence := uint64(seed) // Use golden ratio hash to generate statistically independent seeds rng = rand.New(rand.NewPCG(sequence, sequence^0x9E3779B9)) } if temperature < 0.0 { temperature = 0.0 } if topP < 0.0 { topP = 0.0 } if topP >= 1.0 { topP = 1.0 } if minP < 0.0 { minP = 0.0 } if minP >= 1.0 { minP = 1.0 } return Sampler{ rng: rng, topK: topK, topP: topP, minP: minP, temperature: temperature, grammar: grammar, } } type GrammarSampler struct { grammar *llama.Grammar } func NewGrammarSampler(model model.TextProcessor, grammarStr string) (*GrammarSampler, error) { vocabIds := make([]uint32, len(model.Vocabulary().Values)) pieces := make([]string, len(model.Vocabulary().Values)) for i := range model.Vocabulary().Values { pieces[i], _ = model.Decode([]int32{int32(i)}) vocabIds[i] = uint32(i) } grammar := llama.NewGrammar(grammarStr, vocabIds, pieces, model.Vocabulary().EOS) if grammar == nil { return nil, errors.New("sample: failed to initialize grammar") } return &GrammarSampler{grammar: grammar}, nil } func (g *GrammarSampler) Apply(tokens []token) { tds := make([]llama.TokenData, len(tokens)) for i, token := range tokens { tds[i].ID = token.id tds[i].Logit = token.value } g.grammar.Apply(tds) for i := range tokens { tokens[i].value = tds[i].Logit } } func (g *GrammarSampler) Accept(token int32) { g.grammar.Accept(token) } func (g *GrammarSampler) Free() { g.grammar.Free() }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/sample/samplers_benchmark_test.go
sample/samplers_benchmark_test.go
package sample import ( "fmt" "math/rand" "testing" ) func BenchmarkWeightedSampler(b *testing.B) { sizes := []int{10, 100, 1000, 10000} for _, size := range sizes { b.Run(fmt.Sprintf("Size %d", size), func(b *testing.B) { logits := make([]float32, size) for i := range logits { logits[i] = float32(rand.Float64()*10 - 5) } sampler := NewSampler(0.8, 0, 0, 0, 42, nil) b.ResetTimer() for b.Loop() { sampler.Sample(logits) } }) } configs := []struct { name string temperature float32 topK int topP float32 minP float32 seed int }{ {"Greedy", 0, -1, 0, 0, -1}, {"Temperature", 0.8, -1, 0, 0, -1}, {"TopK", 0.8, 50, 0, 0, -1}, {"TopP", 0.8, -1, 0.9, 0, -1}, {"MinP", 0.8, -1, 0, 0.05, -1}, {"WithSeed", 0.8, 50, 0, 0, 42}, } // Fixed size for common vocab size size := 128000 logits := make([]float32, size) for i := range logits { logits[i] = float32(rand.Float64()*10 - 5) } for _, tc := range configs { b.Run("Config"+tc.name, func(b *testing.B) { sampler := NewSampler(tc.temperature, tc.topK, tc.topP, tc.minP, tc.seed, nil) sampler.Sample(logits) b.ResetTimer() for b.Loop() { sampler.Sample(logits) } }) } // Test with combined transforms separately - topK influences performance greatly b.Run("TransformCombined", func(b *testing.B) { sampler := NewSampler(0.8, 50, 0.9, 0.05, 42, nil) b.ResetTimer() for b.Loop() { sampler.Sample(logits) } }) } func BenchmarkGreedySampler(b *testing.B) { sizes := []int{10, 100, 1000, 10000, 100000} for _, size := range sizes { b.Run(fmt.Sprintf("Size %d", size), func(b *testing.B) { logits := make([]float32, size) for i := range logits { logits[i] = float32(rand.Float64()*10 - 5) } sampler := NewSampler(0, -1, 0, 0, -1, nil) b.ResetTimer() for b.Loop() { sampler.Sample(logits) } }) } }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/sample/transforms.go
sample/transforms.go
package sample import ( "container/heap" "math" "slices" ) // tokenHeap implements heap.Interface and holds tokens as a min-heap to track k largest elements type tokenHeap []token func (h tokenHeap) Len() int { return len(h) } func (h tokenHeap) Less(i, j int) bool { return h[i].value < h[j].value } func (h tokenHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *tokenHeap) Push(x any) { *h = append(*h, x.(token)) } func (h *tokenHeap) Pop() any { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } // temperature applies scaling to the logits func temperature(ts []token, temp float32) { // Ensure temperature clipping near 0 to avoid numerical instability temp = max(temp, 1e-7) for i := range ts { ts[i].value = ts[i].value / temp } } // softmax applies normalization to the logits func softmax(ts []token) { // Find max logit for numerical stability maxLogit := float32(math.Inf(-1)) for _, t := range ts { if t.value > maxLogit { maxLogit = t.value } } // Compute exp(x - max) var sum float32 for i, v := range ts { ts[i].value = float32(math.Exp(float64(v.value - maxLogit))) sum += ts[i].value } // exp(x - max) / sum(exp(x - max)) for i := range ts { ts[i].value /= sum } } // topK limits the number of tokens considered to the k highest logits func topK(ts []token, k int) []token { if k >= len(ts) || k <= 0 { slices.SortFunc(ts, func(a, b token) int { switch { case a.value < b.value: return 1 case a.value > b.value: return -1 default: return 0 } }) return ts } // Initialize min-heap with first k elements h := make(tokenHeap, k) copy(h, ts[:k]) heap.Init(&h) // Process remaining elements for i := k; i < len(ts); i++ { if ts[i].value > h[0].value { heap.Pop(&h) heap.Push(&h, ts[i]) } } // Convert heap to sorted slice in descending order result := make([]token, len(h)) for i := k - 1; i >= 0; i-- { result[i] = heap.Pop(&h).(token) } return result } // topP limits tokens to those with cumulative probability p // requires ts to be sorted in descending order of probabilities func topP(ts []token, p float32) []token { if p == 1.0 { return ts } // Find cutoff index where cumulative sum exceeds p var sum float32 for i, t := range ts { sum += t.value if sum > float32(p) { return ts[:i+1] } } return ts } // minP filters tokens with probabilities >= p * max_prob // requires ts to be sorted in descending order of probabilities func minP(ts []token, p float32) []token { maxProb := ts[0].value threshold := maxProb * p for i, t := range ts { if t.value < threshold { return ts[:i] } } return ts }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/sample/transforms_test.go
sample/transforms_test.go
package sample import ( "math" "math/rand/v2" "testing" ) // Helper to convert float32 slice to logit slice func toTokens(values []float32) []token { tokens := make([]token, len(values)) for i, v := range values { tokens[i] = token{ id: int32(i), value: v, } } return tokens } // Helper to compare logit slices func compareLogits(t *testing.T, name string, want []float32, got []token) { t.Helper() if len(want) != len(got) { t.Errorf("%s: length mismatch: want %d, got %d", name, len(want), len(got)) return } for i := range want { if math.Abs(float64(got[i].value-want[i])) > 1e-6 { t.Errorf("%s: index %d: want %f, got %f", name, i, want[i], got[i].value) } } } func TestTemperature(t *testing.T) { input := []float32{1.0, 4.0, -2.0, 0.0} tokens := toTokens(input) temperature(tokens, 0.5) want := []float32{2.0, 8.0, -4.0, 0.0} compareLogits(t, "temperature(0.5)", want, tokens) input = []float32{1.0, 4.0, -2.0, 0.0} tokens = toTokens(input) temperature(tokens, 1.0) want = []float32{1.0, 4.0, -2.0, 0.0} compareLogits(t, "temperature(1)", want, tokens) input = []float32{1.0, 4.0, -2.0, 0.0} tokens = toTokens(input) temperature(tokens, 0.0) want = []float32{1e7, 4e7, -2e7, 0.0} compareLogits(t, "temperature(0)", want, tokens) } func TestSoftmax(t *testing.T) { tests := []struct { name string input []float32 expected []float32 }{ { name: "correctness softmax", input: []float32{1, -2, 3, 0}, expected: []float32{0.113550, 0.005653, 0.839024, 0.041773}, }, { name: "normal distribution", input: []float32{0.026986899, 0.043722924, 0.036774673, 0.27755088, 0.0046718004, 0.08582123, 0.20409796, 0.00412893, 0.15720603, 0.045046154, 0.0030491839, 0.01681367}, }, { name: "single value", input: []float32{1.0}, }, { name: "identical values", input: []float32{0.9, 0.9, 0.9}, }, { name: "large values", input: []float32{1000.0, 2000.0, 3000.0}, }, { name: "small values", input: []float32{1e-6, 2e-6, 3e-6}, }, { name: "negative values", input: []float32{-1.0, -2.0, -3.0}, }, { name: "mixed values", input: []float32{-100.0, 0.0, 100.0}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tokens := toTokens(tt.input) softmax(tokens) if tt.expected != nil { compareLogits(t, tt.name, tt.expected, tokens) return } // Check probabilities sum to 1 var sum float32 for _, token := range tokens { sum += token.value if token.value < 0 || token.value > 1 { t.Errorf("probability out of range [0,1]: got %f", token.value) } } if math.Abs(float64(sum-1.0)) > 1e-6 { t.Errorf("probabilities don't sum to 1: got %f", sum) } }) } } func TestTopK(t *testing.T) { input := []float32{0.026986899, 0.043722924, 0.036774673, 0.27755088, 0.0046718004, 0.08582123, 0.20409796, 0.00412893, 0.15720603, 0.045046154, 0.0030491839, 0.01681367} tokens := toTokens(input) tokens = topK(tokens, 5) if len(tokens) != 5 { t.Errorf("topK(5): wrong length: want 5, got %d", len(tokens)) } want := []float32{0.27755088, 0.20409796, 0.15720603, 0.08582123, 0.045046154} compareLogits(t, "topK(3)", want, tokens) tokens = toTokens(input) tokens = topK(tokens, 20) if len(tokens) != len(input) { t.Errorf("topK(20): wrong length: want %d, got %d", len(input), len(tokens)) } input = []float32{0.026986899, 0.043722924, 0.036774673, 0.27755088, 0.0046718004, 0.08582123, 0.20409796, 0.00412893, 0.15720603, 0.045046154, 0.0030491839, 0.01681367} want = []float32{0.27755088, 0.20409796, 0.15720603, 0.08582123, 0.045046154, 0.043722924, 0.036774673, 0.026986899, 0.01681367, 0.0046718004, 0.00412893, 0.0030491839} tokens = toTokens(input) tokens = topK(tokens, -1) if len(tokens) != len(input) { t.Errorf("topK(-1): wrong length: want %d, got %d", len(input), len(tokens)) } compareLogits(t, "topK(-1)", want, tokens) input = []float32{0.026986899, 0.043722924, 0.036774673, 0.27755088, 0.0046718004, 0.08582123, 0.20409796, 0.00412893, 0.15720603, 0.045046154, 0.0030491839, 0.01681367} want = []float32{0.27755088, 0.20409796, 0.15720603, 0.08582123, 0.045046154, 0.043722924, 0.036774673, 0.026986899, 0.01681367, 0.0046718004, 0.00412893, 0.0030491839} tokens = toTokens(input) tokens = topK(tokens, 0) if len(tokens) != len(input) { t.Errorf("topK(-1): wrong length: want %d, got %d", len(input), len(tokens)) } compareLogits(t, "topK(-1)", want, tokens) input = []float32{-1e7, -2e7, -3e7, -4e7} tokens = toTokens(input) tokens = topK(tokens, 1) if len(tokens) < 1 { t.Error("topK should keep at least one token") } } func TestTopP(t *testing.T) { input := []float32{-3, -2, -1, 0, 1, 2, 4} tokens := toTokens(input) // First apply temperature and softmax to get probabilities softmax(tokens) tokens = topK(tokens, 20) // Test with very high p value got := topP(tokens, 1.0) // Should keep all tokens since p is 1 if len(got) != len(input) { t.Errorf("topP(1.0): should keep all tokens, got %d, want %d", len(got), len(input)) } // Test with normal p value got = topP(tokens, 0.95) if len(got) > 3 { t.Errorf("topP(0.95): kept too many tokens: got %d", len(tokens)) t.Logf("got: %v", got) } // Test edge case - ensure at least one token remains input = []float32{-1e6, -1e6, -1e7} tokens = toTokens(input) tokens = topK(tokens, 20) softmax(tokens) got = topP(tokens, 0.0) if len(got) < 1 { t.Error("topP should keep at least one token") } // Test with zero p value got = topP(tokens, 0.0) // Should keep only the highest probability token if len(got) != 1 { t.Errorf("topP(0.0): should keep only one token, got %d", len(got)) t.Logf("got: %v", got) } tokens = toTokens(input) tokens = topK(tokens, 20) softmax(tokens) got = topP(tokens, 1e-10) if len(got) == 0 { t.Errorf("topP(1e-10): should keep at least one token, got %d", len(got)) t.Logf("got: %v", got) } } func TestMinP(t *testing.T) { input := []float32{-2, 0, -1, -3, 2, 1, 4, 3} tokens := toTokens(input) // First apply temperature and softmax tokens = topK(tokens, 20) softmax(tokens) tokens = minP(tokens, 1.0) if len(tokens) != 1 { t.Errorf("minP(1.0): should keep all tokens, got %d, want %d", len(tokens), len(tokens)) } // Test with normal p value tokens = toTokens(input) // Reset tokens tokens = topK(tokens, 20) softmax(tokens) tokens = minP(tokens, 0.2) // Should keep tokens with prob >= 0.2 * max_prob if len(tokens) > 3 { t.Errorf("minP(0.2): kept too many tokens: got %d", len(tokens)) t.Logf("got: %v", tokens) } // Test with zero p value tokens = toTokens(input) // Reset tokens tokens = topK(tokens, 20) softmax(tokens) tokens = minP(tokens, 0.0) // Should keep only the highest probability token if len(tokens) != len(input) { t.Errorf("minP(0.0): should keep only one token, got %d", len(tokens)) t.Logf("got: %v", tokens) } // Test with single token tokens = toTokens(input[:1]) tokens = topK(tokens, 20) softmax(tokens) tokens = minP(tokens, 0.1) // Should keep only the highest probability token if len(tokens) != 1 { t.Errorf("minP(0.1): should return single token, got %d", len(tokens)) t.Logf("got: %v", tokens) } input = []float32{1e-10, 1e-10, 1e-10} tokens = toTokens(input) softmax(tokens) tokens = minP(tokens, 1.0) if len(tokens) < 1 { t.Error("minP should keep at least one token even with extreme probabilities") got := minP(tokens, 1.0) if len(got) != 1 { t.Errorf("minP(1.0): should keep all tokens, got %d, want %d", len(got), len(tokens)) } // Test with normal p value got = minP(tokens, 0.2) // Should keep tokens with prob >= 0.2 * max_prob if len(got) > 3 { t.Errorf("minP(0.2): kept too many tokens: got %d", len(got)) t.Logf("got: %v", got) } // Test with zero p value got = minP(tokens, 0.0) // Should keep only the highest probability token if len(got) != len(tokens) { t.Errorf("minP(0.0): should keep only one token, got %d", len(got)) t.Logf("got: %v", got) } } } func BenchmarkTransforms(b *testing.B) { // Generate random logits tokens := make([]token, 1<<16) for i := range tokens { tokens[i] = token{ id: int32(i), value: rand.Float32(), } } tokensCopy := make([]token, len(tokens)) b.Run("Temperature", func(b *testing.B) { b.ResetTimer() for b.Loop() { copy(tokensCopy, tokens) temperature(tokensCopy, 0.5) } }) b.Run("Softmax", func(b *testing.B) { b.ResetTimer() for b.Loop() { copy(tokensCopy, tokens) softmax(tokensCopy) } }) b.Run("TopK", func(b *testing.B) { b.ResetTimer() for b.Loop() { copy(tokensCopy, tokens) tokens = topK(tokensCopy, 10) } }) b.Run("TopP", func(b *testing.B) { b.ResetTimer() for b.Loop() { copy(tokensCopy, tokens) tokens = topP(tokensCopy, 0.9) } }) b.Run("MinP", func(b *testing.B) { b.ResetTimer() for b.Loop() { copy(tokensCopy, tokens) tokens = minP(tokensCopy, 0.2) } }) b.Run("SortTokens", func(b *testing.B) { b.ResetTimer() for b.Loop() { copy(tokensCopy, tokens) tokens = topK(tokensCopy, 200000) } }) }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/sample/samplers_test.go
sample/samplers_test.go
package sample import ( "encoding/json" "math" "math/rand/v2" "os" "path/filepath" "testing" "github.com/ollama/ollama/model" ) func TestWeighted(t *testing.T) { logits := []float32{-10, 3, -10, -10} sampler := NewSampler(0, 0, 0, 0, 0, nil) got, err := sampler.Sample(logits) if err != nil { t.Error(err) return } want := int32(1) if want != got { t.Errorf("index mismatch: want %d, got %d", want, got) } logits = []float32{-100, -10, 0, 10} sampler = NewSampler(0, 0, 0, 0, 0, nil) got, err = sampler.Sample(logits) if err != nil { t.Error(err) return } want = int32(3) // Should pick highest probability with this r value if want != got { t.Errorf("index mismatch: want %d, got %d", want, got) } // Test very high p logits = []float32{1.0, 0.9999999999999999, 0.5, 0.1} // Use extremely small topP to filter out all tokens sampler = NewSampler(1.0, 0, 1e-10, 0, 0, nil) got, err = sampler.Sample(logits) if err != nil { t.Error(err) return } // Should get the token with the highest logit want = int32(0) if want != got { t.Errorf("index mismatch: want %d, got %d", want, got) } logits = []float32{float32(math.NaN()), float32(math.NaN()), float32(math.NaN())} sampler = NewSampler(1, 0, 0.95, 0.05, 0, nil) got, err = sampler.Sample(logits) if err == nil { t.Errorf("expected error, got %d", got) return } } func modelHelper(t testing.TB) model.BytePairEncoding { t.Helper() f, err := os.Open(filepath.Join("..", "model", "testdata", "llama3.2", "encoder.json")) if err != nil { t.Fatal(err) } defer f.Close() vocab := make(map[string]int32) if err := json.NewDecoder(f).Decode(&vocab); err != nil { t.Fatal(err) } tokens := make([]string, len(vocab)) for token, id := range vocab { tokens[id] = token } merges := make([]string, 0, 1) // Only need vocab for Grammar Test return model.NewBytePairEncoding( &model.Vocabulary{ Values: tokens, Types: make([]int32, len(vocab)), Merges: merges, }, ) } func TestGrammar(t *testing.T) { tokenizer := modelHelper(t) grammarJSON := ` root ::= object value ::= object | array | string | number | ("true" | "false" | "null") ws object ::= "{" ws ( string ":" ws value ("," ws string ":" ws value)* )? "}" ws array ::= "[" ws ( value ("," ws value)* )? "]" ws string ::= "\"" ( [^"\\\x7F\x00-\x1F] | "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes )* "\"" ws number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws # Optional space: by convention, applied in this grammar after literal chars when allowed ws ::= ([ \t\n] ws)? ` grammar, err := NewGrammarSampler(tokenizer, grammarJSON) if err != nil { t.Fatal(err) } defer grammar.Free() logits := make([]float32, len(tokenizer.Vocabulary().Values)) for i := range logits { logits[i] = rand.Float32() } tokens := make([]token, len(logits)) for i := range tokens { tokens[i].id = int32(i) tokens[i].value = logits[i] } grammar.Apply(tokens) nonInfCount := 0 infCount := 0 for _, tok := range tokens { if math.IsInf(float64(tok.value), -1) { infCount++ } else { nonInfCount++ } } if nonInfCount == 0 { t.Error("expected at least one non -inf token after grammar application, got none") } if infCount == 0 { t.Error("expected some -inf tokens after grammar application, got none") } } func BenchmarkSample(b *testing.B) { samplers := map[string]Sampler{ "Greedy": NewSampler(0, 0, 0, 0, 0, nil), // Use NewSampler with temp=0 for greedy "Weighted": NewSampler(0.5, 10, 0.9, 0.2, -1, nil), } // Generate random logits for benchmarking logits := make([]float32, 1<<16) for i := range logits { logits[i] = rand.Float32() } for name, s := range samplers { b.Run(name, func(b *testing.B) { b.ResetTimer() for b.Loop() { if _, err := s.Sample(logits); err != nil { b.Fatalf("error sampling: %v", err) } } }) } }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/llama/llama.go
llama/llama.go
package llama /* #cgo CFLAGS: -std=c11 #cgo windows CFLAGS: -Wno-dll-attribute-on-redeclaration #cgo CXXFLAGS: -std=c++17 #cgo CPPFLAGS: -I${SRCDIR}/llama.cpp/include #cgo CPPFLAGS: -I${SRCDIR}/llama.cpp/common #cgo CPPFLAGS: -I${SRCDIR}/llama.cpp/vendor #cgo CPPFLAGS: -I${SRCDIR}/llama.cpp/tools/mtmd #cgo CPPFLAGS: -I${SRCDIR}/llama.cpp/src #cgo CPPFLAGS: -I${SRCDIR}/../ml/backend/ggml/ggml/include #include <stdlib.h> #include "ggml.h" #include "llama.h" #include "mtmd.h" #include "mtmd-helper.h" #include "gguf.h" #include "sampling_ext.h" extern bool llamaProgressCallback(float progress, void *user_data); extern void llamaLog(int level, char* text, void* user_data); */ import "C" import ( "context" _ "embed" "errors" "fmt" "log/slog" "os" "runtime" "runtime/cgo" "slices" "strings" "sync" "unsafe" _ "github.com/ollama/ollama/llama/llama.cpp/common" _ "github.com/ollama/ollama/llama/llama.cpp/src" _ "github.com/ollama/ollama/llama/llama.cpp/tools/mtmd" _ "github.com/ollama/ollama/llama/llama.cpp/tools/mtmd/models" "github.com/ollama/ollama/ml" ggml "github.com/ollama/ollama/ml/backend/ggml/ggml/src" ) func init() { C.llama_log_set(C.ggml_log_callback(C.llamaLog), nil) } //export llamaLog func llamaLog(level C.int, text *C.char, _ unsafe.Pointer) { // slog levels zeros INFO and are multiples of 4 if slog.Default().Enabled(context.TODO(), slog.Level(int(level-C.GGML_LOG_LEVEL_INFO)*4)) { fmt.Fprint(os.Stderr, C.GoString(text)) } } func BackendInit() { ggml.OnceLoad() C.llama_backend_init() } type Devices struct { ml.DeviceID LlamaID uint64 } func EnumerateGPUs() []Devices { var ids []Devices for i := range C.ggml_backend_dev_count() { device := C.ggml_backend_dev_get(i) switch C.ggml_backend_dev_type(device) { case C.GGML_BACKEND_DEVICE_TYPE_GPU, C.GGML_BACKEND_DEVICE_TYPE_IGPU: var props C.struct_ggml_backend_dev_props C.ggml_backend_dev_get_props(device, &props) ids = append(ids, Devices{ DeviceID: ml.DeviceID{ ID: C.GoString(props.id), Library: C.GoString(props.library), }, LlamaID: uint64(i), }) } } return ids } func GetModelArch(modelPath string) (string, error) { mp := C.CString(modelPath) defer C.free(unsafe.Pointer(mp)) gguf_ctx := C.gguf_init_from_file(mp, C.struct_gguf_init_params{no_alloc: true, ctx: (**C.struct_ggml_context)(C.NULL)}) if gguf_ctx == nil { return "", errors.New("unable to load model file") } defer C.gguf_free(gguf_ctx) key := C.CString("general.architecture") defer C.free(unsafe.Pointer(key)) arch_index := C.gguf_find_key(gguf_ctx, key) if int(arch_index) < 0 { return "", errors.New("unknown model architecture") } arch := C.gguf_get_val_str(gguf_ctx, arch_index) return C.GoString(arch), nil } type ContextParams struct { c C.struct_llama_context_params } func NewContextParams(numCtx int, batchSize int, numSeqMax int, threads int, flashAttention ml.FlashAttentionType, kvCacheType string) ContextParams { params := C.llama_context_default_params() params.n_ctx = C.uint(numCtx) params.n_batch = C.uint(batchSize * numSeqMax) params.n_ubatch = C.uint(batchSize) params.n_seq_max = C.uint(numSeqMax) params.n_threads = C.int(threads) params.n_threads_batch = params.n_threads params.embeddings = C.bool(true) switch flashAttention { case ml.FlashAttentionEnabled: params.flash_attn_type = int32(C.LLAMA_FLASH_ATTN_TYPE_ENABLED) case ml.FlashAttentionDisabled: params.flash_attn_type = int32(C.LLAMA_FLASH_ATTN_TYPE_DISABLED) case ml.FlashAttentionAuto: params.flash_attn_type = int32(C.LLAMA_FLASH_ATTN_TYPE_AUTO) } params.type_k = kvCacheTypeFromStr(strings.ToLower(kvCacheType)) params.type_v = kvCacheTypeFromStr(strings.ToLower(kvCacheType)) return ContextParams{c: params} } // kvCacheTypeFromStr converts a string cache type to the corresponding GGML type value func kvCacheTypeFromStr(s string) C.enum_ggml_type { if s == "" { return C.GGML_TYPE_F16 } switch s { case "q8_0": return C.GGML_TYPE_Q8_0 case "q4_0": return C.GGML_TYPE_Q4_0 default: return C.GGML_TYPE_F16 } } type Context struct { c *C.struct_llama_context numThreads int } var ErrKvCacheFull = errors.New("could not find a kv cache slot") func (c *Context) Decode(batch *Batch) error { // Positive return values does not mean a fatal error, but rather a warning. // 0 - success // 1 - could not find a KV slot for the batch (try reducing the size of the batch or increase the context) // < 0 - error code := int(C.llama_decode(c.c, batch.c)) if code < 0 { return fmt.Errorf("llama_decode failed with code %d", code) } if code > 0 { return ErrKvCacheFull } return nil } func (c *Context) Model() *Model { return &Model{c: C.llama_get_model(c.c)} } func (c *Context) KvCacheSeqAdd(seqId int, p0 int, p1 int, delta int) { C.llama_memory_seq_add(C.llama_get_memory(c.c), C.int(seqId), C.int(p0), C.int(p1), C.int(delta)) } func (c *Context) KvCacheSeqRm(seqId int, p0 int, p1 int) bool { return bool(C.llama_memory_seq_rm(C.llama_get_memory(c.c), C.int(seqId), C.int(p0), C.int(p1))) } func (c *Context) KvCacheSeqCp(srcSeqId int, dstSeqId int, p0 int, p1 int) { C.llama_memory_seq_cp(C.llama_get_memory(c.c), C.int(srcSeqId), C.int(dstSeqId), C.int(p0), C.int(p1)) } func (c *Context) KvCacheClear() { C.llama_memory_clear(C.llama_get_memory(c.c), true) } func (c *Context) KvCacheCanShift() bool { return bool(C.llama_memory_can_shift(C.llama_get_memory(c.c))) } // Get the embeddings for a sequence id func (c *Context) GetEmbeddingsSeq(seqId int) []float32 { e := unsafe.Pointer(C.llama_get_embeddings_seq(c.c, C.int(seqId))) if e == nil { return nil } embeddings := make([]float32, c.Model().NEmbd()) _ = copy(embeddings, unsafe.Slice((*float32)(e), c.Model().NEmbd())) return embeddings } func (c *Context) GetEmbeddingsIth(i int) []float32 { e := unsafe.Pointer(C.llama_get_embeddings_ith(c.c, C.int32_t(i))) if e == nil { return nil } embeddings := make([]float32, c.Model().NEmbd()) _ = copy(embeddings, unsafe.Slice((*float32)(e), c.Model().NEmbd())) return embeddings } // GetLogitsIth gets the logits for the ith token func (c *Context) GetLogitsIth(i int) []float32 { logits := unsafe.Pointer(C.llama_get_logits_ith(c.c, C.int32_t(i))) if logits == nil { return nil } vocabSize := c.Model().NumVocab() result := make([]float32, vocabSize) _ = copy(result, unsafe.Slice((*float32)(logits), vocabSize)) return result } type ModelParams struct { Devices []uint64 NumGpuLayers int MainGpu int UseMmap bool TensorSplit []float32 Progress func(float32) VocabOnly bool } //export llamaProgressCallback func llamaProgressCallback(progress C.float, userData unsafe.Pointer) C.bool { handle := *(*cgo.Handle)(userData) callback := handle.Value().(func(float32)) callback(float32(progress)) return true } func LoadModelFromFile(modelPath string, params ModelParams) (*Model, error) { cparams := C.llama_model_default_params() cparams.n_gpu_layers = C.int(params.NumGpuLayers) cparams.main_gpu = C.int32_t(params.MainGpu) cparams.use_mmap = C.bool(params.UseMmap) cparams.vocab_only = C.bool(params.VocabOnly) var devices []C.ggml_backend_dev_t for _, llamaID := range params.Devices { devices = append(devices, C.ggml_backend_dev_get(C.size_t(llamaID))) } if len(devices) > 0 { devices = append(devices, C.ggml_backend_dev_t(C.NULL)) devicesData := &devices[0] var devicesPin runtime.Pinner devicesPin.Pin(devicesData) defer devicesPin.Unpin() cparams.devices = devicesData } if len(params.TensorSplit) > 0 { tensorSplitData := &params.TensorSplit[0] var tensorSplitPin runtime.Pinner tensorSplitPin.Pin(tensorSplitData) defer tensorSplitPin.Unpin() cparams.tensor_split = (*C.float)(unsafe.Pointer(tensorSplitData)) } if params.Progress != nil { handle := cgo.NewHandle(params.Progress) defer handle.Delete() var handlePin runtime.Pinner handlePin.Pin(&handle) defer handlePin.Unpin() cparams.progress_callback = C.llama_progress_callback(C.llamaProgressCallback) cparams.progress_callback_user_data = unsafe.Pointer(&handle) } m := Model{c: C.llama_model_load_from_file(C.CString(modelPath), cparams)} if m.c == nil { return nil, fmt.Errorf("unable to load model: %s", modelPath) } return &m, nil } func FreeModel(model *Model) { C.llama_model_free(model.c) } func NewContextWithModel(model *Model, params ContextParams) (*Context, error) { c := Context{ c: C.llama_init_from_model(model.c, params.c), numThreads: int(params.c.n_threads), } if c.c == nil { return nil, errors.New("unable to create llama context") } return &c, nil } func (m *Model) NumVocab() int { return int(C.llama_vocab_n_tokens(m.Vocab())) } func (m *Model) TokenIsEog(token int) bool { return bool(C.llama_vocab_is_eog(m.Vocab(), C.llama_token(token))) } func (m *Model) AddBOSToken() bool { return bool(C.llama_vocab_get_add_bos(m.Vocab())) } func (m *Model) ApplyLoraFromFile(context *Context, loraPath string, scale float32, threads int) error { cLoraPath := C.CString(loraPath) defer C.free(unsafe.Pointer(cLoraPath)) loraAdapter := C.llama_adapter_lora_init(m.c, cLoraPath) if loraAdapter == nil { return errors.New("unable to load lora") } err := -1 if loraAdapter != nil { err = int(C.llama_set_adapter_lora(context.c, loraAdapter, C.float(scale))) } if err != 0 { return errors.New("error applying lora from file") } return nil } func (m *Model) Vocab() *C.struct_llama_vocab { return C.llama_model_get_vocab(m.c) } type Batch struct { c C.struct_llama_batch batchSize int maxSeq int embedSize int } // Creates a new batch for either word tokens or image embeddings (if embedSize is non-zero). // Batches cannot contain both types at the same time. batchSize is the maximum number of entries // that can be added per sequence func NewBatch(batchSize int, maxSeq int, embedSize int) (*Batch, error) { b := Batch{ c: C.llama_batch_init(C.int(batchSize*maxSeq), C.int(embedSize), C.int(maxSeq)), batchSize: batchSize, maxSeq: maxSeq, embedSize: embedSize, } // Check to see if any of the allocations in llama_batch_init() failed nilPointer := (embedSize == 0 && b.c.token == nil) || (embedSize != 0 && b.c.embd == nil) || b.c.pos == nil || b.c.n_seq_id == nil || b.c.seq_id == nil || b.c.logits == nil || slices.Contains(unsafe.Slice(b.c.seq_id, b.allocSize()), nil) if nilPointer { C.llama_batch_free(b.c) return nil, fmt.Errorf("unable to allocate batch (batchSize=%v maxSeq=%v embedSize=%v)", batchSize, maxSeq, embedSize) } return &b, nil } func (b *Batch) Size() int { return b.batchSize } func (b *Batch) allocSize() int { return b.batchSize * b.maxSeq } func (b *Batch) NumTokens() int { return int(b.c.n_tokens) } func (b *Batch) IsEmbedding() bool { return b.embedSize != 0 } // Add adds either a token or an image embedding to the batch depending on the type // when the batch was initialized. The other argument will be ignored. Adds to the // batch with the given position for the given sequence ids, and optionally instructs // to include logits. func (b *Batch) Add(token int, embed []float32, pos int, logits bool, seqIds ...int) { if !b.IsEmbedding() { unsafe.Slice(b.c.token, b.allocSize())[b.c.n_tokens] = C.llama_token(token) } else { copy(unsafe.Slice((*float32)(b.c.embd), b.allocSize()*b.embedSize)[int(b.c.n_tokens)*b.embedSize:], embed) } unsafe.Slice(b.c.pos, b.allocSize())[b.c.n_tokens] = C.llama_pos(pos) unsafe.Slice(b.c.n_seq_id, b.allocSize())[b.c.n_tokens] = C.int(len(seqIds)) for i, s := range seqIds { unsafe.Slice((unsafe.Slice(b.c.seq_id, b.allocSize())[b.c.n_tokens]), C.int(len(seqIds)))[i] = C.int32_t(s) } if logits { unsafe.Slice(b.c.logits, b.allocSize())[b.c.n_tokens] = 1 } else { unsafe.Slice(b.c.logits, b.allocSize())[b.c.n_tokens] = 0 } b.c.n_tokens += 1 } func (b *Batch) Clear() { b.c.n_tokens = 0 } func (b *Batch) Free() { b.batchSize = 0 C.llama_batch_free(b.c) } type Model struct { c *C.struct_llama_model } func (m *Model) TokenToPiece(token int) string { tokenLen := 12 buf := make([]byte, tokenLen) tokenLen = int(C.llama_token_to_piece( m.Vocab(), C.int32_t(token), (*C.char)(unsafe.Pointer(&buf[0])), C.int32_t(tokenLen), C.int32_t(0), C.bool(true), )) if tokenLen < 0 { tokenLen = -tokenLen buf = make([]byte, tokenLen) C.llama_token_to_piece( m.Vocab(), C.int32_t(token), (*C.char)(unsafe.Pointer(&buf[0])), C.int32_t(tokenLen), C.int32_t(0), C.bool(true), ) } return strings.TrimRight(string(buf), "\x00") } func (m *Model) Tokenize(text string, addSpecial bool, parseSpecial bool) ([]int, error) { maxTokens := len(text) + 2 cTokens := make([]C.llama_token, maxTokens) cText := C.CString(text) defer C.free(unsafe.Pointer(cText)) result := C.llama_tokenize( m.Vocab(), cText, C.int32_t(len(text)), &cTokens[0], C.int32_t(maxTokens), C.bool(addSpecial), C.bool(parseSpecial), ) // if the result is negative, reallocate and retry with the correct buffer size if result < 0 { maxTokens = int(-result) cTokens = make([]C.llama_token, maxTokens) result = C.llama_tokenize( m.Vocab(), cText, C.int32_t(len(text)), &cTokens[0], C.int32_t(maxTokens), C.bool(addSpecial), C.bool(parseSpecial), ) if result < 0 { return nil, fmt.Errorf("tokenization failed, required %d tokens", -result) } } tokens := make([]int, result) for i := range result { tokens[i] = int(cTokens[i]) } return tokens, nil } func (m *Model) NEmbd() int { return int(C.llama_model_n_embd(m.c)) } // vision processing type MtmdContext struct { c *C.struct_mtmd_context } func NewMtmdContext(llamaContext *Context, modelPath string) (*MtmdContext, error) { mp := C.CString(modelPath) defer C.free(unsafe.Pointer(mp)) // TODO: Support non-default params cp := C.mtmd_context_params_default() // NOTE: The model and projector embedding lengths are checked during init c := C.mtmd_init_from_file(mp, C.llama_get_model(llamaContext.c), cp) if c == nil { return nil, fmt.Errorf("unable to load mmtd model: %v", modelPath) } return &MtmdContext{c: c}, nil } func (c *MtmdContext) Free() { C.mtmd_free(c.c) } type MtmdChunk struct { Embed []float32 Tokens []int } func (c *MtmdContext) MultimodalTokenize(llamaContext *Context, data []byte) ([]MtmdChunk, error) { // Initialize the input chunks pointer ic := C.mtmd_input_chunks_init() defer C.mtmd_input_chunks_free(ic) // Initialize an empty text prompt so we can tokenize it := C.mtmd_input_text_init(C.mtmd_default_marker(), true, true) defer C.mtmd_input_text_free(it) // Initialize a bitmap with the image data bm := C.mtmd_helper_bitmap_init_from_buf(c.c, (*C.uchar)(unsafe.Pointer(&data[0])), C.size_t(len(data))) defer C.mtmd_bitmap_free(bm) // Tokenize the image if C.int32_t(0) != C.mtmd_tokenize(c.c, ic, it, &bm, 1) { return nil, errors.New("unable to tokenize mtmd embedding from image") } nChunks := C.mtmd_input_chunks_size(ic) numEmbed := llamaContext.Model().NEmbd() outChunks := make([]MtmdChunk, 0) for i := range int(nChunks) { chunk := C.mtmd_input_chunks_get(ic, C.size_t(i)) numTokens := int(C.mtmd_input_chunk_get_n_tokens(chunk)) slog.Debug("chunk tokens", "index", i, "numTokens", numTokens) if C.mtmd_input_chunk_get_type(chunk) == C.MTMD_INPUT_CHUNK_TYPE_TEXT { // If this is a text chunk, add the tokens cNumTokens := C.size_t(0) cTokens := C.mtmd_input_chunk_get_tokens_text(chunk, &cNumTokens) cTokensArr := unsafe.Slice(cTokens, int(cNumTokens)) tokens := make([]int, int(cNumTokens)) for j := range int(cNumTokens) { tokens[j] = int(cTokensArr[j]) } outChunks = append(outChunks, MtmdChunk{Tokens: tokens}) } else { // Otherwise, encode the image chunk to embeddings // Encode the chunk if C.int32_t(0) != C.mtmd_encode_chunk(c.c, chunk) { return nil, errors.New("unable to encode mtmd image chunk") } // Get the embeddings for this chunk chunkEmbed := make([][]float32, numTokens) chunkEmbd := C.mtmd_get_output_embd(c.c) if nil == chunkEmbd { return nil, errors.New("no mtmd image embedding") } // Extend the embedding array for each token s := unsafe.Slice((*float32)(chunkEmbd), numTokens*numEmbed) rows := make([]float32, len(s)) copy(rows, s) for i := range numTokens { chunkEmbed[i] = rows[i*numEmbed : (i+1)*numEmbed] } for _, e := range chunkEmbed { outChunks = append(outChunks, MtmdChunk{Embed: e}) } } } slog.Debug("image tokenization chunks", "totalChunks", len(outChunks)) return outChunks, nil } func (c *Context) Synchronize() { C.llama_synchronize(c.c) } // sampling // TODO: this is a temporary wrapper to allow calling C++ code from CGo type SamplingContext struct { c *C.struct_common_sampler } type SamplingParams struct { TopK int TopP float32 MinP float32 TypicalP float32 Temp float32 RepeatLastN int PenaltyRepeat float32 PenaltyFreq float32 PenaltyPresent float32 PenalizeNl bool Seed uint32 Grammar string } func NewSamplingContext(model *Model, params SamplingParams) (*SamplingContext, error) { var cparams C.struct_common_sampler_cparams cparams.top_k = C.int32_t(params.TopK) cparams.top_p = C.float(params.TopP) cparams.min_p = C.float(params.MinP) cparams.typical_p = C.float(params.TypicalP) cparams.temp = C.float(params.Temp) cparams.penalty_last_n = C.int32_t(params.RepeatLastN) cparams.penalty_repeat = C.float(params.PenaltyRepeat) cparams.penalty_freq = C.float(params.PenaltyFreq) cparams.penalty_present = C.float(params.PenaltyPresent) cparams.seed = C.uint32_t(params.Seed) grammar := C.CString(params.Grammar) defer C.free(unsafe.Pointer(grammar)) cparams.grammar = grammar context := &SamplingContext{c: C.common_sampler_cinit(model.c, &cparams)} if context.c == nil { return nil, errors.New("unable to create sampling context") } runtime.SetFinalizer(context, func(s *SamplingContext) { C.common_sampler_cfree(s.c) }) return context, nil } func (s *SamplingContext) Reset() { C.common_sampler_creset(s.c) } func (s *SamplingContext) Sample(llamaContext *Context, idx int) int { return int(C.common_sampler_csample(s.c, llamaContext.c, C.int(idx))) } func (s *SamplingContext) Accept(id int, applyGrammar bool) { C.common_sampler_caccept(s.c, C.llama_token(id), C.bool(applyGrammar)) } // SchemaToGrammar converts the provided JSON schema to a grammar. It returns // nil if the provided schema is invalid JSON or an invalid JSON schema. func SchemaToGrammar(schema []byte) []byte { cStr := C.CString(string(schema)) defer C.free(unsafe.Pointer(cStr)) // Allocate buffer for grammar based on schema length but with upper bound maxLen := max(32768, min(1024*1024, len(schema)*4)) buf := make([]byte, maxLen) // Call C function to convert schema to grammar n := C.schema_to_grammar(cStr, (*C.char)(unsafe.Pointer(&buf[0])), C.size_t(maxLen)) if n == 0 { // preserve nil return nil } return buf[:n] } type TokenData struct { ID int32 Logit float32 } type Grammar struct { c *C.struct_llama_grammar mu sync.Mutex } func NewGrammar(grammar string, vocabIds []uint32, vocabValues []string, eogTokens []int32) *Grammar { cGrammar := C.CString(grammar) defer C.free(unsafe.Pointer(cGrammar)) cTokens := make([]C.uint32_t, len(vocabIds)) for i, token := range vocabIds { cTokens[i] = C.uint32_t(token) } cPieces := make([]*C.char, len(vocabValues)) for i, piece := range vocabValues { cPieces[i] = C.CString(piece) defer C.free(unsafe.Pointer(cPieces[i])) } cEogTokens := make([]C.uint32_t, len(eogTokens)) for i, token := range eogTokens { cEogTokens[i] = C.uint32_t(token) } g := C.grammar_init(cGrammar, unsafe.SliceData(cTokens), C.size_t(len(cTokens)), unsafe.SliceData(cPieces), unsafe.SliceData(cEogTokens), C.size_t(len(cEogTokens))) if g == nil { return nil } return &Grammar{c: g} } func (g *Grammar) Free() { g.mu.Lock() defer g.mu.Unlock() if g.c != nil { C.grammar_free(g.c) g.c = nil } } func (g *Grammar) Apply(tokens []TokenData) { g.mu.Lock() defer g.mu.Unlock() if g.c == nil { return } tds := make([]C.struct_llama_token_data, len(tokens)) for i, token := range tokens { tds[i] = C.struct_llama_token_data{ id: C.int32_t(token.ID), logit: C.float(token.Logit), p: C.float(0.0), } } tda := &C.llama_token_data_array{ data: (*C.struct_llama_token_data)(unsafe.Pointer(&tds[0])), size: C.size_t(len(tokens)), selected: C.int64_t(-1), sorted: C.bool(false), } var pinner runtime.Pinner pinner.Pin(&tds[0]) defer pinner.Unpin() C.grammar_apply(g.c, tda) for i := range tokens { tokens[i].Logit = float32(tds[i].logit) } } func (g *Grammar) Accept(token int32) { g.mu.Lock() defer g.mu.Unlock() // Check if grammar was freed if g.c == nil { return } C.grammar_accept(g.c, C.llama_token(token)) }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/llama/llama_test.go
llama/llama_test.go
package llama import ( "bufio" "bytes" "strings" "testing" ) // https://github.com/ollama/ollama/issues/7978 const issue7978JSONSchema = `{ "type": "object", "properties": { "steps": { "type": "array", "items": { "type": "object", "properties": { "explanation": { "type": "string" }, "output": { "type": "string" }, "nested": { "type": "object", "properties": { "deep": { "type": "string" } } } }, "required": ["explanation", "output"], "additionalProperties": false } }, "final_answer": { "type": "string" }, "01_numbered_key": { "type": "string" }, "numbers": { "type": "array", "items": { "type": "number" } }, "booleans": { "type": "array", "items": { "type": "boolean" } }, "mixed": { "type": "array", "items": { "oneOf": [ { "type": "string" }, { "type": "number" }, { "type": "boolean" } ] } } }, "required": ["steps", "final_answer"], "additionalProperties": false }` func TestIssue7978(t *testing.T) { g := SchemaToGrammar([]byte(issue7978JSONSchema)) if g == nil { t.Fatal("failed to convert JSON schema to grammar") } t.Logf("grammar:\n%s", g) t.Log() var got string s := bufio.NewScanner(bytes.NewReader(g)) for s.Scan() { line := strings.TrimSpace(s.Text()) step, _, _ := strings.Cut(line, " ::= ") step = strings.TrimSpace(step) if step == "root" { got = line } } want := `root ::= "{" space steps-kv "," space final-answer-kv ( "," space ( 01-numbered-key-kv 01-numbered-key-rest | numbers-kv numbers-rest | booleans-kv booleans-rest | mixed-kv ) )? "}" space` if got != want { t.Errorf("root =\n%qwant:\n%q", got, want) } } func TestSchemaToGrammar(t *testing.T) { cases := []struct { schema string prefix []byte // nil is checked as nil }{ {`invalid`, nil}, // Simple heuristic/smoke test {`{"type":"object"}`, []byte("root ::= object")}, } for _, c := range cases { t.Run(c.schema, func(t *testing.T) { g := SchemaToGrammar([]byte(c.schema)) if c.prefix == nil && g != nil { t.Fatalf("grammar = %v, want nil", g) } if !bytes.HasPrefix(g, c.prefix) { t.Errorf("grammar = %q, want %q", g, c.prefix) } }) } }
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/llama/llama.cpp/tools/mtmd/mtmd.go
llama/llama.cpp/tools/mtmd/mtmd.go
package mtmd // #cgo CXXFLAGS: -std=c++17 // #cgo CPPFLAGS: -I${SRCDIR}/../../include -I${SRCDIR}/../../common -I${SRCDIR}/../../vendor // #cgo CPPFLAGS: -I${SRCDIR}/../../../../ml/backend/ggml/ggml/include import "C"
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/llama/llama.cpp/tools/mtmd/models/models.go
llama/llama.cpp/tools/mtmd/models/models.go
package models // #cgo CXXFLAGS: -std=c++17 // #cgo CPPFLAGS: -I${SRCDIR}/../../../include -I${SRCDIR}/../../../common -I${SRCDIR}/../../../vendor // #cgo CPPFLAGS: -I${SRCDIR}/../../../../../ml/backend/ggml/ggml/include import "C"
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/llama/llama.cpp/src/llama.go
llama/llama.cpp/src/llama.go
package llama // #cgo CXXFLAGS: -std=c++17 // #cgo CPPFLAGS: -I${SRCDIR}/../include // #cgo CPPFLAGS: -I${SRCDIR}/../../../ml/backend/ggml/ggml/include // #cgo windows CPPFLAGS: -D_WIN32_WINNT=0x0602 import "C" import ( _ "github.com/ollama/ollama/llama/llama.cpp/src/models" _ "github.com/ollama/ollama/ml/backend/ggml/ggml/src" )
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/llama/llama.cpp/src/models/models.go
llama/llama.cpp/src/models/models.go
package models // #cgo CXXFLAGS: -std=c++17 // #cgo CPPFLAGS: -I${SRCDIR}/../../include -I${SRCDIR}/../../vendor // #cgo CPPFLAGS: -I${SRCDIR}/../../../../ml/backend/ggml/ggml/include import "C"
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
ollama/ollama
https://github.com/ollama/ollama/blob/626af2d80973270c4d59b8df7153ac47ad67ed7b/llama/llama.cpp/common/common.go
llama/llama.cpp/common/common.go
package common // #cgo CXXFLAGS: -std=c++17 // #cgo CPPFLAGS: -I${SRCDIR}/../include -I${SRCDIR}/../vendor // #cgo CPPFLAGS: -I${SRCDIR}/../../../ml/backend/ggml/ggml/include import "C"
go
MIT
626af2d80973270c4d59b8df7153ac47ad67ed7b
2026-01-07T08:35:43.337630Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/bridge/convert.go
pkg/bridge/convert.go
/* Copyright 2020 Docker Compose CLI 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 bridge import ( "context" "fmt" "io" "os" "os/user" "path/filepath" "runtime" "strconv" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/errdefs" "github.com/docker/cli/cli/command" cli "github.com/docker/cli/cli/command/container" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/network" "github.com/docker/docker/pkg/jsonmessage" "github.com/docker/go-connections/nat" "github.com/sirupsen/logrus" "go.yaml.in/yaml/v4" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) type ConvertOptions struct { Output string Templates string Transformations []string } func Convert(ctx context.Context, dockerCli command.Cli, project *types.Project, opts ConvertOptions) error { if len(opts.Transformations) == 0 { opts.Transformations = []string{DefaultTransformerImage} } // Load image references, secrets and configs, also expose ports project, err := LoadAdditionalResources(ctx, dockerCli, project) if err != nil { return err } // for user to rely on compose.yaml attribute names, not go struct ones, we marshall back into YAML raw, err := project.MarshalYAML(types.WithSecretContent) // Marshall to YAML if err != nil { return fmt.Errorf("cannot render project into yaml: %w", err) } var model map[string]any err = yaml.Unmarshal(raw, &model) if err != nil { return fmt.Errorf("cannot render project into yaml: %w", err) } if opts.Output != "" { _ = os.RemoveAll(opts.Output) err := os.MkdirAll(opts.Output, 0o744) if err != nil && !os.IsExist(err) { return fmt.Errorf("cannot create output folder: %w", err) } } // Run Transformers images return convert(ctx, dockerCli, model, opts) } func convert(ctx context.Context, dockerCli command.Cli, model map[string]any, opts ConvertOptions) error { raw, err := yaml.Marshal(model) if err != nil { return err } dir, err := os.MkdirTemp("", "compose-convert-*") if err != nil { return err } defer func() { err := os.RemoveAll(dir) if err != nil { logrus.Warnf("failed to remove temp dir %s: %v", dir, err) } }() composeYaml := filepath.Join(dir, "compose.yaml") err = os.WriteFile(composeYaml, raw, 0o600) if err != nil { return err } out, err := filepath.Abs(opts.Output) if err != nil { return err } binds := []string{ fmt.Sprintf("%s:%s", dir, "/in"), fmt.Sprintf("%s:%s", out, "/out"), } if opts.Templates != "" { templateDir, err := filepath.Abs(opts.Templates) if err != nil { return err } binds = append(binds, fmt.Sprintf("%s:%s", templateDir, "/templates")) } for _, transformation := range opts.Transformations { _, err = inspectWithPull(ctx, dockerCli, transformation) if err != nil { return err } containerConfig := &container.Config{ Image: transformation, Env: []string{"LICENSE_AGREEMENT=true"}, } // On POSIX systems, this is a decimal number representing the uid. // On Windows, this is a security identifier (SID) in a string format and the engine isn't able to manage it if runtime.GOOS != "windows" { usr, err := user.Current() if err != nil { return err } containerConfig.User = usr.Uid } created, err := dockerCli.Client().ContainerCreate(ctx, containerConfig, &container.HostConfig{ AutoRemove: true, Binds: binds, }, &network.NetworkingConfig{}, nil, "") if err != nil { return err } err = cli.RunStart(ctx, dockerCli, &cli.StartOptions{ Attach: true, Containers: []string{created.ID}, }) if err != nil { return err } } return nil } // LoadAdditionalResources loads additional resources from the project, such as image references, secrets, configs and exposed ports func LoadAdditionalResources(ctx context.Context, dockerCLI command.Cli, project *types.Project) (*types.Project, error) { for name, service := range project.Services { imageName := api.GetImageNameOrDefault(service, project.Name) inspect, err := inspectWithPull(ctx, dockerCLI, imageName) if err != nil { return nil, err } service.Image = imageName exposed := utils.Set[string]{} exposed.AddAll(service.Expose...) for port := range inspect.Config.ExposedPorts { exposed.Add(nat.Port(port).Port()) } for _, port := range service.Ports { exposed.Add(strconv.Itoa(int(port.Target))) } service.Expose = exposed.Elements() project.Services[name] = service } for name, secret := range project.Secrets { f, err := loadFileObject(types.FileObjectConfig(secret)) if err != nil { return nil, err } project.Secrets[name] = types.SecretConfig(f) } for name, config := range project.Configs { f, err := loadFileObject(types.FileObjectConfig(config)) if err != nil { return nil, err } project.Configs[name] = types.ConfigObjConfig(f) } return project, nil } func loadFileObject(conf types.FileObjectConfig) (types.FileObjectConfig, error) { if !conf.External { switch { case conf.Environment != "": conf.Content = os.Getenv(conf.Environment) case conf.File != "": bytes, err := os.ReadFile(conf.File) if err != nil { return conf, err } conf.Content = string(bytes) } } return conf, nil } func inspectWithPull(ctx context.Context, dockerCli command.Cli, imageName string) (image.InspectResponse, error) { inspect, err := dockerCli.Client().ImageInspect(ctx, imageName) if errdefs.IsNotFound(err) { var stream io.ReadCloser stream, err = dockerCli.Client().ImagePull(ctx, imageName, image.PullOptions{}) if err != nil { return image.InspectResponse{}, err } defer func() { _ = stream.Close() }() err = jsonmessage.DisplayJSONMessagesToStream(stream, dockerCli.Out(), nil) if err != nil { return image.InspectResponse{}, err } if inspect, err = dockerCli.Client().ImageInspect(ctx, imageName); err != nil { return image.InspectResponse{}, err } } return inspect, err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/bridge/transformers.go
pkg/bridge/transformers.go
/* Copyright 2020 Docker Compose CLI 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 bridge import ( "context" "fmt" "os" "path/filepath" "github.com/docker/cli/cli/command" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/network" "github.com/moby/go-archive" ) const ( TransformerLabel = "com.docker.compose.bridge" DefaultTransformerImage = "docker/compose-bridge-kubernetes" templatesPath = "/templates" ) type CreateTransformerOptions struct { Dest string From string } func CreateTransformer(ctx context.Context, dockerCli command.Cli, options CreateTransformerOptions) error { if options.From == "" { options.From = DefaultTransformerImage } out, err := filepath.Abs(options.Dest) if err != nil { return err } if _, err := os.Stat(out); err == nil { return fmt.Errorf("output folder %s already exists", out) } tmpl := filepath.Join(out, "templates") err = os.MkdirAll(tmpl, 0o744) if err != nil && !os.IsExist(err) { return fmt.Errorf("cannot create output folder: %w", err) } if err := command.ValidateOutputPath(out); err != nil { return err } created, err := dockerCli.Client().ContainerCreate(ctx, &container.Config{ Image: options.From, }, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "") defer func() { _ = dockerCli.Client().ContainerRemove(context.Background(), created.ID, container.RemoveOptions{Force: true}) }() if err != nil { return err } content, stat, err := dockerCli.Client().CopyFromContainer(ctx, created.ID, templatesPath) if err != nil { return err } defer func() { _ = content.Close() }() srcInfo := archive.CopyInfo{ Path: templatesPath, Exists: true, IsDir: stat.Mode.IsDir(), } preArchive := content if srcInfo.RebaseName != "" { _, srcBase := archive.SplitPathDirEntry(srcInfo.Path) preArchive = archive.RebaseArchiveEntries(content, srcBase, srcInfo.RebaseName) } if err := archive.CopyTo(preArchive, srcInfo, out); err != nil { return err } dockerfile := `FROM docker/compose-bridge-transformer LABEL com.docker.compose.bridge=transformation COPY templates /templates ` if err := os.WriteFile(filepath.Join(out, "Dockerfile"), []byte(dockerfile), 0o700); err != nil { return err } _, err = fmt.Fprintf(dockerCli.Out(), "Transformer created in %q\n", out) return err } func ListTransformers(ctx context.Context, dockerCli command.Cli) ([]image.Summary, error) { api := dockerCli.Client() return api.ImageList(ctx, image.ListOptions{ Filters: filters.NewArgs( filters.Arg("label", fmt.Sprintf("%s=%s", TransformerLabel, "transformation")), ), }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/mocks/mock_docker_api.go
pkg/mocks/mock_docker_api.go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/docker/docker/client (interfaces: APIClient) // // Generated by this command: // // mockgen -destination pkg/mocks/mock_docker_api.go -package mocks github.com/docker/docker/client APIClient // // Package mocks is a generated GoMock package. package mocks import ( context "context" io "io" net "net" http "net/http" reflect "reflect" types "github.com/docker/docker/api/types" build "github.com/docker/docker/api/types/build" checkpoint "github.com/docker/docker/api/types/checkpoint" common "github.com/docker/docker/api/types/common" container "github.com/docker/docker/api/types/container" events "github.com/docker/docker/api/types/events" filters "github.com/docker/docker/api/types/filters" image "github.com/docker/docker/api/types/image" network "github.com/docker/docker/api/types/network" registry "github.com/docker/docker/api/types/registry" swarm "github.com/docker/docker/api/types/swarm" system "github.com/docker/docker/api/types/system" volume "github.com/docker/docker/api/types/volume" client "github.com/docker/docker/client" v1 "github.com/opencontainers/image-spec/specs-go/v1" gomock "go.uber.org/mock/gomock" ) // MockAPIClient is a mock of APIClient interface. type MockAPIClient struct { ctrl *gomock.Controller recorder *MockAPIClientMockRecorder } // MockAPIClientMockRecorder is the mock recorder for MockAPIClient. type MockAPIClientMockRecorder struct { mock *MockAPIClient } // NewMockAPIClient creates a new mock instance. func NewMockAPIClient(ctrl *gomock.Controller) *MockAPIClient { mock := &MockAPIClient{ctrl: ctrl} mock.recorder = &MockAPIClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockAPIClient) EXPECT() *MockAPIClientMockRecorder { return m.recorder } // BuildCachePrune mocks base method. func (m *MockAPIClient) BuildCachePrune(arg0 context.Context, arg1 build.CachePruneOptions) (*build.CachePruneReport, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BuildCachePrune", arg0, arg1) ret0, _ := ret[0].(*build.CachePruneReport) ret1, _ := ret[1].(error) return ret0, ret1 } // BuildCachePrune indicates an expected call of BuildCachePrune. func (mr *MockAPIClientMockRecorder) BuildCachePrune(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildCachePrune", reflect.TypeOf((*MockAPIClient)(nil).BuildCachePrune), arg0, arg1) } // BuildCancel mocks base method. func (m *MockAPIClient) BuildCancel(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BuildCancel", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // BuildCancel indicates an expected call of BuildCancel. func (mr *MockAPIClientMockRecorder) BuildCancel(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildCancel", reflect.TypeOf((*MockAPIClient)(nil).BuildCancel), arg0, arg1) } // CheckpointCreate mocks base method. func (m *MockAPIClient) CheckpointCreate(arg0 context.Context, arg1 string, arg2 checkpoint.CreateOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CheckpointCreate", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // CheckpointCreate indicates an expected call of CheckpointCreate. func (mr *MockAPIClientMockRecorder) CheckpointCreate(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckpointCreate", reflect.TypeOf((*MockAPIClient)(nil).CheckpointCreate), arg0, arg1, arg2) } // CheckpointDelete mocks base method. func (m *MockAPIClient) CheckpointDelete(arg0 context.Context, arg1 string, arg2 checkpoint.DeleteOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CheckpointDelete", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // CheckpointDelete indicates an expected call of CheckpointDelete. func (mr *MockAPIClientMockRecorder) CheckpointDelete(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckpointDelete", reflect.TypeOf((*MockAPIClient)(nil).CheckpointDelete), arg0, arg1, arg2) } // CheckpointList mocks base method. func (m *MockAPIClient) CheckpointList(arg0 context.Context, arg1 string, arg2 checkpoint.ListOptions) ([]checkpoint.Summary, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CheckpointList", arg0, arg1, arg2) ret0, _ := ret[0].([]checkpoint.Summary) ret1, _ := ret[1].(error) return ret0, ret1 } // CheckpointList indicates an expected call of CheckpointList. func (mr *MockAPIClientMockRecorder) CheckpointList(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckpointList", reflect.TypeOf((*MockAPIClient)(nil).CheckpointList), arg0, arg1, arg2) } // ClientVersion mocks base method. func (m *MockAPIClient) ClientVersion() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ClientVersion") ret0, _ := ret[0].(string) return ret0 } // ClientVersion indicates an expected call of ClientVersion. func (mr *MockAPIClientMockRecorder) ClientVersion() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClientVersion", reflect.TypeOf((*MockAPIClient)(nil).ClientVersion)) } // Close mocks base method. func (m *MockAPIClient) Close() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Close") ret0, _ := ret[0].(error) return ret0 } // Close indicates an expected call of Close. func (mr *MockAPIClientMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockAPIClient)(nil).Close)) } // ConfigCreate mocks base method. func (m *MockAPIClient) ConfigCreate(arg0 context.Context, arg1 swarm.ConfigSpec) (swarm.ConfigCreateResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ConfigCreate", arg0, arg1) ret0, _ := ret[0].(swarm.ConfigCreateResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // ConfigCreate indicates an expected call of ConfigCreate. func (mr *MockAPIClientMockRecorder) ConfigCreate(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigCreate", reflect.TypeOf((*MockAPIClient)(nil).ConfigCreate), arg0, arg1) } // ConfigInspectWithRaw mocks base method. func (m *MockAPIClient) ConfigInspectWithRaw(arg0 context.Context, arg1 string) (swarm.Config, []byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ConfigInspectWithRaw", arg0, arg1) ret0, _ := ret[0].(swarm.Config) ret1, _ := ret[1].([]byte) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // ConfigInspectWithRaw indicates an expected call of ConfigInspectWithRaw. func (mr *MockAPIClientMockRecorder) ConfigInspectWithRaw(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigInspectWithRaw", reflect.TypeOf((*MockAPIClient)(nil).ConfigInspectWithRaw), arg0, arg1) } // ConfigList mocks base method. func (m *MockAPIClient) ConfigList(arg0 context.Context, arg1 swarm.ConfigListOptions) ([]swarm.Config, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ConfigList", arg0, arg1) ret0, _ := ret[0].([]swarm.Config) ret1, _ := ret[1].(error) return ret0, ret1 } // ConfigList indicates an expected call of ConfigList. func (mr *MockAPIClientMockRecorder) ConfigList(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigList", reflect.TypeOf((*MockAPIClient)(nil).ConfigList), arg0, arg1) } // ConfigRemove mocks base method. func (m *MockAPIClient) ConfigRemove(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ConfigRemove", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // ConfigRemove indicates an expected call of ConfigRemove. func (mr *MockAPIClientMockRecorder) ConfigRemove(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigRemove", reflect.TypeOf((*MockAPIClient)(nil).ConfigRemove), arg0, arg1) } // ConfigUpdate mocks base method. func (m *MockAPIClient) ConfigUpdate(arg0 context.Context, arg1 string, arg2 swarm.Version, arg3 swarm.ConfigSpec) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ConfigUpdate", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) return ret0 } // ConfigUpdate indicates an expected call of ConfigUpdate. func (mr *MockAPIClientMockRecorder) ConfigUpdate(arg0, arg1, arg2, arg3 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigUpdate", reflect.TypeOf((*MockAPIClient)(nil).ConfigUpdate), arg0, arg1, arg2, arg3) } // ContainerAttach mocks base method. func (m *MockAPIClient) ContainerAttach(arg0 context.Context, arg1 string, arg2 container.AttachOptions) (types.HijackedResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerAttach", arg0, arg1, arg2) ret0, _ := ret[0].(types.HijackedResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerAttach indicates an expected call of ContainerAttach. func (mr *MockAPIClientMockRecorder) ContainerAttach(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerAttach", reflect.TypeOf((*MockAPIClient)(nil).ContainerAttach), arg0, arg1, arg2) } // ContainerCommit mocks base method. func (m *MockAPIClient) ContainerCommit(arg0 context.Context, arg1 string, arg2 container.CommitOptions) (common.IDResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerCommit", arg0, arg1, arg2) ret0, _ := ret[0].(common.IDResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerCommit indicates an expected call of ContainerCommit. func (mr *MockAPIClientMockRecorder) ContainerCommit(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerCommit", reflect.TypeOf((*MockAPIClient)(nil).ContainerCommit), arg0, arg1, arg2) } // ContainerCreate mocks base method. func (m *MockAPIClient) ContainerCreate(arg0 context.Context, arg1 *container.Config, arg2 *container.HostConfig, arg3 *network.NetworkingConfig, arg4 *v1.Platform, arg5 string) (container.CreateResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerCreate", arg0, arg1, arg2, arg3, arg4, arg5) ret0, _ := ret[0].(container.CreateResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerCreate indicates an expected call of ContainerCreate. func (mr *MockAPIClientMockRecorder) ContainerCreate(arg0, arg1, arg2, arg3, arg4, arg5 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerCreate", reflect.TypeOf((*MockAPIClient)(nil).ContainerCreate), arg0, arg1, arg2, arg3, arg4, arg5) } // ContainerDiff mocks base method. func (m *MockAPIClient) ContainerDiff(arg0 context.Context, arg1 string) ([]container.FilesystemChange, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerDiff", arg0, arg1) ret0, _ := ret[0].([]container.FilesystemChange) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerDiff indicates an expected call of ContainerDiff. func (mr *MockAPIClientMockRecorder) ContainerDiff(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerDiff", reflect.TypeOf((*MockAPIClient)(nil).ContainerDiff), arg0, arg1) } // ContainerExecAttach mocks base method. func (m *MockAPIClient) ContainerExecAttach(arg0 context.Context, arg1 string, arg2 container.ExecStartOptions) (types.HijackedResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerExecAttach", arg0, arg1, arg2) ret0, _ := ret[0].(types.HijackedResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerExecAttach indicates an expected call of ContainerExecAttach. func (mr *MockAPIClientMockRecorder) ContainerExecAttach(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerExecAttach", reflect.TypeOf((*MockAPIClient)(nil).ContainerExecAttach), arg0, arg1, arg2) } // ContainerExecCreate mocks base method. func (m *MockAPIClient) ContainerExecCreate(arg0 context.Context, arg1 string, arg2 container.ExecOptions) (common.IDResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerExecCreate", arg0, arg1, arg2) ret0, _ := ret[0].(common.IDResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerExecCreate indicates an expected call of ContainerExecCreate. func (mr *MockAPIClientMockRecorder) ContainerExecCreate(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerExecCreate", reflect.TypeOf((*MockAPIClient)(nil).ContainerExecCreate), arg0, arg1, arg2) } // ContainerExecInspect mocks base method. func (m *MockAPIClient) ContainerExecInspect(arg0 context.Context, arg1 string) (container.ExecInspect, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerExecInspect", arg0, arg1) ret0, _ := ret[0].(container.ExecInspect) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerExecInspect indicates an expected call of ContainerExecInspect. func (mr *MockAPIClientMockRecorder) ContainerExecInspect(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerExecInspect", reflect.TypeOf((*MockAPIClient)(nil).ContainerExecInspect), arg0, arg1) } // ContainerExecResize mocks base method. func (m *MockAPIClient) ContainerExecResize(arg0 context.Context, arg1 string, arg2 container.ResizeOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerExecResize", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // ContainerExecResize indicates an expected call of ContainerExecResize. func (mr *MockAPIClientMockRecorder) ContainerExecResize(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerExecResize", reflect.TypeOf((*MockAPIClient)(nil).ContainerExecResize), arg0, arg1, arg2) } // ContainerExecStart mocks base method. func (m *MockAPIClient) ContainerExecStart(arg0 context.Context, arg1 string, arg2 container.ExecStartOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerExecStart", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // ContainerExecStart indicates an expected call of ContainerExecStart. func (mr *MockAPIClientMockRecorder) ContainerExecStart(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerExecStart", reflect.TypeOf((*MockAPIClient)(nil).ContainerExecStart), arg0, arg1, arg2) } // ContainerExport mocks base method. func (m *MockAPIClient) ContainerExport(arg0 context.Context, arg1 string) (io.ReadCloser, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerExport", arg0, arg1) ret0, _ := ret[0].(io.ReadCloser) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerExport indicates an expected call of ContainerExport. func (mr *MockAPIClientMockRecorder) ContainerExport(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerExport", reflect.TypeOf((*MockAPIClient)(nil).ContainerExport), arg0, arg1) } // ContainerInspect mocks base method. func (m *MockAPIClient) ContainerInspect(arg0 context.Context, arg1 string) (container.InspectResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerInspect", arg0, arg1) ret0, _ := ret[0].(container.InspectResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerInspect indicates an expected call of ContainerInspect. func (mr *MockAPIClientMockRecorder) ContainerInspect(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerInspect", reflect.TypeOf((*MockAPIClient)(nil).ContainerInspect), arg0, arg1) } // ContainerInspectWithRaw mocks base method. func (m *MockAPIClient) ContainerInspectWithRaw(arg0 context.Context, arg1 string, arg2 bool) (container.InspectResponse, []byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerInspectWithRaw", arg0, arg1, arg2) ret0, _ := ret[0].(container.InspectResponse) ret1, _ := ret[1].([]byte) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // ContainerInspectWithRaw indicates an expected call of ContainerInspectWithRaw. func (mr *MockAPIClientMockRecorder) ContainerInspectWithRaw(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerInspectWithRaw", reflect.TypeOf((*MockAPIClient)(nil).ContainerInspectWithRaw), arg0, arg1, arg2) } // ContainerKill mocks base method. func (m *MockAPIClient) ContainerKill(arg0 context.Context, arg1, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerKill", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // ContainerKill indicates an expected call of ContainerKill. func (mr *MockAPIClientMockRecorder) ContainerKill(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerKill", reflect.TypeOf((*MockAPIClient)(nil).ContainerKill), arg0, arg1, arg2) } // ContainerList mocks base method. func (m *MockAPIClient) ContainerList(arg0 context.Context, arg1 container.ListOptions) ([]container.Summary, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerList", arg0, arg1) ret0, _ := ret[0].([]container.Summary) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerList indicates an expected call of ContainerList. func (mr *MockAPIClientMockRecorder) ContainerList(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerList", reflect.TypeOf((*MockAPIClient)(nil).ContainerList), arg0, arg1) } // ContainerLogs mocks base method. func (m *MockAPIClient) ContainerLogs(arg0 context.Context, arg1 string, arg2 container.LogsOptions) (io.ReadCloser, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerLogs", arg0, arg1, arg2) ret0, _ := ret[0].(io.ReadCloser) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerLogs indicates an expected call of ContainerLogs. func (mr *MockAPIClientMockRecorder) ContainerLogs(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerLogs", reflect.TypeOf((*MockAPIClient)(nil).ContainerLogs), arg0, arg1, arg2) } // ContainerPause mocks base method. func (m *MockAPIClient) ContainerPause(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerPause", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // ContainerPause indicates an expected call of ContainerPause. func (mr *MockAPIClientMockRecorder) ContainerPause(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerPause", reflect.TypeOf((*MockAPIClient)(nil).ContainerPause), arg0, arg1) } // ContainerRemove mocks base method. func (m *MockAPIClient) ContainerRemove(arg0 context.Context, arg1 string, arg2 container.RemoveOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerRemove", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // ContainerRemove indicates an expected call of ContainerRemove. func (mr *MockAPIClientMockRecorder) ContainerRemove(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerRemove", reflect.TypeOf((*MockAPIClient)(nil).ContainerRemove), arg0, arg1, arg2) } // ContainerRename mocks base method. func (m *MockAPIClient) ContainerRename(arg0 context.Context, arg1, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerRename", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // ContainerRename indicates an expected call of ContainerRename. func (mr *MockAPIClientMockRecorder) ContainerRename(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerRename", reflect.TypeOf((*MockAPIClient)(nil).ContainerRename), arg0, arg1, arg2) } // ContainerResize mocks base method. func (m *MockAPIClient) ContainerResize(arg0 context.Context, arg1 string, arg2 container.ResizeOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerResize", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // ContainerResize indicates an expected call of ContainerResize. func (mr *MockAPIClientMockRecorder) ContainerResize(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerResize", reflect.TypeOf((*MockAPIClient)(nil).ContainerResize), arg0, arg1, arg2) } // ContainerRestart mocks base method. func (m *MockAPIClient) ContainerRestart(arg0 context.Context, arg1 string, arg2 container.StopOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerRestart", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // ContainerRestart indicates an expected call of ContainerRestart. func (mr *MockAPIClientMockRecorder) ContainerRestart(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerRestart", reflect.TypeOf((*MockAPIClient)(nil).ContainerRestart), arg0, arg1, arg2) } // ContainerStart mocks base method. func (m *MockAPIClient) ContainerStart(arg0 context.Context, arg1 string, arg2 container.StartOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerStart", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // ContainerStart indicates an expected call of ContainerStart. func (mr *MockAPIClientMockRecorder) ContainerStart(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerStart", reflect.TypeOf((*MockAPIClient)(nil).ContainerStart), arg0, arg1, arg2) } // ContainerStatPath mocks base method. func (m *MockAPIClient) ContainerStatPath(arg0 context.Context, arg1, arg2 string) (container.PathStat, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerStatPath", arg0, arg1, arg2) ret0, _ := ret[0].(container.PathStat) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerStatPath indicates an expected call of ContainerStatPath. func (mr *MockAPIClientMockRecorder) ContainerStatPath(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerStatPath", reflect.TypeOf((*MockAPIClient)(nil).ContainerStatPath), arg0, arg1, arg2) } // ContainerStats mocks base method. func (m *MockAPIClient) ContainerStats(arg0 context.Context, arg1 string, arg2 bool) (container.StatsResponseReader, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerStats", arg0, arg1, arg2) ret0, _ := ret[0].(container.StatsResponseReader) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerStats indicates an expected call of ContainerStats. func (mr *MockAPIClientMockRecorder) ContainerStats(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerStats", reflect.TypeOf((*MockAPIClient)(nil).ContainerStats), arg0, arg1, arg2) } // ContainerStatsOneShot mocks base method. func (m *MockAPIClient) ContainerStatsOneShot(arg0 context.Context, arg1 string) (container.StatsResponseReader, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerStatsOneShot", arg0, arg1) ret0, _ := ret[0].(container.StatsResponseReader) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerStatsOneShot indicates an expected call of ContainerStatsOneShot. func (mr *MockAPIClientMockRecorder) ContainerStatsOneShot(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerStatsOneShot", reflect.TypeOf((*MockAPIClient)(nil).ContainerStatsOneShot), arg0, arg1) } // ContainerStop mocks base method. func (m *MockAPIClient) ContainerStop(arg0 context.Context, arg1 string, arg2 container.StopOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerStop", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // ContainerStop indicates an expected call of ContainerStop. func (mr *MockAPIClientMockRecorder) ContainerStop(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerStop", reflect.TypeOf((*MockAPIClient)(nil).ContainerStop), arg0, arg1, arg2) } // ContainerTop mocks base method. func (m *MockAPIClient) ContainerTop(arg0 context.Context, arg1 string, arg2 []string) (container.TopResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerTop", arg0, arg1, arg2) ret0, _ := ret[0].(container.TopResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerTop indicates an expected call of ContainerTop. func (mr *MockAPIClientMockRecorder) ContainerTop(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerTop", reflect.TypeOf((*MockAPIClient)(nil).ContainerTop), arg0, arg1, arg2) } // ContainerUnpause mocks base method. func (m *MockAPIClient) ContainerUnpause(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerUnpause", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // ContainerUnpause indicates an expected call of ContainerUnpause. func (mr *MockAPIClientMockRecorder) ContainerUnpause(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerUnpause", reflect.TypeOf((*MockAPIClient)(nil).ContainerUnpause), arg0, arg1) } // ContainerUpdate mocks base method. func (m *MockAPIClient) ContainerUpdate(arg0 context.Context, arg1 string, arg2 container.UpdateConfig) (container.UpdateResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerUpdate", arg0, arg1, arg2) ret0, _ := ret[0].(container.UpdateResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainerUpdate indicates an expected call of ContainerUpdate. func (mr *MockAPIClientMockRecorder) ContainerUpdate(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerUpdate", reflect.TypeOf((*MockAPIClient)(nil).ContainerUpdate), arg0, arg1, arg2) } // ContainerWait mocks base method. func (m *MockAPIClient) ContainerWait(arg0 context.Context, arg1 string, arg2 container.WaitCondition) (<-chan container.WaitResponse, <-chan error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainerWait", arg0, arg1, arg2) ret0, _ := ret[0].(<-chan container.WaitResponse) ret1, _ := ret[1].(<-chan error) return ret0, ret1 } // ContainerWait indicates an expected call of ContainerWait. func (mr *MockAPIClientMockRecorder) ContainerWait(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainerWait", reflect.TypeOf((*MockAPIClient)(nil).ContainerWait), arg0, arg1, arg2) } // ContainersPrune mocks base method. func (m *MockAPIClient) ContainersPrune(arg0 context.Context, arg1 filters.Args) (container.PruneReport, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContainersPrune", arg0, arg1) ret0, _ := ret[0].(container.PruneReport) ret1, _ := ret[1].(error) return ret0, ret1 } // ContainersPrune indicates an expected call of ContainersPrune. func (mr *MockAPIClientMockRecorder) ContainersPrune(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContainersPrune", reflect.TypeOf((*MockAPIClient)(nil).ContainersPrune), arg0, arg1) } // CopyFromContainer mocks base method. func (m *MockAPIClient) CopyFromContainer(arg0 context.Context, arg1, arg2 string) (io.ReadCloser, container.PathStat, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CopyFromContainer", arg0, arg1, arg2) ret0, _ := ret[0].(io.ReadCloser) ret1, _ := ret[1].(container.PathStat) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // CopyFromContainer indicates an expected call of CopyFromContainer. func (mr *MockAPIClientMockRecorder) CopyFromContainer(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CopyFromContainer", reflect.TypeOf((*MockAPIClient)(nil).CopyFromContainer), arg0, arg1, arg2) } // CopyToContainer mocks base method. func (m *MockAPIClient) CopyToContainer(arg0 context.Context, arg1, arg2 string, arg3 io.Reader, arg4 container.CopyToContainerOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CopyToContainer", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(error) return ret0 } // CopyToContainer indicates an expected call of CopyToContainer. func (mr *MockAPIClientMockRecorder) CopyToContainer(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CopyToContainer", reflect.TypeOf((*MockAPIClient)(nil).CopyToContainer), arg0, arg1, arg2, arg3, arg4) } // DaemonHost mocks base method. func (m *MockAPIClient) DaemonHost() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DaemonHost") ret0, _ := ret[0].(string) return ret0 } // DaemonHost indicates an expected call of DaemonHost. func (mr *MockAPIClientMockRecorder) DaemonHost() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DaemonHost", reflect.TypeOf((*MockAPIClient)(nil).DaemonHost)) } // DialHijack mocks base method. func (m *MockAPIClient) DialHijack(arg0 context.Context, arg1, arg2 string, arg3 map[string][]string) (net.Conn, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DialHijack", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(net.Conn) ret1, _ := ret[1].(error) return ret0, ret1 } // DialHijack indicates an expected call of DialHijack. func (mr *MockAPIClientMockRecorder) DialHijack(arg0, arg1, arg2, arg3 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DialHijack", reflect.TypeOf((*MockAPIClient)(nil).DialHijack), arg0, arg1, arg2, arg3) } // Dialer mocks base method. func (m *MockAPIClient) Dialer() func(context.Context) (net.Conn, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Dialer") ret0, _ := ret[0].(func(context.Context) (net.Conn, error)) return ret0 } // Dialer indicates an expected call of Dialer. func (mr *MockAPIClientMockRecorder) Dialer() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Dialer", reflect.TypeOf((*MockAPIClient)(nil).Dialer)) } // DiskUsage mocks base method. func (m *MockAPIClient) DiskUsage(arg0 context.Context, arg1 types.DiskUsageOptions) (types.DiskUsage, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DiskUsage", arg0, arg1) ret0, _ := ret[0].(types.DiskUsage) ret1, _ := ret[1].(error) return ret0, ret1 } // DiskUsage indicates an expected call of DiskUsage. func (mr *MockAPIClientMockRecorder) DiskUsage(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DiskUsage", reflect.TypeOf((*MockAPIClient)(nil).DiskUsage), arg0, arg1) } // DistributionInspect mocks base method. func (m *MockAPIClient) DistributionInspect(arg0 context.Context, arg1, arg2 string) (registry.DistributionInspect, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DistributionInspect", arg0, arg1, arg2) ret0, _ := ret[0].(registry.DistributionInspect) ret1, _ := ret[1].(error) return ret0, ret1 } // DistributionInspect indicates an expected call of DistributionInspect. func (mr *MockAPIClientMockRecorder) DistributionInspect(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DistributionInspect", reflect.TypeOf((*MockAPIClient)(nil).DistributionInspect), arg0, arg1, arg2) } // Events mocks base method. func (m *MockAPIClient) Events(arg0 context.Context, arg1 events.ListOptions) (<-chan events.Message, <-chan error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Events", arg0, arg1) ret0, _ := ret[0].(<-chan events.Message)
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
true
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/mocks/mock_docker_cli.go
pkg/mocks/mock_docker_cli.go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/docker/cli/cli/command (interfaces: Cli) // // Generated by this command: // // mockgen -destination pkg/mocks/mock_docker_cli.go -package mocks github.com/docker/cli/cli/command Cli // // Package mocks is a generated GoMock package. package mocks import ( reflect "reflect" command "github.com/docker/cli/cli/command" configfile "github.com/docker/cli/cli/config/configfile" docker "github.com/docker/cli/cli/context/docker" store "github.com/docker/cli/cli/context/store" streams "github.com/docker/cli/cli/streams" client "github.com/docker/docker/client" metric "go.opentelemetry.io/otel/metric" resource "go.opentelemetry.io/otel/sdk/resource" trace "go.opentelemetry.io/otel/trace" gomock "go.uber.org/mock/gomock" ) // MockCli is a mock of Cli interface. type MockCli struct { ctrl *gomock.Controller recorder *MockCliMockRecorder } // MockCliMockRecorder is the mock recorder for MockCli. type MockCliMockRecorder struct { mock *MockCli } // NewMockCli creates a new mock instance. func NewMockCli(ctrl *gomock.Controller) *MockCli { mock := &MockCli{ctrl: ctrl} mock.recorder = &MockCliMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockCli) EXPECT() *MockCliMockRecorder { return m.recorder } // Apply mocks base method. func (m *MockCli) Apply(arg0 ...command.CLIOption) error { m.ctrl.T.Helper() varargs := []any{} for _, a := range arg0 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Apply", varargs...) ret0, _ := ret[0].(error) return ret0 } // Apply indicates an expected call of Apply. func (mr *MockCliMockRecorder) Apply(arg0 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*MockCli)(nil).Apply), arg0...) } // BuildKitEnabled mocks base method. func (m *MockCli) BuildKitEnabled() (bool, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BuildKitEnabled") ret0, _ := ret[0].(bool) ret1, _ := ret[1].(error) return ret0, ret1 } // BuildKitEnabled indicates an expected call of BuildKitEnabled. func (mr *MockCliMockRecorder) BuildKitEnabled() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildKitEnabled", reflect.TypeOf((*MockCli)(nil).BuildKitEnabled)) } // Client mocks base method. func (m *MockCli) Client() client.APIClient { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Client") ret0, _ := ret[0].(client.APIClient) return ret0 } // Client indicates an expected call of Client. func (mr *MockCliMockRecorder) Client() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Client", reflect.TypeOf((*MockCli)(nil).Client)) } // ConfigFile mocks base method. func (m *MockCli) ConfigFile() *configfile.ConfigFile { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ConfigFile") ret0, _ := ret[0].(*configfile.ConfigFile) return ret0 } // ConfigFile indicates an expected call of ConfigFile. func (mr *MockCliMockRecorder) ConfigFile() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigFile", reflect.TypeOf((*MockCli)(nil).ConfigFile)) } // ContextStore mocks base method. func (m *MockCli) ContextStore() store.Store { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ContextStore") ret0, _ := ret[0].(store.Store) return ret0 } // ContextStore indicates an expected call of ContextStore. func (mr *MockCliMockRecorder) ContextStore() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContextStore", reflect.TypeOf((*MockCli)(nil).ContextStore)) } // CurrentContext mocks base method. func (m *MockCli) CurrentContext() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CurrentContext") ret0, _ := ret[0].(string) return ret0 } // CurrentContext indicates an expected call of CurrentContext. func (mr *MockCliMockRecorder) CurrentContext() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CurrentContext", reflect.TypeOf((*MockCli)(nil).CurrentContext)) } // CurrentVersion mocks base method. func (m *MockCli) CurrentVersion() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CurrentVersion") ret0, _ := ret[0].(string) return ret0 } // CurrentVersion indicates an expected call of CurrentVersion. func (mr *MockCliMockRecorder) CurrentVersion() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CurrentVersion", reflect.TypeOf((*MockCli)(nil).CurrentVersion)) } // DockerEndpoint mocks base method. func (m *MockCli) DockerEndpoint() docker.Endpoint { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DockerEndpoint") ret0, _ := ret[0].(docker.Endpoint) return ret0 } // DockerEndpoint indicates an expected call of DockerEndpoint. func (mr *MockCliMockRecorder) DockerEndpoint() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DockerEndpoint", reflect.TypeOf((*MockCli)(nil).DockerEndpoint)) } // Err mocks base method. func (m *MockCli) Err() *streams.Out { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Err") ret0, _ := ret[0].(*streams.Out) return ret0 } // Err indicates an expected call of Err. func (mr *MockCliMockRecorder) Err() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Err", reflect.TypeOf((*MockCli)(nil).Err)) } // In mocks base method. func (m *MockCli) In() *streams.In { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "In") ret0, _ := ret[0].(*streams.In) return ret0 } // In indicates an expected call of In. func (mr *MockCliMockRecorder) In() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "In", reflect.TypeOf((*MockCli)(nil).In)) } // MeterProvider mocks base method. func (m *MockCli) MeterProvider() metric.MeterProvider { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "MeterProvider") ret0, _ := ret[0].(metric.MeterProvider) return ret0 } // MeterProvider indicates an expected call of MeterProvider. func (mr *MockCliMockRecorder) MeterProvider() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MeterProvider", reflect.TypeOf((*MockCli)(nil).MeterProvider)) } // Out mocks base method. func (m *MockCli) Out() *streams.Out { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Out") ret0, _ := ret[0].(*streams.Out) return ret0 } // Out indicates an expected call of Out. func (mr *MockCliMockRecorder) Out() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Out", reflect.TypeOf((*MockCli)(nil).Out)) } // Resource mocks base method. func (m *MockCli) Resource() *resource.Resource { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Resource") ret0, _ := ret[0].(*resource.Resource) return ret0 } // Resource indicates an expected call of Resource. func (mr *MockCliMockRecorder) Resource() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Resource", reflect.TypeOf((*MockCli)(nil).Resource)) } // ServerInfo mocks base method. func (m *MockCli) ServerInfo() command.ServerInfo { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ServerInfo") ret0, _ := ret[0].(command.ServerInfo) return ret0 } // ServerInfo indicates an expected call of ServerInfo. func (mr *MockCliMockRecorder) ServerInfo() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServerInfo", reflect.TypeOf((*MockCli)(nil).ServerInfo)) } // SetIn mocks base method. func (m *MockCli) SetIn(arg0 *streams.In) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetIn", arg0) } // SetIn indicates an expected call of SetIn. func (mr *MockCliMockRecorder) SetIn(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetIn", reflect.TypeOf((*MockCli)(nil).SetIn), arg0) } // TracerProvider mocks base method. func (m *MockCli) TracerProvider() trace.TracerProvider { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TracerProvider") ret0, _ := ret[0].(trace.TracerProvider) return ret0 } // TracerProvider indicates an expected call of TracerProvider. func (mr *MockCliMockRecorder) TracerProvider() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TracerProvider", reflect.TypeOf((*MockCli)(nil).TracerProvider)) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/mocks/mock_docker_compose_api.go
pkg/mocks/mock_docker_compose_api.go
// Code generated by MockGen. DO NOT EDIT. // Source: ./pkg/api/api.go // // Generated by this command: // // mockgen -destination pkg/mocks/mock_docker_compose_api.go -package mocks -source=./pkg/api/api.go Service // // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" types "github.com/compose-spec/compose-go/v2/types" api "github.com/docker/compose/v5/pkg/api" gomock "go.uber.org/mock/gomock" ) // MockCompose is a mock of Compose interface. type MockCompose struct { ctrl *gomock.Controller recorder *MockComposeMockRecorder } // MockComposeMockRecorder is the mock recorder for MockCompose. type MockComposeMockRecorder struct { mock *MockCompose } // NewMockCompose creates a new mock instance. func NewMockCompose(ctrl *gomock.Controller) *MockCompose { mock := &MockCompose{ctrl: ctrl} mock.recorder = &MockComposeMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockCompose) EXPECT() *MockComposeMockRecorder { return m.recorder } // Attach mocks base method. func (m *MockCompose) Attach(ctx context.Context, projectName string, options api.AttachOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Attach", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Attach indicates an expected call of Attach. func (mr *MockComposeMockRecorder) Attach(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Attach", reflect.TypeOf((*MockCompose)(nil).Attach), ctx, projectName, options) } // Build mocks base method. func (m *MockCompose) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Build", ctx, project, options) ret0, _ := ret[0].(error) return ret0 } // Build indicates an expected call of Build. func (mr *MockComposeMockRecorder) Build(ctx, project, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Build", reflect.TypeOf((*MockCompose)(nil).Build), ctx, project, options) } // Commit mocks base method. func (m *MockCompose) Commit(ctx context.Context, projectName string, options api.CommitOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Commit", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Commit indicates an expected call of Commit. func (mr *MockComposeMockRecorder) Commit(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Commit", reflect.TypeOf((*MockCompose)(nil).Commit), ctx, projectName, options) } // Copy mocks base method. func (m *MockCompose) Copy(ctx context.Context, projectName string, options api.CopyOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Copy", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Copy indicates an expected call of Copy. func (mr *MockComposeMockRecorder) Copy(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Copy", reflect.TypeOf((*MockCompose)(nil).Copy), ctx, projectName, options) } // Create mocks base method. func (m *MockCompose) Create(ctx context.Context, project *types.Project, options api.CreateOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Create", ctx, project, options) ret0, _ := ret[0].(error) return ret0 } // Create indicates an expected call of Create. func (mr *MockComposeMockRecorder) Create(ctx, project, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockCompose)(nil).Create), ctx, project, options) } // Down mocks base method. func (m *MockCompose) Down(ctx context.Context, projectName string, options api.DownOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Down", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Down indicates an expected call of Down. func (mr *MockComposeMockRecorder) Down(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Down", reflect.TypeOf((*MockCompose)(nil).Down), ctx, projectName, options) } // Events mocks base method. func (m *MockCompose) Events(ctx context.Context, projectName string, options api.EventsOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Events", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Events indicates an expected call of Events. func (mr *MockComposeMockRecorder) Events(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Events", reflect.TypeOf((*MockCompose)(nil).Events), ctx, projectName, options) } // Exec mocks base method. func (m *MockCompose) Exec(ctx context.Context, projectName string, options api.RunOptions) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Exec", ctx, projectName, options) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } // Exec indicates an expected call of Exec. func (mr *MockComposeMockRecorder) Exec(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Exec", reflect.TypeOf((*MockCompose)(nil).Exec), ctx, projectName, options) } // Export mocks base method. func (m *MockCompose) Export(ctx context.Context, projectName string, options api.ExportOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Export", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Export indicates an expected call of Export. func (mr *MockComposeMockRecorder) Export(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Export", reflect.TypeOf((*MockCompose)(nil).Export), ctx, projectName, options) } // Generate mocks base method. func (m *MockCompose) Generate(ctx context.Context, options api.GenerateOptions) (*types.Project, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Generate", ctx, options) ret0, _ := ret[0].(*types.Project) ret1, _ := ret[1].(error) return ret0, ret1 } // Generate indicates an expected call of Generate. func (mr *MockComposeMockRecorder) Generate(ctx, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Generate", reflect.TypeOf((*MockCompose)(nil).Generate), ctx, options) } // Images mocks base method. func (m *MockCompose) Images(ctx context.Context, projectName string, options api.ImagesOptions) (map[string]api.ImageSummary, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Images", ctx, projectName, options) ret0, _ := ret[0].(map[string]api.ImageSummary) ret1, _ := ret[1].(error) return ret0, ret1 } // Images indicates an expected call of Images. func (mr *MockComposeMockRecorder) Images(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Images", reflect.TypeOf((*MockCompose)(nil).Images), ctx, projectName, options) } // Kill mocks base method. func (m *MockCompose) Kill(ctx context.Context, projectName string, options api.KillOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Kill", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Kill indicates an expected call of Kill. func (mr *MockComposeMockRecorder) Kill(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Kill", reflect.TypeOf((*MockCompose)(nil).Kill), ctx, projectName, options) } // List mocks base method. func (m *MockCompose) List(ctx context.Context, options api.ListOptions) ([]api.Stack, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "List", ctx, options) ret0, _ := ret[0].([]api.Stack) ret1, _ := ret[1].(error) return ret0, ret1 } // List indicates an expected call of List. func (mr *MockComposeMockRecorder) List(ctx, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockCompose)(nil).List), ctx, options) } // LoadProject mocks base method. func (m *MockCompose) LoadProject(ctx context.Context, options api.ProjectLoadOptions) (*types.Project, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LoadProject", ctx, options) ret0, _ := ret[0].(*types.Project) ret1, _ := ret[1].(error) return ret0, ret1 } // LoadProject indicates an expected call of LoadProject. func (mr *MockComposeMockRecorder) LoadProject(ctx, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LoadProject", reflect.TypeOf((*MockCompose)(nil).LoadProject), ctx, options) } // Logs mocks base method. func (m *MockCompose) Logs(ctx context.Context, projectName string, consumer api.LogConsumer, options api.LogOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Logs", ctx, projectName, consumer, options) ret0, _ := ret[0].(error) return ret0 } // Logs indicates an expected call of Logs. func (mr *MockComposeMockRecorder) Logs(ctx, projectName, consumer, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Logs", reflect.TypeOf((*MockCompose)(nil).Logs), ctx, projectName, consumer, options) } // Pause mocks base method. func (m *MockCompose) Pause(ctx context.Context, projectName string, options api.PauseOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Pause", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Pause indicates an expected call of Pause. func (mr *MockComposeMockRecorder) Pause(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Pause", reflect.TypeOf((*MockCompose)(nil).Pause), ctx, projectName, options) } // Port mocks base method. func (m *MockCompose) Port(ctx context.Context, projectName, service string, port uint16, options api.PortOptions) (string, int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Port", ctx, projectName, service, port, options) ret0, _ := ret[0].(string) ret1, _ := ret[1].(int) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } // Port indicates an expected call of Port. func (mr *MockComposeMockRecorder) Port(ctx, projectName, service, port, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Port", reflect.TypeOf((*MockCompose)(nil).Port), ctx, projectName, service, port, options) } // Ps mocks base method. func (m *MockCompose) Ps(ctx context.Context, projectName string, options api.PsOptions) ([]api.ContainerSummary, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Ps", ctx, projectName, options) ret0, _ := ret[0].([]api.ContainerSummary) ret1, _ := ret[1].(error) return ret0, ret1 } // Ps indicates an expected call of Ps. func (mr *MockComposeMockRecorder) Ps(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ps", reflect.TypeOf((*MockCompose)(nil).Ps), ctx, projectName, options) } // Publish mocks base method. func (m *MockCompose) Publish(ctx context.Context, project *types.Project, repository string, options api.PublishOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Publish", ctx, project, repository, options) ret0, _ := ret[0].(error) return ret0 } // Publish indicates an expected call of Publish. func (mr *MockComposeMockRecorder) Publish(ctx, project, repository, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Publish", reflect.TypeOf((*MockCompose)(nil).Publish), ctx, project, repository, options) } // Pull mocks base method. func (m *MockCompose) Pull(ctx context.Context, project *types.Project, options api.PullOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Pull", ctx, project, options) ret0, _ := ret[0].(error) return ret0 } // Pull indicates an expected call of Pull. func (mr *MockComposeMockRecorder) Pull(ctx, project, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Pull", reflect.TypeOf((*MockCompose)(nil).Pull), ctx, project, options) } // Push mocks base method. func (m *MockCompose) Push(ctx context.Context, project *types.Project, options api.PushOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Push", ctx, project, options) ret0, _ := ret[0].(error) return ret0 } // Push indicates an expected call of Push. func (mr *MockComposeMockRecorder) Push(ctx, project, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Push", reflect.TypeOf((*MockCompose)(nil).Push), ctx, project, options) } // Remove mocks base method. func (m *MockCompose) Remove(ctx context.Context, projectName string, options api.RemoveOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Remove", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Remove indicates an expected call of Remove. func (mr *MockComposeMockRecorder) Remove(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockCompose)(nil).Remove), ctx, projectName, options) } // Restart mocks base method. func (m *MockCompose) Restart(ctx context.Context, projectName string, options api.RestartOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Restart", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Restart indicates an expected call of Restart. func (mr *MockComposeMockRecorder) Restart(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Restart", reflect.TypeOf((*MockCompose)(nil).Restart), ctx, projectName, options) } // RunOneOffContainer mocks base method. func (m *MockCompose) RunOneOffContainer(ctx context.Context, project *types.Project, opts api.RunOptions) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RunOneOffContainer", ctx, project, opts) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } // RunOneOffContainer indicates an expected call of RunOneOffContainer. func (mr *MockComposeMockRecorder) RunOneOffContainer(ctx, project, opts any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RunOneOffContainer", reflect.TypeOf((*MockCompose)(nil).RunOneOffContainer), ctx, project, opts) } // Scale mocks base method. func (m *MockCompose) Scale(ctx context.Context, project *types.Project, options api.ScaleOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Scale", ctx, project, options) ret0, _ := ret[0].(error) return ret0 } // Scale indicates an expected call of Scale. func (mr *MockComposeMockRecorder) Scale(ctx, project, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Scale", reflect.TypeOf((*MockCompose)(nil).Scale), ctx, project, options) } // Start mocks base method. func (m *MockCompose) Start(ctx context.Context, projectName string, options api.StartOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Start", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Start indicates an expected call of Start. func (mr *MockComposeMockRecorder) Start(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockCompose)(nil).Start), ctx, projectName, options) } // Stop mocks base method. func (m *MockCompose) Stop(ctx context.Context, projectName string, options api.StopOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Stop", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // Stop indicates an expected call of Stop. func (mr *MockComposeMockRecorder) Stop(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stop", reflect.TypeOf((*MockCompose)(nil).Stop), ctx, projectName, options) } // Top mocks base method. func (m *MockCompose) Top(ctx context.Context, projectName string, services []string) ([]api.ContainerProcSummary, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Top", ctx, projectName, services) ret0, _ := ret[0].([]api.ContainerProcSummary) ret1, _ := ret[1].(error) return ret0, ret1 } // Top indicates an expected call of Top. func (mr *MockComposeMockRecorder) Top(ctx, projectName, services any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Top", reflect.TypeOf((*MockCompose)(nil).Top), ctx, projectName, services) } // UnPause mocks base method. func (m *MockCompose) UnPause(ctx context.Context, projectName string, options api.PauseOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UnPause", ctx, projectName, options) ret0, _ := ret[0].(error) return ret0 } // UnPause indicates an expected call of UnPause. func (mr *MockComposeMockRecorder) UnPause(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnPause", reflect.TypeOf((*MockCompose)(nil).UnPause), ctx, projectName, options) } // Up mocks base method. func (m *MockCompose) Up(ctx context.Context, project *types.Project, options api.UpOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Up", ctx, project, options) ret0, _ := ret[0].(error) return ret0 } // Up indicates an expected call of Up. func (mr *MockComposeMockRecorder) Up(ctx, project, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Up", reflect.TypeOf((*MockCompose)(nil).Up), ctx, project, options) } // Viz mocks base method. func (m *MockCompose) Viz(ctx context.Context, project *types.Project, options api.VizOptions) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Viz", ctx, project, options) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // Viz indicates an expected call of Viz. func (mr *MockComposeMockRecorder) Viz(ctx, project, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Viz", reflect.TypeOf((*MockCompose)(nil).Viz), ctx, project, options) } // Volumes mocks base method. func (m *MockCompose) Volumes(ctx context.Context, project string, options api.VolumesOptions) ([]api.VolumesSummary, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Volumes", ctx, project, options) ret0, _ := ret[0].([]api.VolumesSummary) ret1, _ := ret[1].(error) return ret0, ret1 } // Volumes indicates an expected call of Volumes. func (mr *MockComposeMockRecorder) Volumes(ctx, project, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Volumes", reflect.TypeOf((*MockCompose)(nil).Volumes), ctx, project, options) } // Wait mocks base method. func (m *MockCompose) Wait(ctx context.Context, projectName string, options api.WaitOptions) (int64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Wait", ctx, projectName, options) ret0, _ := ret[0].(int64) ret1, _ := ret[1].(error) return ret0, ret1 } // Wait indicates an expected call of Wait. func (mr *MockComposeMockRecorder) Wait(ctx, projectName, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Wait", reflect.TypeOf((*MockCompose)(nil).Wait), ctx, projectName, options) } // Watch mocks base method. func (m *MockCompose) Watch(ctx context.Context, project *types.Project, options api.WatchOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Watch", ctx, project, options) ret0, _ := ret[0].(error) return ret0 } // Watch indicates an expected call of Watch. func (mr *MockComposeMockRecorder) Watch(ctx, project, options any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Watch", reflect.TypeOf((*MockCompose)(nil).Watch), ctx, project, options) } // MockLogConsumer is a mock of LogConsumer interface. type MockLogConsumer struct { ctrl *gomock.Controller recorder *MockLogConsumerMockRecorder } // MockLogConsumerMockRecorder is the mock recorder for MockLogConsumer. type MockLogConsumerMockRecorder struct { mock *MockLogConsumer } // NewMockLogConsumer creates a new mock instance. func NewMockLogConsumer(ctrl *gomock.Controller) *MockLogConsumer { mock := &MockLogConsumer{ctrl: ctrl} mock.recorder = &MockLogConsumerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockLogConsumer) EXPECT() *MockLogConsumerMockRecorder { return m.recorder } // Err mocks base method. func (m *MockLogConsumer) Err(containerName, message string) { m.ctrl.T.Helper() m.ctrl.Call(m, "Err", containerName, message) } // Err indicates an expected call of Err. func (mr *MockLogConsumerMockRecorder) Err(containerName, message any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Err", reflect.TypeOf((*MockLogConsumer)(nil).Err), containerName, message) } // Log mocks base method. func (m *MockLogConsumer) Log(containerName, message string) { m.ctrl.T.Helper() m.ctrl.Call(m, "Log", containerName, message) } // Log indicates an expected call of Log. func (mr *MockLogConsumerMockRecorder) Log(containerName, message any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Log", reflect.TypeOf((*MockLogConsumer)(nil).Log), containerName, message) } // Status mocks base method. func (m *MockLogConsumer) Status(container, msg string) { m.ctrl.T.Helper() m.ctrl.Call(m, "Status", container, msg) } // Status indicates an expected call of Status. func (mr *MockLogConsumerMockRecorder) Status(container, msg any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Status", reflect.TypeOf((*MockLogConsumer)(nil).Status), container, msg) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/remote/git.go
pkg/remote/git.go
/* Copyright 2020 Docker Compose CLI 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 remote import ( "bufio" "bytes" "context" "fmt" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "github.com/compose-spec/compose-go/v2/cli" "github.com/compose-spec/compose-go/v2/loader" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/command" gitutil "github.com/moby/buildkit/frontend/dockerfile/dfgitutil" "github.com/sirupsen/logrus" "github.com/docker/compose/v5/pkg/api" ) const GIT_REMOTE_ENABLED = "COMPOSE_EXPERIMENTAL_GIT_REMOTE" func gitRemoteLoaderEnabled() (bool, error) { if v := os.Getenv(GIT_REMOTE_ENABLED); v != "" { enabled, err := strconv.ParseBool(v) if err != nil { return false, fmt.Errorf("COMPOSE_EXPERIMENTAL_GIT_REMOTE environment variable expects boolean value: %w", err) } return enabled, err } return true, nil } func NewGitRemoteLoader(dockerCli command.Cli, offline bool) loader.ResourceLoader { return gitRemoteLoader{ dockerCli: dockerCli, offline: offline, known: map[string]string{}, } } type gitRemoteLoader struct { dockerCli command.Cli offline bool known map[string]string } func (g gitRemoteLoader) Accept(path string) bool { _, _, err := gitutil.ParseGitRef(path) return err == nil } var commitSHA = regexp.MustCompile(`^[a-f0-9]{40}$`) func (g gitRemoteLoader) Load(ctx context.Context, path string) (string, error) { enabled, err := gitRemoteLoaderEnabled() if err != nil { return "", err } if !enabled { return "", fmt.Errorf("git remote resource is disabled by %q", GIT_REMOTE_ENABLED) } ref, _, err := gitutil.ParseGitRef(path) if err != nil { return "", err } local, ok := g.known[path] if !ok { if ref.Ref == "" { ref.Ref = "HEAD" // default branch } err = g.resolveGitRef(ctx, path, ref) if err != nil { return "", err } cache, err := cacheDir() if err != nil { return "", fmt.Errorf("initializing remote resource cache: %w", err) } local = filepath.Join(cache, ref.Ref) if _, err := os.Stat(local); os.IsNotExist(err) { if g.offline { return "", nil } err = g.checkout(ctx, local, ref) if err != nil { return "", err } } g.known[path] = local } if ref.SubDir != "" { if err := validateGitSubDir(local, ref.SubDir); err != nil { return "", err } local = filepath.Join(local, ref.SubDir) } stat, err := os.Stat(local) if err != nil { return "", err } if stat.IsDir() { local, err = findFile(cli.DefaultFileNames, local) } return local, err } func (g gitRemoteLoader) Dir(path string) string { return g.known[path] } // validateGitSubDir ensures a subdirectory path is contained within the base directory // and doesn't escape via path traversal. Unlike validatePathInBase for OCI artifacts, // this allows nested directories but prevents traversal outside the base. func validateGitSubDir(base, subDir string) error { cleanSubDir := filepath.Clean(subDir) if filepath.IsAbs(cleanSubDir) { return fmt.Errorf("git subdirectory must be relative, got: %s", subDir) } if cleanSubDir == ".." || strings.HasPrefix(cleanSubDir, "../") || strings.HasPrefix(cleanSubDir, "..\\") { return fmt.Errorf("git subdirectory path traversal detected: %s", subDir) } if len(cleanSubDir) >= 2 && cleanSubDir[1] == ':' { return fmt.Errorf("git subdirectory must be relative, got: %s", subDir) } targetPath := filepath.Join(base, cleanSubDir) cleanBase := filepath.Clean(base) cleanTarget := filepath.Clean(targetPath) // Ensure the target starts with the base path relPath, err := filepath.Rel(cleanBase, cleanTarget) if err != nil { return fmt.Errorf("invalid git subdirectory path: %w", err) } if relPath == ".." || strings.HasPrefix(relPath, "../") || strings.HasPrefix(relPath, "..\\") { return fmt.Errorf("git subdirectory escapes base directory: %s", subDir) } return nil } func (g gitRemoteLoader) resolveGitRef(ctx context.Context, path string, ref *gitutil.GitRef) error { if !commitSHA.MatchString(ref.Ref) { cmd := exec.CommandContext(ctx, "git", "ls-remote", "--exit-code", ref.Remote, ref.Ref) cmd.Env = g.gitCommandEnv() out, err := cmd.CombinedOutput() if err != nil { if cmd.ProcessState.ExitCode() == 2 { return fmt.Errorf("repository does not contain ref %s, output: %q: %w", path, string(out), err) } return fmt.Errorf("failed to access repository at %s:\n %s", ref.Remote, out) } if len(out) < 40 { return fmt.Errorf("unexpected git command output: %q", string(out)) } sha := string(out[:40]) if !commitSHA.MatchString(sha) { return fmt.Errorf("invalid commit sha %q", sha) } ref.Ref = sha } return nil } func (g gitRemoteLoader) checkout(ctx context.Context, path string, ref *gitutil.GitRef) error { err := os.MkdirAll(path, 0o700) if err != nil { return err } err = exec.CommandContext(ctx, "git", "init", path).Run() if err != nil { return err } cmd := exec.CommandContext(ctx, "git", "remote", "add", "origin", ref.Remote) cmd.Dir = path err = cmd.Run() if err != nil { return err } cmd = exec.CommandContext(ctx, "git", "fetch", "--depth=1", "origin", ref.Ref) cmd.Env = g.gitCommandEnv() cmd.Dir = path err = g.run(cmd) if err != nil { return err } cmd = exec.CommandContext(ctx, "git", "checkout", ref.Ref) cmd.Dir = path err = cmd.Run() if err != nil { return err } return nil } func (g gitRemoteLoader) run(cmd *exec.Cmd) error { if logrus.IsLevelEnabled(logrus.DebugLevel) { output, err := cmd.CombinedOutput() scanner := bufio.NewScanner(bytes.NewBuffer(output)) for scanner.Scan() { line := scanner.Text() logrus.Debug(line) } return err } return cmd.Run() } func (g gitRemoteLoader) gitCommandEnv() []string { env := types.NewMapping(os.Environ()) if env["GIT_TERMINAL_PROMPT"] == "" { // Disable prompting for passwords by Git until user explicitly asks for it. env["GIT_TERMINAL_PROMPT"] = "0" } if env["GIT_SSH"] == "" && env["GIT_SSH_COMMAND"] == "" { // Disable any ssh connection pooling by Git and do not attempt to prompt the user. env["GIT_SSH_COMMAND"] = "ssh -o ControlMaster=no -o BatchMode=yes" } v := env.Values() return v } func findFile(names []string, pwd string) (string, error) { for _, n := range names { f := filepath.Join(pwd, n) if fi, err := os.Stat(f); err == nil && !fi.IsDir() { return f, nil } } return "", api.ErrNotFound } var _ loader.ResourceLoader = gitRemoteLoader{}
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/remote/cache_darwin.go
pkg/remote/cache_darwin.go
/* Copyright 2020 Docker Compose CLI 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 remote import ( "os" "path/filepath" ) // Based on https://github.com/adrg/xdg // Licensed under MIT License (MIT) // Copyright (c) 2014 Adrian-George Bostan <adrg@epistack.com> func osDependentCacheDir() (string, error) { home, err := os.UserHomeDir() if err != nil { return "", err } return filepath.Join(home, "Library", "Caches", "docker-compose"), nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/remote/cache.go
pkg/remote/cache.go
/* Copyright 2020 Docker Compose CLI 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 remote import ( "os" "path/filepath" ) func cacheDir() (string, error) { cache, ok := os.LookupEnv("XDG_CACHE_HOME") if ok { return filepath.Join(cache, "docker-compose"), nil } path, err := osDependentCacheDir() if err != nil { return "", err } err = os.MkdirAll(path, 0o700) return path, err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/remote/cache_windows.go
pkg/remote/cache_windows.go
/* Copyright 2020 Docker Compose CLI 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 remote import ( "os" "path/filepath" "golang.org/x/sys/windows" ) // Based on https://github.com/adrg/xdg // Licensed under MIT License (MIT) // Copyright (c) 2014 Adrian-George Bostan <adrg@epistack.com> func osDependentCacheDir() (string, error) { flags := []uint32{windows.KF_FLAG_DEFAULT, windows.KF_FLAG_DEFAULT_PATH} for _, flag := range flags { p, _ := windows.KnownFolderPath(windows.FOLDERID_LocalAppData, flag|windows.KF_FLAG_DONT_VERIFY) if p != "" { return filepath.Join(p, "cache", "docker-compose"), nil } } appData, ok := os.LookupEnv("LOCALAPPDATA") if ok { return filepath.Join(appData, "cache", "docker-compose"), nil } home, err := os.UserHomeDir() if err != nil { return "", err } return filepath.Join(home, "AppData", "Local", "cache", "docker-compose"), nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/remote/oci.go
pkg/remote/oci.go
/* Copyright 2020 Docker Compose CLI 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 remote import ( "context" "encoding/json" "fmt" "os" "path/filepath" "strconv" "strings" "github.com/compose-spec/compose-go/v2/loader" "github.com/containerd/containerd/v2/core/images" "github.com/containerd/containerd/v2/core/remotes" "github.com/distribution/reference" "github.com/docker/cli/cli/command" spec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/docker/compose/v5/internal/oci" "github.com/docker/compose/v5/pkg/api" ) const ( OCI_REMOTE_ENABLED = "COMPOSE_EXPERIMENTAL_OCI_REMOTE" OciPrefix = "oci://" ) // validatePathInBase ensures a file path is contained within the base directory, // as OCI artifacts resources must all live within the same folder. func validatePathInBase(base, unsafePath string) error { // Reject paths with path separators regardless of OS if strings.ContainsAny(unsafePath, "\\/") { return fmt.Errorf("invalid OCI artifact") } // Join the base with the untrusted path targetPath := filepath.Join(base, unsafePath) // Get the directory of the target path targetDir := filepath.Dir(targetPath) // Clean both paths to resolve any .. or . components cleanBase := filepath.Clean(base) cleanTargetDir := filepath.Clean(targetDir) // Check if the target directory is the same as base directory if cleanTargetDir != cleanBase { return fmt.Errorf("invalid OCI artifact") } return nil } func ociRemoteLoaderEnabled() (bool, error) { if v := os.Getenv(OCI_REMOTE_ENABLED); v != "" { enabled, err := strconv.ParseBool(v) if err != nil { return false, fmt.Errorf("COMPOSE_EXPERIMENTAL_OCI_REMOTE environment variable expects boolean value: %w", err) } return enabled, err } return true, nil } func NewOCIRemoteLoader(dockerCli command.Cli, offline bool, options api.OCIOptions) loader.ResourceLoader { return ociRemoteLoader{ dockerCli: dockerCli, offline: offline, known: map[string]string{}, insecureRegistries: options.InsecureRegistries, } } type ociRemoteLoader struct { dockerCli command.Cli offline bool known map[string]string insecureRegistries []string } func (g ociRemoteLoader) Accept(path string) bool { return strings.HasPrefix(path, OciPrefix) } //nolint:gocyclo func (g ociRemoteLoader) Load(ctx context.Context, path string) (string, error) { enabled, err := ociRemoteLoaderEnabled() if err != nil { return "", err } if !enabled { return "", fmt.Errorf("OCI remote resource is disabled by %q", OCI_REMOTE_ENABLED) } if g.offline { return "", nil } local, ok := g.known[path] if !ok { ref, err := reference.ParseDockerRef(path[len(OciPrefix):]) if err != nil { return "", err } resolver := oci.NewResolver(g.dockerCli.ConfigFile(), g.insecureRegistries...) descriptor, content, err := oci.Get(ctx, resolver, ref) if err != nil { return "", fmt.Errorf("failed to pull OCI resource %q: %w", ref, err) } cache, err := cacheDir() if err != nil { return "", fmt.Errorf("initializing remote resource cache: %w", err) } local = filepath.Join(cache, descriptor.Digest.Hex()) if _, err = os.Stat(local); os.IsNotExist(err) { // a Compose application bundle is published as image index if images.IsIndexType(descriptor.MediaType) { var index spec.Index err = json.Unmarshal(content, &index) if err != nil { return "", err } found := false for _, manifest := range index.Manifests { if manifest.ArtifactType != oci.ComposeProjectArtifactType { continue } found = true digested, err := reference.WithDigest(ref, manifest.Digest) if err != nil { return "", err } descriptor, content, err = oci.Get(ctx, resolver, digested) if err != nil { return "", fmt.Errorf("failed to pull OCI resource %q: %w", ref, err) } } if !found { return "", fmt.Errorf("OCI index %s doesn't refer to compose artifacts", ref) } } var manifest spec.Manifest err = json.Unmarshal(content, &manifest) if err != nil { return "", err } err = g.pullComposeFiles(ctx, local, manifest, ref, resolver) if err != nil { // we need to clean up the directory to be sure we won't let empty files present _ = os.RemoveAll(local) return "", err } } g.known[path] = local } return filepath.Join(local, "compose.yaml"), nil } func (g ociRemoteLoader) Dir(path string) string { return g.known[path] } func (g ociRemoteLoader) pullComposeFiles(ctx context.Context, local string, manifest spec.Manifest, ref reference.Named, resolver remotes.Resolver) error { err := os.MkdirAll(local, 0o700) if err != nil { return err } if (manifest.ArtifactType != "" && manifest.ArtifactType != oci.ComposeProjectArtifactType) || (manifest.ArtifactType == "" && manifest.Config.MediaType != oci.ComposeEmptyConfigMediaType) { return fmt.Errorf("%s is not a compose project OCI artifact, but %s", ref.String(), manifest.ArtifactType) } for i, layer := range manifest.Layers { digested, err := reference.WithDigest(ref, layer.Digest) if err != nil { return err } _, content, err := oci.Get(ctx, resolver, digested) if err != nil { return err } switch layer.MediaType { case oci.ComposeYAMLMediaType: if err := writeComposeFile(layer, i, local, content); err != nil { return err } case oci.ComposeEnvFileMediaType: if err := writeEnvFile(layer, local, content); err != nil { return err } case oci.ComposeEmptyConfigMediaType: } } return nil } func writeComposeFile(layer spec.Descriptor, i int, local string, content []byte) error { file := "compose.yaml" if _, ok := layer.Annotations["com.docker.compose.extends"]; ok { file = layer.Annotations["com.docker.compose.file"] if err := validatePathInBase(local, file); err != nil { return err } } f, err := os.OpenFile(filepath.Join(local, file), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600) if err != nil { return err } defer func() { _ = f.Close() }() if _, ok := layer.Annotations["com.docker.compose.file"]; i > 0 && ok { _, err := f.Write([]byte("\n---\n")) if err != nil { return err } } _, err = f.Write(content) return err } func writeEnvFile(layer spec.Descriptor, local string, content []byte) error { envfilePath, ok := layer.Annotations["com.docker.compose.envfile"] if !ok { return fmt.Errorf("missing annotation com.docker.compose.envfile in layer %q", layer.Digest) } if err := validatePathInBase(local, envfilePath); err != nil { return err } otherFile, err := os.Create(filepath.Join(local, envfilePath)) if err != nil { return err } defer func() { _ = otherFile.Close() }() _, err = otherFile.Write(content) return err } var _ loader.ResourceLoader = ociRemoteLoader{}
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/remote/oci_test.go
pkg/remote/oci_test.go
/* Copyright 2020 Docker Compose CLI 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 remote import ( "path/filepath" "testing" spec "github.com/opencontainers/image-spec/specs-go/v1" "gotest.tools/v3/assert" ) func TestValidatePathInBase(t *testing.T) { base := "/tmp/cache/compose" tests := []struct { name string unsafePath string wantErr bool }{ { name: "valid simple filename", unsafePath: "compose.yaml", wantErr: false, }, { name: "valid hashed filename", unsafePath: "f8f9ede3d201ec37d5a5e3a77bbadab79af26035e53135e19571f50d541d390c.yaml", wantErr: false, }, { name: "valid env file", unsafePath: ".env", wantErr: false, }, { name: "valid env file with suffix", unsafePath: ".env.prod", wantErr: false, }, { name: "unix path traversal", unsafePath: "../../../etc/passwd", wantErr: true, }, { name: "windows path traversal", unsafePath: "..\\..\\..\\windows\\system32\\config\\sam", wantErr: true, }, { name: "subdirectory unix", unsafePath: "config/base.yaml", wantErr: true, }, { name: "subdirectory windows", unsafePath: "config\\base.yaml", wantErr: true, }, { name: "absolute unix path", unsafePath: "/etc/passwd", wantErr: true, }, { name: "absolute windows path", unsafePath: "C:\\windows\\system32\\config\\sam", wantErr: true, }, { name: "parent reference only", unsafePath: "..", wantErr: true, }, { name: "mixed separators", unsafePath: "config/sub\\file.yaml", wantErr: true, }, { name: "filename with spaces", unsafePath: "my file.yaml", wantErr: false, }, { name: "filename with special chars", unsafePath: "file-name_v1.2.3.yaml", wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := validatePathInBase(base, tt.unsafePath) if (err != nil) != tt.wantErr { targetPath := filepath.Join(base, tt.unsafePath) targetDir := filepath.Dir(targetPath) t.Errorf("validatePathInBase(%q, %q) error = %v, wantErr %v\ntargetDir=%q base=%q", base, tt.unsafePath, err, tt.wantErr, targetDir, base) } }) } } func TestWriteComposeFileWithExtendsPathTraversal(t *testing.T) { tmpDir := t.TempDir() // Create a layer with com.docker.compose.extends=true and a path traversal attempt layer := spec.Descriptor{ MediaType: "application/vnd.docker.compose.file.v1+yaml", Digest: "sha256:test123", Size: 100, Annotations: map[string]string{ "com.docker.compose.extends": "true", "com.docker.compose.file": "../other", }, } content := []byte("services:\n test:\n image: nginx\n") // writeComposeFile should return an error due to path traversal err := writeComposeFile(layer, 0, tmpDir, content) assert.Error(t, err, "invalid OCI artifact") }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/remote/cache_unix.go
pkg/remote/cache_unix.go
//go:build linux || openbsd || freebsd /* Copyright 2020 Docker Compose CLI 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 remote import ( "os" "path/filepath" ) // Based on https://github.com/adrg/xdg // Licensed under MIT License (MIT) // Copyright (c) 2014 Adrian-George Bostan <adrg@epistack.com> func osDependentCacheDir() (string, error) { home, err := os.UserHomeDir() if err != nil { return "", err } return filepath.Join(home, ".cache", "docker-compose"), nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/remote/git_test.go
pkg/remote/git_test.go
/* Copyright 2020 Docker Compose CLI 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 remote import ( "testing" "gotest.tools/v3/assert" ) func TestValidateGitSubDir(t *testing.T) { base := "/tmp/cache/compose/abc123def456" tests := []struct { name string subDir string wantErr bool }{ { name: "valid simple directory", subDir: "examples", wantErr: false, }, { name: "valid nested directory", subDir: "examples/nginx", wantErr: false, }, { name: "valid deeply nested directory", subDir: "examples/web/frontend/config", wantErr: false, }, { name: "valid current directory", subDir: ".", wantErr: false, }, { name: "valid directory with redundant separators", subDir: "examples//nginx", wantErr: false, }, { name: "valid directory with dots in name", subDir: "examples/nginx.conf.d", wantErr: false, }, { name: "path traversal - parent directory", subDir: "..", wantErr: true, }, { name: "path traversal - multiple parent directories", subDir: "../../../etc/passwd", wantErr: true, }, { name: "path traversal - deeply nested escape", subDir: "../../../../../../../tmp/pwned", wantErr: true, }, { name: "path traversal - mixed with valid path", subDir: "examples/../../etc/passwd", wantErr: true, }, { name: "path traversal - at the end", subDir: "examples/..", wantErr: false, // This resolves to "." which is the current directory, safe }, { name: "path traversal - in the middle", subDir: "examples/../../../etc/passwd", wantErr: true, }, { name: "path traversal - windows style", subDir: "..\\..\\..\\windows\\system32", wantErr: true, }, { name: "absolute unix path", subDir: "/etc/passwd", wantErr: true, }, { name: "absolute windows path", subDir: "C:\\windows\\system32\\config\\sam", wantErr: true, }, { name: "absolute path with home directory", subDir: "/home/user/.ssh/id_rsa", wantErr: true, }, { name: "normalized path that would escape", subDir: "./../../etc/passwd", wantErr: true, }, { name: "directory name with three dots", subDir: ".../config", wantErr: false, }, { name: "directory name with four dots", subDir: "..../config", wantErr: false, }, { name: "directory name with five dots", subDir: "...../etc/passwd", wantErr: false, // ".....'' is a valid directory name, not path traversal }, { name: "directory name starting with two dots and letter", subDir: "..foo/bar", wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := validateGitSubDir(base, tt.subDir) if (err != nil) != tt.wantErr { t.Errorf("validateGitSubDir(%q, %q) error = %v, wantErr %v", base, tt.subDir, err, tt.wantErr) } }) } } // TestValidateGitSubDirSecurityScenarios tests specific security scenarios func TestValidateGitSubDirSecurityScenarios(t *testing.T) { base := "/var/cache/docker-compose/git/1234567890abcdef" // Test the exact vulnerability scenario from the issue t.Run("CVE scenario - /tmp traversal", func(t *testing.T) { maliciousPath := "../../../../../../../tmp/pwned" err := validateGitSubDir(base, maliciousPath) assert.ErrorContains(t, err, "path traversal") }) // Test variations of the attack t.Run("CVE scenario - /etc traversal", func(t *testing.T) { maliciousPath := "../../../../../../../../etc/passwd" err := validateGitSubDir(base, maliciousPath) assert.ErrorContains(t, err, "path traversal") }) // Test that legitimate nested paths still work t.Run("legitimate nested path", func(t *testing.T) { validPath := "examples/docker-compose/nginx/config" err := validateGitSubDir(base, validPath) assert.NilError(t, err) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/utils/writer_test.go
pkg/utils/writer_test.go
/* Copyright 2020 Docker Compose CLI 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 utils import ( "testing" "gotest.tools/v3/assert" ) //nolint:errcheck func TestSplitWriter(t *testing.T) { var lines []string w := GetWriter(func(line string) { lines = append(lines, line) }) w.Write([]byte("h")) w.Write([]byte("e")) w.Write([]byte("l")) w.Write([]byte("l")) w.Write([]byte("o")) w.Write([]byte("\n")) w.Write([]byte("world!\n")) assert.DeepEqual(t, lines, []string{"hello", "world!"}) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/utils/safebuffer.go
pkg/utils/safebuffer.go
/* Copyright 2020 Docker Compose CLI 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 utils import ( "bytes" "strings" "sync" "testing" "time" "github.com/stretchr/testify/require" ) // SafeBuffer is a thread safe version of bytes.Buffer type SafeBuffer struct { m sync.RWMutex b bytes.Buffer } // Read is a thread safe version of bytes.Buffer::Read func (b *SafeBuffer) Read(p []byte) (n int, err error) { b.m.RLock() defer b.m.RUnlock() return b.b.Read(p) } // Write is a thread safe version of bytes.Buffer::Write func (b *SafeBuffer) Write(p []byte) (n int, err error) { b.m.Lock() defer b.m.Unlock() return b.b.Write(p) } // String is a thread safe version of bytes.Buffer::String func (b *SafeBuffer) String() string { b.m.RLock() defer b.m.RUnlock() return b.b.String() } // Bytes is a thread safe version of bytes.Buffer::Bytes func (b *SafeBuffer) Bytes() []byte { b.m.RLock() defer b.m.RUnlock() return b.b.Bytes() } // RequireEventuallyContains is a thread safe eventual checker for the buffer content func (b *SafeBuffer) RequireEventuallyContains(t testing.TB, v string) { t.Helper() var bufContents strings.Builder require.Eventuallyf(t, func() bool { b.m.Lock() defer b.m.Unlock() if _, err := b.b.WriteTo(&bufContents); err != nil { require.FailNowf(t, "Failed to copy from buffer", "Error: %v", err) } return strings.Contains(bufContents.String(), v) }, 2*time.Second, 20*time.Millisecond, "Buffer did not contain %q\n============\n%s\n============", v, &bufContents) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/utils/writer.go
pkg/utils/writer.go
/* Copyright 2020 Docker Compose CLI 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 utils import ( "bytes" "io" ) // GetWriter creates an io.Writer that will actually split by line and format by LogConsumer func GetWriter(consumer func(string)) io.WriteCloser { return &splitWriter{ buffer: bytes.Buffer{}, consumer: consumer, } } type splitWriter struct { buffer bytes.Buffer consumer func(string) } // Write implements io.Writer. joins all input, splits on the separator and yields each chunk func (s *splitWriter) Write(b []byte) (int, error) { n, err := s.buffer.Write(b) if err != nil { return n, err } for { b = s.buffer.Bytes() index := bytes.Index(b, []byte{'\n'}) if index < 0 { break } line := s.buffer.Next(index + 1) s.consumer(string(line[:len(line)-1])) } return n, nil } func (s *splitWriter) Close() error { b := s.buffer.Bytes() if len(b) == 0 { return nil } s.consumer(string(b)) return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/utils/set_test.go
pkg/utils/set_test.go
/* Copyright 2022 Docker Compose CLI 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 utils import ( "testing" "github.com/stretchr/testify/require" ) func TestSet_Has(t *testing.T) { x := NewSet[string]("value") require.True(t, x.Has("value")) require.False(t, x.Has("VALUE")) } func TestSet_Diff(t *testing.T) { a := NewSet[int](1, 2) b := NewSet[int](2, 3) require.ElementsMatch(t, []int{1}, a.Diff(b).Elements()) require.ElementsMatch(t, []int{3}, b.Diff(a).Elements()) } func TestSet_Union(t *testing.T) { a := NewSet[int](1, 2) b := NewSet[int](2, 3) require.ElementsMatch(t, []int{1, 2, 3}, a.Union(b).Elements()) require.ElementsMatch(t, []int{1, 2, 3}, b.Union(a).Elements()) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/utils/set.go
pkg/utils/set.go
/* Copyright 2020 Docker Compose CLI 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 utils type Set[T comparable] map[T]struct{} func NewSet[T comparable](v ...T) Set[T] { if len(v) == 0 { return make(Set[T]) } out := make(Set[T], len(v)) for i := range v { out.Add(v[i]) } return out } func (s Set[T]) Has(v T) bool { _, ok := s[v] return ok } func (s Set[T]) Add(v T) { s[v] = struct{}{} } func (s Set[T]) AddAll(v ...T) { for _, e := range v { s[e] = struct{}{} } } func (s Set[T]) Remove(v T) bool { _, ok := s[v] if ok { delete(s, v) } return ok } func (s Set[T]) Clear() { for v := range s { delete(s, v) } } func (s Set[T]) Elements() []T { elements := make([]T, 0, len(s)) for v := range s { elements = append(elements, v) } return elements } func (s Set[T]) RemoveAll(elements ...T) { for _, e := range elements { s.Remove(e) } } func (s Set[T]) Diff(other Set[T]) Set[T] { out := make(Set[T]) for k := range s { if _, ok := other[k]; !ok { out[k] = struct{}{} } } return out } func (s Set[T]) Union(other Set[T]) Set[T] { out := make(Set[T]) for k := range s { out[k] = struct{}{} } for k := range other { out[k] = struct{}{} } return out }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/utils/stringutils.go
pkg/utils/stringutils.go
/* Copyright 2020 Docker Compose CLI 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 utils import ( "strconv" "strings" ) // StringToBool converts a string to a boolean ignoring errors func StringToBool(s string) bool { s = strings.ToLower(strings.TrimSpace(s)) if s == "y" { return true } b, _ := strconv.ParseBool(s) return b }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/utils/durationutils.go
pkg/utils/durationutils.go
/* Copyright 2020 Docker Compose CLI 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 utils import "time" func DurationSecondToInt(d *time.Duration) *int { if d == nil { return nil } timeout := int(d.Seconds()) return &timeout }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/cancel_test.go
pkg/e2e/cancel_test.go
//go:build !windows /* Copyright 2020 Docker Compose CLI 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 e2e import ( "context" "fmt" "os/exec" "strings" "syscall" "testing" "time" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" "github.com/docker/compose/v5/pkg/utils" ) func TestComposeCancel(t *testing.T) { c := NewParallelCLI(t) t.Run("metrics on cancel Compose build", func(t *testing.T) { const buildProjectPath = "fixtures/build-infinite/compose.yaml" ctx, cancel := context.WithCancel(context.Background()) defer cancel() // require a separate groupID from the process running tests, in order to simulate ctrl+C from a terminal. // sending kill signal var stdout, stderr utils.SafeBuffer cmd, err := StartWithNewGroupID( ctx, c.NewDockerComposeCmd(t, "-f", buildProjectPath, "build", "--progress", "plain"), &stdout, &stderr, ) assert.NilError(t, err) processDone := make(chan error, 1) go func() { defer close(processDone) processDone <- cmd.Wait() }() c.WaitForCondition(t, func() (bool, string) { out := stdout.String() errors := stderr.String() return strings.Contains(out, "RUN sleep infinity"), fmt.Sprintf("'RUN sleep infinity' not found in : \n%s\nStderr: \n%s\n", out, errors) }, 30*time.Second, 1*time.Second) // simulate Ctrl-C : send signal to processGroup, children will have same groupId by default err = syscall.Kill(-cmd.Process.Pid, syscall.SIGINT) assert.NilError(t, err) select { case <-ctx.Done(): t.Fatal("test context canceled") case err := <-processDone: // TODO(milas): Compose should really not return exit code 130 here, // this is an old hack for the compose-cli wrapper assert.Error(t, err, "exit status 130", "STDOUT:\n%s\nSTDERR:\n%s\n", stdout.String(), stderr.String()) case <-time.After(10 * time.Second): t.Fatal("timeout waiting for Compose exit") } }) } func StartWithNewGroupID(ctx context.Context, command icmd.Cmd, stdout *utils.SafeBuffer, stderr *utils.SafeBuffer) (*exec.Cmd, error) { cmd := exec.CommandContext(ctx, command.Command[0], command.Command[1:]...) cmd.Env = command.Env cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} if stdout != nil { cmd.Stdout = stdout } if stderr != nil { cmd.Stderr = stderr } err := cmd.Start() return cmd, err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/wait_test.go
pkg/e2e/wait_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "strings" "testing" "time" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestWaitOnFaster(t *testing.T) { const projectName = "e2e-wait-faster" c := NewParallelCLI(t) cleanup := func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--timeout=0", "--remove-orphans") } t.Cleanup(cleanup) cleanup() c.RunDockerComposeCmd(t, "-f", "./fixtures/wait/compose.yaml", "--project-name", projectName, "up", "-d") c.RunDockerComposeCmd(t, "--project-name", projectName, "wait", "faster") } func TestWaitOnSlower(t *testing.T) { const projectName = "e2e-wait-slower" c := NewParallelCLI(t) cleanup := func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--timeout=0", "--remove-orphans") } t.Cleanup(cleanup) cleanup() c.RunDockerComposeCmd(t, "-f", "./fixtures/wait/compose.yaml", "--project-name", projectName, "up", "-d") c.RunDockerComposeCmd(t, "--project-name", projectName, "wait", "slower") } func TestWaitOnInfinity(t *testing.T) { const projectName = "e2e-wait-infinity" c := NewParallelCLI(t) cleanup := func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--timeout=0", "--remove-orphans") } t.Cleanup(cleanup) cleanup() c.RunDockerComposeCmd(t, "-f", "./fixtures/wait/compose.yaml", "--project-name", projectName, "up", "-d") cmd := c.NewDockerComposeCmd(t, "--project-name", projectName, "wait", "infinity") r := icmd.StartCmd(cmd) assert.NilError(t, r.Error) t.Cleanup(func() { if r.Cmd.Process != nil { _ = r.Cmd.Process.Kill() } }) finished := make(chan struct{}) ticker := time.NewTicker(7 * time.Second) go func() { _ = r.Cmd.Wait() finished <- struct{}{} }() select { case <-finished: t.Fatal("wait infinity should not finish") case <-ticker.C: } } func TestWaitAndDrop(t *testing.T) { const projectName = "e2e-wait-and-drop" c := NewParallelCLI(t) cleanup := func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--timeout=0", "--remove-orphans") } t.Cleanup(cleanup) cleanup() c.RunDockerComposeCmd(t, "-f", "./fixtures/wait/compose.yaml", "--project-name", projectName, "up", "-d") c.RunDockerComposeCmd(t, "--project-name", projectName, "wait", "--down-project", "faster") res := c.RunDockerCmd(t, "ps", "--all") assert.Assert(t, !strings.Contains(res.Combined(), projectName), res.Combined()) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/expose_test.go
pkg/e2e/expose_test.go
//go:build !windows /* Copyright 2020 Docker Compose CLI 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 e2e import ( "os" "path/filepath" "testing" "gotest.tools/v3/assert" ) // see https://github.com/docker/compose/issues/13378 func TestExposeRange(t *testing.T) { c := NewParallelCLI(t) f := filepath.Join(t.TempDir(), "compose.yaml") err := os.WriteFile(f, []byte(` name: test-expose-range services: test: image: alpine expose: - "9091-9092" `), 0o644) assert.NilError(t, err) t.Cleanup(func() { c.cleanupWithDown(t, "test-expose-range") }) c.RunDockerComposeCmd(t, "-f", f, "up") }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/watch_test.go
pkg/e2e/watch_test.go
/* Copyright 2023 Docker Compose CLI 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 e2e import ( "bytes" "crypto/rand" "fmt" "os" "path/filepath" "strings" "sync/atomic" "testing" "time" "github.com/stretchr/testify/require" "gotest.tools/v3/assert" "gotest.tools/v3/assert/cmp" "gotest.tools/v3/icmd" "gotest.tools/v3/poll" ) func TestWatch(t *testing.T) { services := []string{"alpine", "busybox", "debian"} for _, svcName := range services { t.Run(svcName, func(t *testing.T) { t.Helper() doTest(t, svcName) }) } } func TestRebuildOnDotEnvWithExternalNetwork(t *testing.T) { const projectName = "test_rebuild_on_dotenv_with_external_network" const svcName = "ext-alpine" containerName := strings.Join([]string{projectName, svcName, "1"}, "-") const networkName = "e2e-watch-external_network_test" const dotEnvFilepath = "./fixtures/watch/.env" c := NewCLI(t, WithEnv( "COMPOSE_PROJECT_NAME="+projectName, "COMPOSE_FILE=./fixtures/watch/with-external-network.yaml", )) cleanup := func() { c.RunDockerComposeCmdNoCheck(t, "down", "--remove-orphans", "--volumes", "--rmi=local") c.RunDockerOrExitError(t, "network", "rm", networkName) os.Remove(dotEnvFilepath) //nolint:errcheck } cleanup() t.Log("create network that is referenced by the container we're testing") c.RunDockerCmd(t, "network", "create", networkName) res := c.RunDockerCmd(t, "network", "ls") assert.Assert(t, !strings.Contains(res.Combined(), projectName), res.Combined()) t.Log("create a dotenv file that will be used to trigger the rebuild") err := os.WriteFile(dotEnvFilepath, []byte("HELLO=WORLD"), 0o666) assert.NilError(t, err) _, err = os.ReadFile(dotEnvFilepath) assert.NilError(t, err) // TODO: refactor this duplicated code into frameworks? Maybe? t.Log("starting docker compose watch") cmd := c.NewDockerComposeCmd(t, "--verbose", "watch", svcName) // stream output since watch runs in the background cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr r := icmd.StartCmd(cmd) require.NoError(t, r.Error) var testComplete atomic.Bool go func() { // if the process exits abnormally before the test is done, fail the test if err := r.Cmd.Wait(); err != nil && !t.Failed() && !testComplete.Load() { assert.Check(t, cmp.Nil(err)) } }() t.Log("wait for watch to start watching") c.WaitForCondition(t, func() (bool, string) { out := r.String() return strings.Contains(out, "Watch enabled"), "watch not started" }, 30*time.Second, 1*time.Second) pn := c.RunDockerCmd(t, "inspect", containerName, "-f", "{{ .HostConfig.NetworkMode }}") assert.Equal(t, strings.TrimSpace(pn.Stdout()), networkName) t.Log("create a dotenv file that will be used to trigger the rebuild") err = os.WriteFile(dotEnvFilepath, []byte("HELLO=WORLD\nTEST=REBUILD"), 0o666) assert.NilError(t, err) _, err = os.ReadFile(dotEnvFilepath) assert.NilError(t, err) // NOTE: are there any other ways to check if the container has been rebuilt? t.Log("check if the container has been rebuild") c.WaitForCondition(t, func() (bool, string) { out := r.String() if strings.Count(out, "batch complete") != 1 { return false, fmt.Sprintf("container %s was not rebuilt", containerName) } return true, fmt.Sprintf("container %s was rebuilt", containerName) }, 30*time.Second, 1*time.Second) pn2 := c.RunDockerCmd(t, "inspect", containerName, "-f", "{{ .HostConfig.NetworkMode }}") assert.Equal(t, strings.TrimSpace(pn2.Stdout()), networkName) assert.Check(t, !strings.Contains(r.Combined(), "Application failed to start after update")) t.Cleanup(cleanup) t.Cleanup(func() { // IMPORTANT: watch doesn't exit on its own, don't leak processes! if r.Cmd.Process != nil { t.Logf("Killing watch process: pid[%d]", r.Cmd.Process.Pid) _ = r.Cmd.Process.Kill() } }) testComplete.Store(true) } // NOTE: these tests all share a single Compose file but are safe to run // concurrently (though that's not recommended). func doTest(t *testing.T, svcName string) { tmpdir := t.TempDir() dataDir := filepath.Join(tmpdir, "data") configDir := filepath.Join(tmpdir, "config") writeTestFile := func(name, contents, sourceDir string) { t.Helper() dest := filepath.Join(sourceDir, name) require.NoError(t, os.MkdirAll(filepath.Dir(dest), 0o700)) t.Logf("writing %q to %q", contents, dest) require.NoError(t, os.WriteFile(dest, []byte(contents+"\n"), 0o600)) } writeDataFile := func(name, contents string) { writeTestFile(name, contents, dataDir) } composeFilePath := filepath.Join(tmpdir, "compose.yaml") CopyFile(t, filepath.Join("fixtures", "watch", "compose.yaml"), composeFilePath) projName := "e2e-watch-" + svcName env := []string{ "COMPOSE_FILE=" + composeFilePath, "COMPOSE_PROJECT_NAME=" + projName, } cli := NewCLI(t, WithEnv(env...)) // important that --rmi is used to prune the images and ensure that watch builds on launch defer cli.cleanupWithDown(t, projName, "--rmi=local") cmd := cli.NewDockerComposeCmd(t, "--verbose", "watch", svcName) // stream output since watch runs in the background cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr r := icmd.StartCmd(cmd) require.NoError(t, r.Error) t.Cleanup(func() { // IMPORTANT: watch doesn't exit on its own, don't leak processes! if r.Cmd.Process != nil { t.Logf("Killing watch process: pid[%d]", r.Cmd.Process.Pid) _ = r.Cmd.Process.Kill() } }) var testComplete atomic.Bool go func() { // if the process exits abnormally before the test is done, fail the test if err := r.Cmd.Wait(); err != nil && !t.Failed() && !testComplete.Load() { assert.Check(t, cmp.Nil(err)) } }() require.NoError(t, os.Mkdir(dataDir, 0o700)) checkFileContents := func(path string, contents string) poll.Check { return func(pollLog poll.LogT) poll.Result { if r.Cmd.ProcessState != nil { return poll.Error(fmt.Errorf("watch process exited early: %s", r.Cmd.ProcessState)) } res := icmd.RunCmd(cli.NewDockerComposeCmd(t, "exec", svcName, "cat", path)) if strings.Contains(res.Stdout(), contents) { return poll.Success() } return poll.Continue("%v", res.Combined()) } } waitForFlush := func() { b := make([]byte, 32) _, _ = rand.Read(b) sentinelVal := fmt.Sprintf("%x", b) writeDataFile("wait.txt", sentinelVal) poll.WaitOn(t, checkFileContents("/app/data/wait.txt", sentinelVal)) } t.Logf("Writing to a file until Compose watch is up and running") poll.WaitOn(t, func(t poll.LogT) poll.Result { writeDataFile("hello.txt", "hello world") return checkFileContents("/app/data/hello.txt", "hello world")(t) }, poll.WithDelay(time.Second)) t.Logf("Modifying file contents") writeDataFile("hello.txt", "hello watch") poll.WaitOn(t, checkFileContents("/app/data/hello.txt", "hello watch")) t.Logf("Deleting file") require.NoError(t, os.Remove(filepath.Join(dataDir, "hello.txt"))) waitForFlush() cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/hello.txt"). Assert(t, icmd.Expected{ ExitCode: 1, Err: "No such file or directory", }) t.Logf("Writing to ignored paths") writeDataFile("data.foo", "ignored") writeDataFile(filepath.Join("ignored", "hello.txt"), "ignored") waitForFlush() cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/data.foo"). Assert(t, icmd.Expected{ ExitCode: 1, Err: "No such file or directory", }) cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/ignored"). Assert(t, icmd.Expected{ ExitCode: 1, Err: "No such file or directory", }) t.Logf("Creating subdirectory") require.NoError(t, os.Mkdir(filepath.Join(dataDir, "subdir"), 0o700)) waitForFlush() cli.RunDockerComposeCmd(t, "exec", svcName, "stat", "/app/data/subdir") t.Logf("Writing to file in subdirectory") writeDataFile(filepath.Join("subdir", "file.txt"), "a") poll.WaitOn(t, checkFileContents("/app/data/subdir/file.txt", "a")) t.Logf("Writing to file multiple times") writeDataFile(filepath.Join("subdir", "file.txt"), "x") writeDataFile(filepath.Join("subdir", "file.txt"), "y") writeDataFile(filepath.Join("subdir", "file.txt"), "z") poll.WaitOn(t, checkFileContents("/app/data/subdir/file.txt", "z")) writeDataFile(filepath.Join("subdir", "file.txt"), "z") writeDataFile(filepath.Join("subdir", "file.txt"), "y") writeDataFile(filepath.Join("subdir", "file.txt"), "x") poll.WaitOn(t, checkFileContents("/app/data/subdir/file.txt", "x")) t.Logf("Deleting directory") require.NoError(t, os.RemoveAll(filepath.Join(dataDir, "subdir"))) waitForFlush() cli.RunDockerComposeCmdNoCheck(t, "exec", svcName, "stat", "/app/data/subdir"). Assert(t, icmd.Expected{ ExitCode: 1, Err: "No such file or directory", }) t.Logf("Sync and restart use case") require.NoError(t, os.Mkdir(configDir, 0o700)) writeTestFile("file.config", "This is an updated config file", configDir) checkRestart := func(state string) poll.Check { return func(pollLog poll.LogT) poll.Result { if strings.Contains(r.Combined(), state) { return poll.Success() } return poll.Continue("%v", r.Combined()) } } poll.WaitOn(t, checkRestart(fmt.Sprintf("service(s) [%q] restarted", svcName))) poll.WaitOn(t, checkFileContents("/app/config/file.config", "This is an updated config file")) testComplete.Store(true) } func TestWatchExec(t *testing.T) { c := NewCLI(t) const projectName = "test_watch_exec" defer c.cleanupWithDown(t, projectName) tmpdir := t.TempDir() composeFilePath := filepath.Join(tmpdir, "compose.yaml") CopyFile(t, filepath.Join("fixtures", "watch", "exec.yaml"), composeFilePath) cmd := c.NewDockerComposeCmd(t, "-p", projectName, "-f", composeFilePath, "up", "--watch") buffer := bytes.NewBuffer(nil) cmd.Stdout = buffer watch := icmd.StartCmd(cmd) poll.WaitOn(t, func(l poll.LogT) poll.Result { out := buffer.String() if strings.Contains(out, "64 bytes from") { return poll.Success() } return poll.Continue("%v", watch.Stdout()) }) t.Logf("Create new file") testFile := filepath.Join(tmpdir, "test") require.NoError(t, os.WriteFile(testFile, []byte("test\n"), 0o600)) poll.WaitOn(t, func(l poll.LogT) poll.Result { out := buffer.String() if strings.Contains(out, "SUCCESS") { return poll.Success() } return poll.Continue("%v", out) }) c.RunDockerComposeCmdNoCheck(t, "-p", projectName, "kill", "-s", "9") } func TestWatchMultiServices(t *testing.T) { c := NewCLI(t) const projectName = "test_watch_rebuild" defer c.cleanupWithDown(t, projectName) tmpdir := t.TempDir() composeFilePath := filepath.Join(tmpdir, "compose.yaml") CopyFile(t, filepath.Join("fixtures", "watch", "rebuild.yaml"), composeFilePath) testFile := filepath.Join(tmpdir, "test") require.NoError(t, os.WriteFile(testFile, []byte("test"), 0o600)) cmd := c.NewDockerComposeCmd(t, "-p", projectName, "-f", composeFilePath, "up", "--watch") buffer := bytes.NewBuffer(nil) cmd.Stdout = buffer watch := icmd.StartCmd(cmd) poll.WaitOn(t, func(l poll.LogT) poll.Result { if strings.Contains(watch.Stdout(), "Attaching to ") { return poll.Success() } return poll.Continue("%v", watch.Stdout()) }) waitRebuild := func(service string, expected string) { poll.WaitOn(t, func(l poll.LogT) poll.Result { cat := c.RunDockerComposeCmdNoCheck(t, "-p", projectName, "exec", service, "cat", "/data/"+service) if strings.Contains(cat.Stdout(), expected) { return poll.Success() } return poll.Continue("%v", cat.Combined()) }) } waitRebuild("a", "test") waitRebuild("b", "test") waitRebuild("c", "test") require.NoError(t, os.WriteFile(testFile, []byte("updated"), 0o600)) waitRebuild("a", "updated") waitRebuild("b", "updated") waitRebuild("c", "updated") c.RunDockerComposeCmdNoCheck(t, "-p", projectName, "kill", "-s", "9") } func TestWatchIncludes(t *testing.T) { c := NewCLI(t) const projectName = "test_watch_includes" defer c.cleanupWithDown(t, projectName) tmpdir := t.TempDir() composeFilePath := filepath.Join(tmpdir, "compose.yaml") CopyFile(t, filepath.Join("fixtures", "watch", "include.yaml"), composeFilePath) cmd := c.NewDockerComposeCmd(t, "-p", projectName, "-f", composeFilePath, "up", "--watch") buffer := bytes.NewBuffer(nil) cmd.Stdout = buffer watch := icmd.StartCmd(cmd) poll.WaitOn(t, func(l poll.LogT) poll.Result { if strings.Contains(watch.Stdout(), "Attaching to ") { return poll.Success() } return poll.Continue("%v", watch.Stdout()) }) require.NoError(t, os.WriteFile(filepath.Join(tmpdir, "B.test"), []byte("test"), 0o600)) require.NoError(t, os.WriteFile(filepath.Join(tmpdir, "A.test"), []byte("test"), 0o600)) poll.WaitOn(t, func(l poll.LogT) poll.Result { cat := c.RunDockerComposeCmdNoCheck(t, "-p", projectName, "exec", "a", "ls", "/data/") if strings.Contains(cat.Stdout(), "A.test") { assert.Check(t, !strings.Contains(cat.Stdout(), "B.test")) return poll.Success() } return poll.Continue("%v", cat.Combined()) }) c.RunDockerComposeCmdNoCheck(t, "-p", projectName, "kill", "-s", "9") } func TestCheckWarningXInitialSyn(t *testing.T) { c := NewCLI(t) const projectName = "test_watch_warn_initial_syn" defer c.cleanupWithDown(t, projectName) tmpdir := t.TempDir() composeFilePath := filepath.Join(tmpdir, "compose.yaml") CopyFile(t, filepath.Join("fixtures", "watch", "x-initialSync.yaml"), composeFilePath) cmd := c.NewDockerComposeCmd(t, "-p", projectName, "-f", composeFilePath, "--verbose", "up", "--watch") buffer := bytes.NewBuffer(nil) cmd.Stdout = buffer watch := icmd.StartCmd(cmd) poll.WaitOn(t, func(l poll.LogT) poll.Result { if strings.Contains(watch.Combined(), "x-initialSync is DEPRECATED, please use the official `initial_sync` attribute") { return poll.Success() } return poll.Continue("%v", watch.Stdout()) }) c.RunDockerComposeCmdNoCheck(t, "-p", projectName, "kill", "-s", "9") }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/healthcheck_test.go
pkg/e2e/healthcheck_test.go
/* Copyright 2023 Docker Compose CLI 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 e2e import ( "strings" "testing" "time" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestStartInterval(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-start-interval" t.Cleanup(func() { c.cleanupWithDown(t, projectName) }) res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/start_interval/compose.yaml", "--project-name", projectName, "up", "--wait", "-d", "error") res.Assert(t, icmd.Expected{ExitCode: 1, Err: "healthcheck.start_interval requires healthcheck.start_period to be set"}) timeout := time.After(30 * time.Second) done := make(chan bool) go func() { //nolint:nolintlint,testifylint // helper asserts inside goroutine; acceptable in this e2e test res := c.RunDockerComposeCmd(t, "-f", "fixtures/start_interval/compose.yaml", "--project-name", projectName, "up", "--wait", "-d", "test") out := res.Combined() assert.Assert(t, strings.Contains(out, "Healthy"), out) done <- true }() select { case <-timeout: t.Fatal("test did not finish in time") case <-done: break } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/compose_run_test.go
pkg/e2e/compose_run_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "os" "strings" "testing" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestLocalComposeRun(t *testing.T) { c := NewParallelCLI(t) defer c.cleanupWithDown(t, "run-test") t.Run("compose run", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/compose.yaml", "run", "back") lines := Lines(res.Stdout()) assert.Equal(t, lines[len(lines)-1], "Hello there!!", res.Stdout()) assert.Assert(t, !strings.Contains(res.Combined(), "orphan")) res = c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/compose.yaml", "run", "back", "echo", "Hello one more time") lines = Lines(res.Stdout()) assert.Equal(t, lines[len(lines)-1], "Hello one more time", res.Stdout()) assert.Assert(t, strings.Contains(res.Combined(), "orphan")) }) t.Run("check run container exited", func(t *testing.T) { res := c.RunDockerCmd(t, "ps", "--all") lines := Lines(res.Stdout()) var runContainerID string var truncatedSlug string for _, line := range lines { fields := strings.Fields(line) containerID := fields[len(fields)-1] assert.Assert(t, !strings.HasPrefix(containerID, "run-test-front")) if strings.HasPrefix(containerID, "run-test-back") { // only the one-off container for back service assert.Assert(t, strings.HasPrefix(containerID, "run-test-back-run-"), containerID) truncatedSlug = strings.Replace(containerID, "run-test-back-run-", "", 1) runContainerID = containerID } if strings.HasPrefix(containerID, "run-test-db-1") { assert.Assert(t, strings.Contains(line, "Up"), line) } } assert.Assert(t, runContainerID != "") res = c.RunDockerCmd(t, "inspect", runContainerID) res.Assert(t, icmd.Expected{Out: ` "Status": "exited"`}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.project": "run-test"`}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.oneoff": "True",`}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.slug": "` + truncatedSlug}) }) t.Run("compose run --rm", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/compose.yaml", "run", "--rm", "back", "echo", "Hello again") lines := Lines(res.Stdout()) assert.Equal(t, lines[len(lines)-1], "Hello again", res.Stdout()) res = c.RunDockerCmd(t, "ps", "--all") assert.Assert(t, strings.Contains(res.Stdout(), "run-test-back"), res.Stdout()) }) t.Run("down", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/compose.yaml", "down", "--remove-orphans") res := c.RunDockerCmd(t, "ps", "--all") assert.Assert(t, !strings.Contains(res.Stdout(), "run-test"), res.Stdout()) }) t.Run("compose run --volumes", func(t *testing.T) { wd, err := os.Getwd() assert.NilError(t, err) res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/compose.yaml", "run", "--volumes", wd+":/foo", "back", "/bin/sh", "-c", "ls /foo") res.Assert(t, icmd.Expected{Out: "compose_run_test.go"}) res = c.RunDockerCmd(t, "ps", "--all") assert.Assert(t, strings.Contains(res.Stdout(), "run-test-back"), res.Stdout()) }) t.Run("compose run --publish", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/ports.yaml", "run", "--publish", "8081:80", "-d", "back", "/bin/sh", "-c", "sleep 1") res := c.RunDockerCmd(t, "ps") assert.Assert(t, strings.Contains(res.Stdout(), "8081->80/tcp"), res.Stdout()) assert.Assert(t, !strings.Contains(res.Stdout(), "8082->80/tcp"), res.Stdout()) }) t.Run("compose run --service-ports", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/ports.yaml", "run", "--service-ports", "-d", "back", "/bin/sh", "-c", "sleep 1") res := c.RunDockerCmd(t, "ps") assert.Assert(t, strings.Contains(res.Stdout(), "8082->80/tcp"), res.Stdout()) }) t.Run("compose run orphan", func(t *testing.T) { // Use different compose files to get an orphan container c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/orphan.yaml", "run", "simple") res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/compose.yaml", "run", "back", "echo", "Hello") assert.Assert(t, strings.Contains(res.Combined(), "orphan")) cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/run-test/compose.yaml", "run", "back", "echo", "Hello") res = icmd.RunCmd(cmd, func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "COMPOSE_IGNORE_ORPHANS=True") }) assert.Assert(t, !strings.Contains(res.Combined(), "orphan")) }) t.Run("down", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/run-test/compose.yaml", "down") icmd.RunCmd(cmd, func(c *icmd.Cmd) { c.Env = append(c.Env, "COMPOSE_REMOVE_ORPHANS=True") }) res := c.RunDockerCmd(t, "ps", "--all") assert.Assert(t, !strings.Contains(res.Stdout(), "run-test"), res.Stdout()) }) t.Run("run starts only container and dependencies", func(t *testing.T) { // ensure that even if another service is up run does not start it: https://github.com/docker/compose/issues/9459 res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/deps.yaml", "up", "service_b", "--menu=false") res.Assert(t, icmd.Success) res = c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/deps.yaml", "run", "service_a") assert.Assert(t, strings.Contains(res.Combined(), "shared_dep"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "service_b"), res.Combined()) c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/deps.yaml", "down", "--remove-orphans") }) t.Run("run without dependencies", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/deps.yaml", "run", "--no-deps", "service_a") assert.Assert(t, !strings.Contains(res.Combined(), "shared_dep"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "service_b"), res.Combined()) c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/deps.yaml", "down", "--remove-orphans") }) t.Run("run with not required dependency", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/dependencies/deps-not-required.yaml", "run", "foo") assert.Assert(t, strings.Contains(res.Combined(), "foo"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "bar"), res.Combined()) c.RunDockerComposeCmd(t, "-f", "./fixtures/dependencies/deps-not-required.yaml", "down", "--remove-orphans") }) t.Run("--quiet-pull", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/quiet-pull.yaml", "down", "--remove-orphans", "--rmi", "all") res.Assert(t, icmd.Success) res = c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/quiet-pull.yaml", "run", "--quiet-pull", "backend") assert.Assert(t, !strings.Contains(res.Combined(), "Pull complete"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "Pulled"), res.Combined()) }) t.Run("COMPOSE_PROGRESS quiet", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/quiet-pull.yaml", "down", "--remove-orphans", "--rmi", "all") res.Assert(t, icmd.Success) cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/run-test/quiet-pull.yaml", "run", "backend") res = icmd.RunCmd(cmd, func(c *icmd.Cmd) { c.Env = append(c.Env, "COMPOSE_PROGRESS=quiet") }) assert.Assert(t, !strings.Contains(res.Combined(), "Pull complete"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "Pulled"), res.Combined()) }) t.Run("--pull", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/pull.yaml", "down", "--remove-orphans", "--rmi", "all") res.Assert(t, icmd.Success) res = c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/pull.yaml", "run", "--pull", "always", "backend") assert.Assert(t, strings.Contains(res.Combined(), "Image nginx Pulling"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "Image nginx Pulled"), res.Combined()) }) t.Run("compose run --env-from-file", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/compose.yaml", "run", "--env-from-file", "./fixtures/run-test/run.env", "front", "env") res.Assert(t, icmd.Expected{Out: "FOO=BAR"}) }) t.Run("compose run -rm with stop signal", func(t *testing.T) { projectName := "run-test" res := c.RunDockerComposeCmd(t, "--project-name", projectName, "-f", "./fixtures/ps-test/compose.yaml", "run", "--rm", "-d", "nginx") res.Assert(t, icmd.Success) res = c.RunDockerCmd(t, "ps", "--quiet", "--filter", "name=run-test-nginx") containerID := strings.TrimSpace(res.Stdout()) res = c.RunDockerCmd(t, "stop", containerID) res.Assert(t, icmd.Success) res = c.RunDockerCmd(t, "ps", "--all", "--filter", "name=run-test-nginx", "--format", "'{{.Names}}'") assert.Assert(t, !strings.Contains(res.Stdout(), "run-test-nginx"), res.Stdout()) }) t.Run("compose run --env", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/compose.yaml", "run", "--env", "FOO=BAR", "front", "env") res.Assert(t, icmd.Expected{Out: "FOO=BAR"}) }) t.Run("compose run --build", func(t *testing.T) { c.cleanupWithDown(t, "run-test", "--rmi=local") res := c.RunDockerComposeCmd(t, "-f", "./fixtures/run-test/compose.yaml", "run", "build", "echo", "hello world") res.Assert(t, icmd.Expected{Out: "hello world"}) }) t.Run("compose run with piped input detection", func(t *testing.T) { if composeStandaloneMode { t.Skip("Skipping test compose with piped input detection in standalone mode") } // Test that piped input is properly detected and TTY is automatically disabled // This tests the logic added in run.go that checks dockerCli.In().IsTerminal() cmd := c.NewCmd("sh", "-c", "echo 'piped-content' | docker compose -f ./fixtures/run-test/piped-test.yaml run --rm piped-test") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{Out: "piped-content"}) res.Assert(t, icmd.Success) }) t.Run("compose run piped input should not allocate TTY", func(t *testing.T) { if composeStandaloneMode { t.Skip("Skipping test compose with piped input detection in standalone mode") } // Test that when stdin is piped, the container correctly detects no TTY // This verifies that the automatic noTty=true setting works correctly cmd := c.NewCmd("sh", "-c", "echo '' | docker compose -f ./fixtures/run-test/piped-test.yaml run --rm tty-test") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{Out: "No TTY detected"}) res.Assert(t, icmd.Success) }) t.Run("compose run piped input with explicit --tty should fail", func(t *testing.T) { if composeStandaloneMode { t.Skip("Skipping test compose with piped input detection in standalone mode") } // Test that explicitly requesting TTY with piped input fails with proper error message // This should trigger the "input device is not a TTY" error cmd := c.NewCmd("sh", "-c", "echo 'test' | docker compose -f ./fixtures/run-test/piped-test.yaml run --rm --tty piped-test") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{ ExitCode: 1, Err: "the input device is not a TTY", }) }) t.Run("compose run piped input with --no-TTY=false should fail", func(t *testing.T) { if composeStandaloneMode { t.Skip("Skipping test compose with piped input detection in standalone mode") } // Test that explicitly disabling --no-TTY (i.e., requesting TTY) with piped input fails // This should also trigger the "input device is not a TTY" error cmd := c.NewCmd("sh", "-c", "echo 'test' | docker compose -f ./fixtures/run-test/piped-test.yaml run --rm --no-TTY=false piped-test") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{ ExitCode: 1, Err: "the input device is not a TTY", }) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/compose_exec_test.go
pkg/e2e/compose_exec_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "strings" "testing" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestLocalComposeExec(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-exec" cmdArgs := func(cmd string, args ...string) []string { ret := []string{"--project-directory", "fixtures/simple-composefile", "--project-name", projectName, cmd} ret = append(ret, args...) return ret } cleanup := func() { c.RunDockerComposeCmd(t, cmdArgs("down", "--timeout=0")...) } cleanup() t.Cleanup(cleanup) c.RunDockerComposeCmd(t, cmdArgs("up", "-d")...) t.Run("exec true", func(t *testing.T) { c.RunDockerComposeCmd(t, cmdArgs("exec", "simple", "/bin/true")...) }) t.Run("exec false", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, cmdArgs("exec", "simple", "/bin/false")...) res.Assert(t, icmd.Expected{ExitCode: 1}) }) t.Run("exec with env set", func(t *testing.T) { res := icmd.RunCmd(c.NewDockerComposeCmd(t, cmdArgs("exec", "-e", "FOO", "simple", "/usr/bin/env")...), func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "FOO=BAR") }) res.Assert(t, icmd.Expected{Out: "FOO=BAR"}) }) t.Run("exec without env set", func(t *testing.T) { res := c.RunDockerComposeCmd(t, cmdArgs("exec", "-e", "FOO", "simple", "/usr/bin/env")...) assert.Check(t, !strings.Contains(res.Stdout(), "FOO="), res.Combined()) }) } func TestLocalComposeExecOneOff(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-exec-one-off" defer c.cleanupWithDown(t, projectName) cmdArgs := func(cmd string, args ...string) []string { ret := []string{"--project-directory", "fixtures/simple-composefile", "--project-name", projectName, cmd} ret = append(ret, args...) return ret } c.RunDockerComposeCmd(t, cmdArgs("run", "-d", "simple")...) t.Run("exec in one-off container", func(t *testing.T) { res := c.RunDockerComposeCmd(t, cmdArgs("exec", "-e", "FOO", "simple", "/usr/bin/env")...) assert.Check(t, !strings.Contains(res.Stdout(), "FOO="), res.Combined()) }) t.Run("exec with index", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, cmdArgs("exec", "--index", "1", "-e", "FOO", "simple", "/usr/bin/env")...) res.Assert(t, icmd.Expected{ExitCode: 1, Err: "service \"simple\" is not running container #1"}) }) cmdResult := c.RunDockerCmd(t, "ps", "-q", "--filter", "label=com.docker.compose.project=compose-e2e-exec-one-off").Stdout() containerIDs := strings.Split(cmdResult, "\n") _ = c.RunDockerOrExitError(t, append([]string{"stop"}, containerIDs...)...) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/compose_test.go
pkg/e2e/compose_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "fmt" "net/http" "os" "path/filepath" "strings" "testing" "time" testify "github.com/stretchr/testify/assert" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestLocalComposeUp(t *testing.T) { // this test shares a fixture with TestCompatibility and can't run at the same time c := NewCLI(t) const projectName = "compose-e2e-demo" t.Run("up", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/sentences/compose.yaml", "--project-name", projectName, "up", "-d") }) t.Run("check accessing running app", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-p", projectName, "ps") res.Assert(t, icmd.Expected{Out: `web`}) endpoint := "http://localhost:90" output := HTTPGetWithRetry(t, endpoint+"/words/noun", http.StatusOK, 2*time.Second, 20*time.Second) assert.Assert(t, strings.Contains(output, `"word":`)) res = c.RunDockerCmd(t, "network", "ls") res.Assert(t, icmd.Expected{Out: projectName + "_default"}) }) t.Run("top", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-p", projectName, "top") output := res.Stdout() head := []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"} for _, h := range head { assert.Assert(t, strings.Contains(output, h), output) } assert.Assert(t, strings.Contains(output, `java -Xmx8m -Xms8m -jar /app/words.jar`), output) assert.Assert(t, strings.Contains(output, `/dispatcher`), output) }) t.Run("check compose labels", func(t *testing.T) { res := c.RunDockerCmd(t, "inspect", projectName+"-web-1") res.Assert(t, icmd.Expected{Out: `"com.docker.compose.container-number": "1"`}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.project": "compose-e2e-demo"`}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.oneoff": "False",`}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.config-hash":`}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.project.config_files":`}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.project.working_dir":`}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.service": "web"`}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.version":`}) res = c.RunDockerCmd(t, "network", "inspect", projectName+"_default") res.Assert(t, icmd.Expected{Out: `"com.docker.compose.network": "default"`}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.project": `}) res.Assert(t, icmd.Expected{Out: `"com.docker.compose.version": `}) }) t.Run("check user labels", func(t *testing.T) { res := c.RunDockerCmd(t, "inspect", projectName+"-web-1") res.Assert(t, icmd.Expected{Out: `"my-label": "test"`}) }) t.Run("check healthcheck output", func(t *testing.T) { c.WaitForCmdResult(t, c.NewDockerComposeCmd(t, "-p", projectName, "ps", "--format", "json"), IsHealthy(projectName+"-web-1"), 5*time.Second, 1*time.Second) res := c.RunDockerComposeCmd(t, "-p", projectName, "ps") assertServiceStatus(t, projectName, "web", "(healthy)", res.Stdout()) }) t.Run("images", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-p", projectName, "images") res.Assert(t, icmd.Expected{Out: `compose-e2e-demo-db-1 gtardif/sentences-db latest`}) res.Assert(t, icmd.Expected{Out: `compose-e2e-demo-web-1 gtardif/sentences-web latest`}) res.Assert(t, icmd.Expected{Out: `compose-e2e-demo-words-1 gtardif/sentences-api latest`}) }) t.Run("down SERVICE", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "web") res := c.RunDockerComposeCmd(t, "--project-name", projectName, "ps") assert.Assert(t, !strings.Contains(res.Combined(), "compose-e2e-demo-web-1"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "compose-e2e-demo-db-1"), res.Combined()) }) t.Run("down", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) t.Run("check containers after down", func(t *testing.T) { res := c.RunDockerCmd(t, "ps", "--all") assert.Assert(t, !strings.Contains(res.Combined(), projectName), res.Combined()) }) t.Run("check networks after down", func(t *testing.T) { res := c.RunDockerCmd(t, "network", "ls") assert.Assert(t, !strings.Contains(res.Combined(), projectName), res.Combined()) }) } func TestDownComposefileInParentFolder(t *testing.T) { c := NewParallelCLI(t) tmpFolder, err := os.MkdirTemp("fixtures/simple-composefile", "test-tmp") assert.NilError(t, err) defer os.Remove(tmpFolder) //nolint:errcheck projectName := filepath.Base(tmpFolder) res := c.RunDockerComposeCmd(t, "--project-directory", tmpFolder, "up", "-d") res.Assert(t, icmd.Expected{Err: "Started", ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "down") res.Assert(t, icmd.Expected{Err: "Removed", ExitCode: 0}) } func TestAttachRestart(t *testing.T) { t.Skip("Skipping test until we can fix it") if _, ok := os.LookupEnv("CI"); ok { t.Skip("Skipping test on CI... flaky") } c := NewParallelCLI(t) cmd := c.NewDockerComposeCmd(t, "--ansi=never", "--project-directory", "./fixtures/attach-restart", "up") res := icmd.StartCmd(cmd) defer c.RunDockerComposeCmd(t, "-p", "attach-restart", "down") c.WaitForCondition(t, func() (bool, string) { debug := res.Combined() return strings.Count(res.Stdout(), "failing-1 exited with code 1") == 3, fmt.Sprintf("'failing-1 exited with code 1' not found 3 times in : \n%s\n", debug) }, 4*time.Minute, 2*time.Second) assert.Equal(t, strings.Count(res.Stdout(), "failing-1 | world"), 3, res.Combined()) } func TestInitContainer(t *testing.T) { c := NewParallelCLI(t) res := c.RunDockerComposeCmd(t, "--ansi=never", "--project-directory", "./fixtures/init-container", "up", "--menu=false") defer c.RunDockerComposeCmd(t, "-p", "init-container", "down") testify.Regexp(t, "foo-1 | hello(?m:.*)bar-1 | world", res.Stdout()) } func TestRm(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-rm" t.Run("up", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/simple-composefile/compose.yaml", "-p", projectName, "up", "-d") }) t.Run("rm --stop --force simple", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/simple-composefile/compose.yaml", "-p", projectName, "rm", "--stop", "--force", "simple") res.Assert(t, icmd.Expected{Err: "Removed", ExitCode: 0}) }) t.Run("check containers after rm", func(t *testing.T) { res := c.RunDockerCmd(t, "ps", "--all") assert.Assert(t, !strings.Contains(res.Combined(), projectName+"-simple"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), projectName+"-another"), res.Combined()) }) t.Run("up (again)", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/simple-composefile/compose.yaml", "-p", projectName, "up", "-d") }) t.Run("rm ---stop --force <none>", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/simple-composefile/compose.yaml", "-p", projectName, "rm", "--stop", "--force") res.Assert(t, icmd.Expected{ExitCode: 0}) }) t.Run("check containers after rm", func(t *testing.T) { res := c.RunDockerCmd(t, "ps", "--all") assert.Assert(t, !strings.Contains(res.Combined(), projectName+"-simple"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), projectName+"-another"), res.Combined()) }) t.Run("down", func(t *testing.T) { c.RunDockerComposeCmd(t, "-p", projectName, "down") }) } func TestCompatibility(t *testing.T) { // this test shares a fixture with TestLocalComposeUp and can't run at the same time c := NewCLI(t) const projectName = "compose-e2e-compatibility" t.Run("up", func(t *testing.T) { c.RunDockerComposeCmd(t, "--compatibility", "-f", "./fixtures/sentences/compose.yaml", "--project-name", projectName, "up", "-d") }) t.Run("check container names", func(t *testing.T) { res := c.RunDockerCmd(t, "ps", "--format", "{{.Names}}") res.Assert(t, icmd.Expected{Out: "compose-e2e-compatibility_web_1"}) res.Assert(t, icmd.Expected{Out: "compose-e2e-compatibility_words_1"}) res.Assert(t, icmd.Expected{Out: "compose-e2e-compatibility_db_1"}) }) t.Run("down", func(t *testing.T) { c.RunDockerComposeCmd(t, "-p", projectName, "down") }) } func TestConfig(t *testing.T) { const projectName = "compose-e2e-config" c := NewParallelCLI(t) wd, err := os.Getwd() assert.NilError(t, err) t.Run("up", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/simple-build-test/compose.yaml", "-p", projectName, "config") res.Assert(t, icmd.Expected{Out: fmt.Sprintf(`name: %s services: nginx: build: context: %s dockerfile: Dockerfile networks: default: null networks: default: name: compose-e2e-config_default `, projectName, filepath.Join(wd, "fixtures", "simple-build-test", "nginx-build")), ExitCode: 0}) }) } func TestConfigInterpolate(t *testing.T) { const projectName = "compose-e2e-config-interpolate" c := NewParallelCLI(t) wd, err := os.Getwd() assert.NilError(t, err) t.Run("config", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/simple-build-test/compose-interpolate.yaml", "-p", projectName, "config", "--no-interpolate") res.Assert(t, icmd.Expected{Out: fmt.Sprintf(`name: %s networks: default: name: compose-e2e-config-interpolate_default services: nginx: build: context: %s dockerfile: ${MYVAR} networks: default: null `, projectName, filepath.Join(wd, "fixtures", "simple-build-test", "nginx-build")), ExitCode: 0}) }) } func TestStopWithDependenciesAttached(t *testing.T) { const projectName = "compose-e2e-stop-with-deps" c := NewParallelCLI(t, WithEnv("COMMAND=echo hello")) cleanup := func() { c.RunDockerComposeCmd(t, "-p", projectName, "down", "--remove-orphans", "--timeout=0") } cleanup() t.Cleanup(cleanup) res := c.RunDockerComposeCmd(t, "-f", "./fixtures/dependencies/compose.yaml", "-p", projectName, "up", "--attach-dependencies", "foo", "--menu=false") res.Assert(t, icmd.Expected{Out: "exited with code 0"}) } func TestRemoveOrphaned(t *testing.T) { const projectName = "compose-e2e-remove-orphaned" c := NewParallelCLI(t) cleanup := func() { c.RunDockerComposeCmd(t, "-p", projectName, "down", "--remove-orphans", "--timeout=0") } cleanup() t.Cleanup(cleanup) // run stack c.RunDockerComposeCmd(t, "-f", "./fixtures/sentences/compose.yaml", "-p", projectName, "up", "-d") // down "web" service with orphaned removed c.RunDockerComposeCmd(t, "-f", "./fixtures/sentences/compose.yaml", "-p", projectName, "down", "--remove-orphans", "web") // check "words" service has not been considered orphaned res := c.RunDockerComposeCmd(t, "-f", "./fixtures/sentences/compose.yaml", "-p", projectName, "ps", "--format", "{{.Name}}") res.Assert(t, icmd.Expected{Out: fmt.Sprintf("%s-words-1", projectName)}) } func TestComposeFileSetByDotEnv(t *testing.T) { c := NewCLI(t) defer c.cleanupWithDown(t, "dotenv") cmd := c.NewDockerComposeCmd(t, "config") cmd.Dir = filepath.Join(".", "fixtures", "dotenv") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{ ExitCode: 0, Out: "image: test:latest", }) res.Assert(t, icmd.Expected{ Out: "image: enabled:profile", }) } func TestComposeFileSetByProjectDirectory(t *testing.T) { c := NewCLI(t) defer c.cleanupWithDown(t, "dotenv") dir := filepath.Join(".", "fixtures", "dotenv", "development") cmd := c.NewDockerComposeCmd(t, "--project-directory", dir, "config") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{ ExitCode: 0, Out: "image: backend:latest", }) } func TestComposeFileSetByEnvFile(t *testing.T) { c := NewCLI(t) defer c.cleanupWithDown(t, "dotenv") dotEnv, err := os.CreateTemp(t.TempDir(), ".env") assert.NilError(t, err) err = os.WriteFile(dotEnv.Name(), []byte(` COMPOSE_FILE=fixtures/dotenv/development/compose.yaml IMAGE_NAME=test IMAGE_TAG=latest COMPOSE_PROFILES=test `), 0o700) assert.NilError(t, err) cmd := c.NewDockerComposeCmd(t, "--env-file", dotEnv.Name(), "config") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{ Out: "image: test:latest", }) res.Assert(t, icmd.Expected{ Out: "image: enabled:profile", }) } func TestNestedDotEnv(t *testing.T) { c := NewCLI(t) defer c.cleanupWithDown(t, "nested") cmd := c.NewDockerComposeCmd(t, "run", "echo") cmd.Dir = filepath.Join(".", "fixtures", "nested") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{ ExitCode: 0, Out: "root win=root", }) cmd = c.NewDockerComposeCmd(t, "run", "echo") cmd.Dir = filepath.Join(".", "fixtures", "nested", "sub") defer c.cleanupWithDown(t, "nested") res = icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{ ExitCode: 0, Out: "root sub win=sub", }) } func TestUnnecessaryResources(t *testing.T) { const projectName = "compose-e2e-unnecessary-resources" c := NewParallelCLI(t) defer c.cleanupWithDown(t, projectName) res := c.RunDockerComposeCmdNoCheck(t, "-f", "./fixtures/external/compose.yaml", "-p", projectName, "up", "-d") res.Assert(t, icmd.Expected{ ExitCode: 1, Err: "network foo_bar declared as external, but could not be found", }) c.RunDockerComposeCmd(t, "-f", "./fixtures/external/compose.yaml", "-p", projectName, "up", "-d", "test") // Should not fail as missing external network is not used }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/scale_test.go
pkg/e2e/scale_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "fmt" "strings" "testing" testify "github.com/stretchr/testify/assert" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) const NO_STATE_TO_CHECK = "" func TestScaleBasicCases(t *testing.T) { c := NewCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=scale-basic-tests")) reset := func() { c.RunDockerComposeCmd(t, "down", "--rmi", "all") } t.Cleanup(reset) res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "up", "-d") res.Assert(t, icmd.Success) t.Log("scale up one service") res = c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "scale", "dbadmin=2") out := res.Combined() checkServiceContainer(t, out, "scale-basic-tests-dbadmin", "Started", 2) t.Log("scale up 2 services") res = c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "scale", "front=3", "back=2") out = res.Combined() checkServiceContainer(t, out, "scale-basic-tests-front", "Running", 2) checkServiceContainer(t, out, "scale-basic-tests-front", "Started", 1) checkServiceContainer(t, out, "scale-basic-tests-back", "Running", 1) checkServiceContainer(t, out, "scale-basic-tests-back", "Started", 1) t.Log("scale down one service") res = c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "scale", "dbadmin=1") out = res.Combined() checkServiceContainer(t, out, "scale-basic-tests-dbadmin", "Running", 1) t.Log("scale to 0 a service") res = c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "scale", "dbadmin=0") assert.Check(t, res.Stdout() == "", res.Stdout()) t.Log("scale down 2 services") res = c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "scale", "front=2", "back=1") out = res.Combined() checkServiceContainer(t, out, "scale-basic-tests-front", "Running", 2) assert.Check(t, !strings.Contains(out, "Container scale-basic-tests-front-3 Running"), res.Combined()) checkServiceContainer(t, out, "scale-basic-tests-back", "Running", 1) } func TestScaleWithDepsCases(t *testing.T) { c := NewCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=scale-deps-tests")) reset := func() { c.RunDockerComposeCmd(t, "down", "--rmi", "all") } t.Cleanup(reset) res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "up", "-d", "--scale", "db=2") res.Assert(t, icmd.Success) res = c.RunDockerComposeCmd(t, "ps") checkServiceContainer(t, res.Combined(), "scale-deps-tests-db", NO_STATE_TO_CHECK, 2) t.Log("scale up 1 service with --no-deps") _ = c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "scale", "--no-deps", "back=2") res = c.RunDockerComposeCmd(t, "ps") checkServiceContainer(t, res.Combined(), "scale-deps-tests-back", NO_STATE_TO_CHECK, 2) checkServiceContainer(t, res.Combined(), "scale-deps-tests-db", NO_STATE_TO_CHECK, 2) t.Log("scale up 1 service without --no-deps") _ = c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "scale", "back=2") res = c.RunDockerComposeCmd(t, "ps") checkServiceContainer(t, res.Combined(), "scale-deps-tests-back", NO_STATE_TO_CHECK, 2) checkServiceContainer(t, res.Combined(), "scale-deps-tests-db", NO_STATE_TO_CHECK, 1) } func TestScaleUpAndDownPreserveContainerNumber(t *testing.T) { const projectName = "scale-up-down-test" c := NewCLI(t, WithEnv( "COMPOSE_PROJECT_NAME="+projectName)) reset := func() { c.RunDockerComposeCmd(t, "down", "--rmi", "all") } t.Cleanup(reset) res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "up", "-d", "--scale", "db=2", "db") res.Assert(t, icmd.Success) res = c.RunDockerComposeCmd(t, "ps", "--format", "{{.Name}}", "db") res.Assert(t, icmd.Success) assert.Equal(t, strings.TrimSpace(res.Stdout()), projectName+"-db-1\n"+projectName+"-db-2") t.Log("scale down removes replica #2") res = c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "up", "-d", "--scale", "db=1", "db") res.Assert(t, icmd.Success) res = c.RunDockerComposeCmd(t, "ps", "--format", "{{.Name}}", "db") res.Assert(t, icmd.Success) assert.Equal(t, strings.TrimSpace(res.Stdout()), projectName+"-db-1") t.Log("scale up restores replica #2") res = c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "up", "-d", "--scale", "db=2", "db") res.Assert(t, icmd.Success) res = c.RunDockerComposeCmd(t, "ps", "--format", "{{.Name}}", "db") res.Assert(t, icmd.Success) assert.Equal(t, strings.TrimSpace(res.Stdout()), projectName+"-db-1\n"+projectName+"-db-2") } func TestScaleDownRemovesObsolete(t *testing.T) { const projectName = "scale-down-obsolete-test" c := NewCLI(t, WithEnv( "COMPOSE_PROJECT_NAME="+projectName)) reset := func() { c.RunDockerComposeCmd(t, "down", "--rmi", "all") } t.Cleanup(reset) res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/scale", "up", "-d", "db") res.Assert(t, icmd.Success) res = c.RunDockerComposeCmd(t, "ps", "--format", "{{.Name}}", "db") res.Assert(t, icmd.Success) assert.Equal(t, strings.TrimSpace(res.Stdout()), projectName+"-db-1") cmd := c.NewDockerComposeCmd(t, "--project-directory", "fixtures/scale", "up", "-d", "--scale", "db=2", "db") res = icmd.RunCmd(cmd, func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "MAYBE=value") }) res.Assert(t, icmd.Success) res = c.RunDockerComposeCmd(t, "ps", "--format", "{{.Name}}", "db") res.Assert(t, icmd.Success) assert.Equal(t, strings.TrimSpace(res.Stdout()), projectName+"-db-1\n"+projectName+"-db-2") t.Log("scale down removes obsolete replica #1") cmd = c.NewDockerComposeCmd(t, "--project-directory", "fixtures/scale", "up", "-d", "--scale", "db=1", "db") res = icmd.RunCmd(cmd, func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "MAYBE=value") }) res.Assert(t, icmd.Success) res = c.RunDockerComposeCmd(t, "ps", "--format", "{{.Name}}", "db") res.Assert(t, icmd.Success) assert.Equal(t, strings.TrimSpace(res.Stdout()), projectName+"-db-1") } func checkServiceContainer(t *testing.T, stdout, containerName, containerState string, count int) { found := 0 lines := strings.SplitSeq(stdout, "\n") for line := range lines { if strings.Contains(line, containerName) && strings.Contains(line, containerState) { found++ } } if found == count { return } errMessage := fmt.Sprintf("expected %d but found %d instance(s) of container %s in stoud", count, found, containerName) if containerState != "" { errMessage += fmt.Sprintf(" with expected state %s", containerState) } testify.Fail(t, errMessage, stdout) } func TestScaleDownNoRecreate(t *testing.T) { const projectName = "scale-down-recreated-test" c := NewCLI(t, WithEnv( "COMPOSE_PROJECT_NAME="+projectName)) reset := func() { c.RunDockerComposeCmd(t, "down", "--rmi", "all") } t.Cleanup(reset) c.RunDockerComposeCmd(t, "-f", "fixtures/scale/build.yaml", "build", "--build-arg", "FOO=test") c.RunDockerComposeCmd(t, "-f", "fixtures/scale/build.yaml", "up", "-d", "--scale", "test=2") c.RunDockerComposeCmd(t, "-f", "fixtures/scale/build.yaml", "build", "--build-arg", "FOO=updated") c.RunDockerComposeCmd(t, "-f", "fixtures/scale/build.yaml", "up", "-d", "--scale", "test=4", "--no-recreate") res := c.RunDockerComposeCmd(t, "ps", "--format", "{{.Name}}", "test") res.Assert(t, icmd.Success) assert.Check(t, strings.Contains(res.Stdout(), "scale-down-recreated-test-test-1")) assert.Check(t, strings.Contains(res.Stdout(), "scale-down-recreated-test-test-2")) assert.Check(t, strings.Contains(res.Stdout(), "scale-down-recreated-test-test-3")) assert.Check(t, strings.Contains(res.Stdout(), "scale-down-recreated-test-test-4")) t.Log("scale down removes obsolete replica #1 and #2") c.NewDockerComposeCmd(t, "--project-directory", "fixtures/scale", "up", "-d", "--scale", "test=2") res = c.RunDockerComposeCmd(t, "ps", "--format", "{{.Name}}", "test") res.Assert(t, icmd.Success) assert.Check(t, strings.Contains(res.Stdout(), "scale-down-recreated-test-test-3")) assert.Check(t, strings.Contains(res.Stdout(), "scale-down-recreated-test-test-4")) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/container_name_test.go
pkg/e2e/container_name_test.go
//go:build !windows /* Copyright 2022 Docker Compose CLI 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 e2e import ( "testing" "gotest.tools/v3/icmd" ) func TestUpContainerNameConflict(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-container_name_conflict" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/container_name/compose.yaml", "--project-name", projectName, "up") res.Assert(t, icmd.Expected{ExitCode: 1, Err: `container name "test" is already in use`}) c.RunDockerComposeCmd(t, "--project-name", projectName, "down") c.RunDockerComposeCmd(t, "-f", "fixtures/container_name/compose.yaml", "--project-name", projectName, "up", "test") c.RunDockerComposeCmd(t, "--project-name", projectName, "down") c.RunDockerComposeCmd(t, "-f", "fixtures/container_name/compose.yaml", "--project-name", projectName, "up", "another_test") }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/configs_test.go
pkg/e2e/configs_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "testing" "gotest.tools/v3/icmd" ) func TestConfigFromEnv(t *testing.T) { c := NewParallelCLI(t) defer c.cleanupWithDown(t, "configs") t.Run("config from file", func(t *testing.T) { res := icmd.RunCmd(c.NewDockerComposeCmd(t, "-f", "./fixtures/configs/compose.yaml", "run", "from_file")) res.Assert(t, icmd.Expected{Out: "This is my config file"}) }) t.Run("config from env", func(t *testing.T) { res := icmd.RunCmd(c.NewDockerComposeCmd(t, "-f", "./fixtures/configs/compose.yaml", "run", "from_env"), func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "CONFIG=config") }) res.Assert(t, icmd.Expected{Out: "config"}) }) t.Run("config inlined", func(t *testing.T) { res := icmd.RunCmd(c.NewDockerComposeCmd(t, "-f", "./fixtures/configs/compose.yaml", "run", "inlined"), func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "CONFIG=config") }) res.Assert(t, icmd.Expected{Out: "This is my config"}) }) t.Run("custom target", func(t *testing.T) { res := icmd.RunCmd(c.NewDockerComposeCmd(t, "-f", "./fixtures/configs/compose.yaml", "run", "target"), func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "CONFIG=config") }) res.Assert(t, icmd.Expected{Out: "This is my config"}) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/ps_test.go
pkg/e2e/ps_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "encoding/json" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gotest.tools/v3/icmd" "github.com/docker/compose/v5/pkg/api" ) func TestPs(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-ps" res := c.RunDockerComposeCmd(t, "-f", "./fixtures/ps-test/compose.yaml", "--project-name", projectName, "up", "-d") require.NoError(t, res.Error) t.Cleanup(func() { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) assert.Contains(t, res.Combined(), "Container e2e-ps-busybox-1 Started", res.Combined()) t.Run("table", func(t *testing.T) { res = c.RunDockerComposeCmd(t, "-f", "./fixtures/ps-test/compose.yaml", "--project-name", projectName, "ps") lines := strings.Split(res.Stdout(), "\n") assert.Len(t, lines, 4) count := 0 for _, line := range lines[1:3] { if strings.Contains(line, "e2e-ps-busybox-1") { assert.Contains(t, line, "127.0.0.1:8001->8000/tcp") count++ } if strings.Contains(line, "e2e-ps-nginx-1") { assert.Contains(t, line, "80/tcp, 443/tcp, 8080/tcp") count++ } } assert.Equal(t, 2, count, "Did not match both services:\n"+res.Combined()) }) t.Run("json", func(t *testing.T) { res = c.RunDockerComposeCmd(t, "-f", "./fixtures/ps-test/compose.yaml", "--project-name", projectName, "ps", "--format", "json") type element struct { Name string Project string Publishers api.PortPublishers } var output []element out := res.Stdout() dec := json.NewDecoder(strings.NewReader(out)) for dec.More() { var s element require.NoError(t, dec.Decode(&s), "Failed to unmarshal ps JSON output") output = append(output, s) } count := 0 assert.Len(t, output, 2) for _, service := range output { assert.Equal(t, projectName, service.Project) publishers := service.Publishers if service.Name == "e2e-ps-busybox-1" { assert.Len(t, publishers, 1) assert.Equal(t, api.PortPublishers{ { URL: "127.0.0.1", TargetPort: 8000, PublishedPort: 8001, Protocol: "tcp", }, }, publishers) count++ } if service.Name == "e2e-ps-nginx-1" { assert.Len(t, publishers, 3) assert.Equal(t, api.PortPublishers{ {TargetPort: 80, Protocol: "tcp"}, {TargetPort: 443, Protocol: "tcp"}, {TargetPort: 8080, Protocol: "tcp"}, }, publishers) count++ } } assert.Equal(t, 2, count, "Did not match both services:\n"+res.Combined()) }) t.Run("ps --all", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "stop") require.NoError(t, res.Error) res = c.RunDockerComposeCmd(t, "-f", "./fixtures/ps-test/compose.yaml", "--project-name", projectName, "ps") lines := strings.Split(res.Stdout(), "\n") assert.Len(t, lines, 2) res = c.RunDockerComposeCmd(t, "-f", "./fixtures/ps-test/compose.yaml", "--project-name", projectName, "ps", "--all") lines = strings.Split(res.Stdout(), "\n") assert.Len(t, lines, 4) }) t.Run("ps unknown", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "stop") require.NoError(t, res.Error) res = c.RunDockerComposeCmd(t, "-f", "./fixtures/ps-test/compose.yaml", "--project-name", projectName, "ps", "nginx") res.Assert(t, icmd.Success) res = c.RunDockerComposeCmdNoCheck(t, "-f", "./fixtures/ps-test/compose.yaml", "--project-name", projectName, "ps", "unknown") res.Assert(t, icmd.Expected{ExitCode: 1, Err: "no such service: unknown"}) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/e2e_config_standalone.go
pkg/e2e/e2e_config_standalone.go
//go:build standalone /* Copyright 2020 Docker Compose CLI 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 e2e const composeStandaloneMode = true
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/start_stop_test.go
pkg/e2e/start_stop_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "fmt" "strings" "testing" testify "github.com/stretchr/testify/assert" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestStartStop(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-start-stop-no-dependencies" getProjectRegx := func(status string) string { // match output with random spaces like: // e2e-start-stop running(3) return fmt.Sprintf("%s\\s+%s\\(%d\\)", projectName, status, 2) } t.Run("Up a project", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/start-stop/compose.yaml", "--project-name", projectName, "up", "-d") assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-start-stop-no-dependencies-simple-1 Started"), res.Combined()) res = c.RunDockerComposeCmd(t, "ls", "--all") testify.Regexp(t, getProjectRegx("running"), res.Stdout()) res = c.RunDockerComposeCmd(t, "--project-name", projectName, "ps") assertServiceStatus(t, projectName, "simple", "Up", res.Stdout()) assertServiceStatus(t, projectName, "another", "Up", res.Stdout()) }) t.Run("stop project", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/start-stop/compose.yaml", "--project-name", projectName, "stop") res := c.RunDockerComposeCmd(t, "ls") assert.Assert(t, !strings.Contains(res.Combined(), "e2e-start-stop-no-dependencies"), res.Combined()) res = c.RunDockerComposeCmd(t, "ls", "--all") testify.Regexp(t, getProjectRegx("exited"), res.Stdout()) res = c.RunDockerComposeCmd(t, "--project-name", projectName, "ps") assert.Assert(t, !strings.Contains(res.Combined(), "e2e-start-stop-no-dependencies-words-1"), res.Combined()) res = c.RunDockerComposeCmd(t, "--project-name", projectName, "ps", "--all") assertServiceStatus(t, projectName, "simple", "Exited", res.Stdout()) assertServiceStatus(t, projectName, "another", "Exited", res.Stdout()) }) t.Run("start project", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/start-stop/compose.yaml", "--project-name", projectName, "start") res := c.RunDockerComposeCmd(t, "ls") testify.Regexp(t, getProjectRegx("running"), res.Stdout()) }) t.Run("down", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) } func TestStartStopWithDependencies(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-start-stop-with-dependencies" defer c.RunDockerComposeCmd(t, "--project-name", projectName, "rm", "-fsv") t.Run("Up", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/dependencies/compose.yaml", "--project-name", projectName, "up", "-d") assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-start-stop-with-dependencies-foo-1 Started"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-start-stop-with-dependencies-bar-1 Started"), res.Combined()) }) t.Run("stop foo", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "stop", "foo") assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-start-stop-with-dependencies-foo-1 Stopped"), res.Combined()) res = c.RunDockerComposeCmd(t, "--project-name", projectName, "ps", "--status", "running") assert.Assert(t, strings.Contains(res.Combined(), "e2e-start-stop-with-dependencies-bar-1"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "e2e-start-stop-with-dependencies-foo-1"), res.Combined()) }) t.Run("start foo", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "stop") assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-start-stop-with-dependencies-bar-1 Stopped"), res.Combined()) res = c.RunDockerComposeCmd(t, "--project-name", projectName, "start", "foo") out := res.Combined() assert.Assert(t, strings.Contains(out, "Container e2e-start-stop-with-dependencies-bar-1 Started"), out) assert.Assert(t, strings.Contains(out, "Container e2e-start-stop-with-dependencies-foo-1 Started"), out) res = c.RunDockerComposeCmd(t, "--project-name", projectName, "ps", "--status", "running") out = res.Combined() assert.Assert(t, strings.Contains(out, "e2e-start-stop-with-dependencies-bar-1"), out) assert.Assert(t, strings.Contains(out, "e2e-start-stop-with-dependencies-foo-1"), out) }) t.Run("Up no-deps links", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") res := c.RunDockerComposeCmd(t, "-f", "./fixtures/links/compose.yaml", "--project-name", projectName, "up", "--no-deps", "-d", "foo") assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-start-stop-with-dependencies-foo-1 Started"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "Container e2e-start-stop-with-dependencies-bar-1 Started"), res.Combined()) }) t.Run("down", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) } func TestStartStopWithOneOffs(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-start-stop-with-oneoffs" t.Run("Up", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/dependencies/compose.yaml", "--project-name", projectName, "up", "-d") assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-start-stop-with-oneoffs-foo-1 Started"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-start-stop-with-oneoffs-bar-1 Started"), res.Combined()) }) t.Run("run one-off", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/dependencies/compose.yaml", "--project-name", projectName, "run", "-d", "bar", "sleep", "infinity") res := c.RunDockerComposeCmd(t, "--project-name", projectName, "ps", "-a") assert.Assert(t, strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-foo-1"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-bar-1"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-bar-run"), res.Combined()) }) t.Run("stop (not one-off containers)", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "stop") assert.Assert(t, strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-foo-1"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-bar-1"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "e2e_start_stop_with_oneoffs-bar-run"), res.Combined()) res = c.RunDockerComposeCmd(t, "--project-name", projectName, "ps", "-a", "--status", "running") assert.Assert(t, strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-bar-run"), res.Combined()) }) t.Run("start (not one-off containers)", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "start") assert.Assert(t, strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-foo-1"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-bar-1"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-bar-run"), res.Combined()) }) t.Run("restart (not one-off containers)", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "restart") assert.Assert(t, strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-foo-1"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-bar-1"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-bar-run"), res.Combined()) }) t.Run("down", func(t *testing.T) { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--remove-orphans") res := c.RunDockerComposeCmd(t, "--project-name", projectName, "ps", "-a", "--status", "running") assert.Assert(t, !strings.Contains(res.Combined(), "e2e-start-stop-with-oneoffs-bar"), res.Combined()) }) } func TestStartAlreadyRunning(t *testing.T) { cli := NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=e2e-start-stop-svc-already-running", "COMPOSE_FILE=./fixtures/start-stop/compose.yaml")) t.Cleanup(func() { cli.RunDockerComposeCmd(t, "down", "--remove-orphans", "-v", "-t", "0") }) cli.RunDockerComposeCmd(t, "up", "-d", "--wait") res := cli.RunDockerComposeCmd(t, "start", "simple") assert.Equal(t, res.Stdout(), "", "No output should have been written to stdout") } func TestStopAlreadyStopped(t *testing.T) { cli := NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=e2e-start-stop-svc-already-stopped", "COMPOSE_FILE=./fixtures/start-stop/compose.yaml")) t.Cleanup(func() { cli.RunDockerComposeCmd(t, "down", "--remove-orphans", "-v", "-t", "0") }) cli.RunDockerComposeCmd(t, "up", "-d", "--wait") // stop the container cli.RunDockerComposeCmd(t, "stop", "simple") // attempt to stop it again res := cli.RunDockerComposeCmdNoCheck(t, "stop", "simple") // TODO: for consistency, this should NOT write any output because the // container is already stopped res.Assert(t, icmd.Expected{ ExitCode: 0, Err: "Container e2e-start-stop-svc-already-stopped-simple-1 Stopped", }) } func TestStartStopMultipleServices(t *testing.T) { cli := NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=e2e-start-stop-svc-multiple", "COMPOSE_FILE=./fixtures/start-stop/compose.yaml")) t.Cleanup(func() { cli.RunDockerComposeCmd(t, "down", "--remove-orphans", "-v", "-t", "0") }) cli.RunDockerComposeCmd(t, "up", "-d", "--wait") res := cli.RunDockerComposeCmd(t, "stop", "simple", "another") services := []string{"simple", "another"} for _, svc := range services { stopMsg := fmt.Sprintf("Container e2e-start-stop-svc-multiple-%s-1 Stopped", svc) assert.Assert(t, strings.Contains(res.Stderr(), stopMsg), fmt.Sprintf("Missing stop message for %s\n%s", svc, res.Combined())) } res = cli.RunDockerComposeCmd(t, "start", "simple", "another") for _, svc := range services { startMsg := fmt.Sprintf("Container e2e-start-stop-svc-multiple-%s-1 Started", svc) assert.Assert(t, strings.Contains(res.Stderr(), startMsg), fmt.Sprintf("Missing start message for %s\n%s", svc, res.Combined())) } } func TestStartSingleServiceAndDependency(t *testing.T) { cli := NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=e2e-start-single-deps", "COMPOSE_FILE=./fixtures/start-stop/start-stop-deps.yaml")) t.Cleanup(func() { cli.RunDockerComposeCmd(t, "down", "--remove-orphans", "-v", "-t", "0") }) cli.RunDockerComposeCmd(t, "create", "desired") res := cli.RunDockerComposeCmd(t, "start", "desired") desiredServices := []string{"desired", "dep_1", "dep_2"} for _, s := range desiredServices { startMsg := fmt.Sprintf("Container e2e-start-single-deps-%s-1 Started", s) assert.Assert(t, strings.Contains(res.Combined(), startMsg), fmt.Sprintf("Missing start message for service: %s\n%s", s, res.Combined())) } undesiredServices := []string{"another", "another_2"} for _, s := range undesiredServices { assert.Assert(t, !strings.Contains(res.Combined(), s), fmt.Sprintf("Shouldn't have message for service: %s\n%s", s, res.Combined())) } } func TestStartStopMultipleFiles(t *testing.T) { cli := NewParallelCLI(t, WithEnv("COMPOSE_PROJECT_NAME=e2e-start-stop-svc-multiple-files")) t.Cleanup(func() { cli.RunDockerComposeCmd(t, "-p", "e2e-start-stop-svc-multiple-files", "down", "--remove-orphans") }) cli.RunDockerComposeCmd(t, "-f", "./fixtures/start-stop/compose.yaml", "up", "-d") cli.RunDockerComposeCmd(t, "-f", "./fixtures/start-stop/other.yaml", "up", "-d") res := cli.RunDockerComposeCmd(t, "-f", "./fixtures/start-stop/compose.yaml", "stop") assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-start-stop-svc-multiple-files-simple-1 Stopped"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-start-stop-svc-multiple-files-another-1 Stopped"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "Container e2e-start-stop-svc-multiple-files-a-different-one-1 Stopped"), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "Container e2e-start-stop-svc-multiple-files-and-another-one-1 Stopped"), res.Combined()) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/recreate_no_deps_test.go
pkg/e2e/recreate_no_deps_test.go
/* Copyright 2022 Docker Compose CLI 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 e2e import ( "testing" "gotest.tools/v3/icmd" ) func TestRecreateWithNoDeps(t *testing.T) { c := NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=recreate-no-deps", )) res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/dependencies/recreate-no-deps.yaml", "up", "-d") res.Assert(t, icmd.Success) res = c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/dependencies/recreate-no-deps.yaml", "up", "-d", "--force-recreate", "--no-deps", "my-service") res.Assert(t, icmd.Success) RequireServiceState(t, c, "my-service", "running") c.RunDockerComposeCmd(t, "down") }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/pause_test.go
pkg/e2e/pause_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "encoding/json" "errors" "fmt" "net" "net/http" "os" "testing" "time" "github.com/stretchr/testify/require" "gotest.tools/v3/icmd" ) func TestPause(t *testing.T) { if _, ok := os.LookupEnv("CI"); ok { t.Skip("Skipping test on CI... flaky") } cli := NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=e2e-pause", "COMPOSE_FILE=./fixtures/pause/compose.yaml")) cleanup := func() { cli.RunDockerComposeCmd(t, "down", "-v", "--remove-orphans", "-t", "0") } cleanup() t.Cleanup(cleanup) // launch both services and verify that they are accessible cli.RunDockerComposeCmd(t, "up", "-d") urls := map[string]string{ "a": urlForService(t, cli, "a", 80), "b": urlForService(t, cli, "b", 80), } for _, url := range urls { HTTPGetWithRetry(t, url, http.StatusOK, 50*time.Millisecond, 20*time.Second) } // pause a and verify that it can no longer be hit but b still can cli.RunDockerComposeCmd(t, "pause", "a") httpClient := http.Client{Timeout: 250 * time.Millisecond} resp, err := httpClient.Get(urls["a"]) if resp != nil { _ = resp.Body.Close() } require.Error(t, err, "a should no longer respond") var netErr net.Error errors.As(err, &netErr) require.True(t, netErr.Timeout(), "Error should have indicated a timeout") HTTPGetWithRetry(t, urls["b"], http.StatusOK, 50*time.Millisecond, 5*time.Second) // unpause a and verify that both containers work again cli.RunDockerComposeCmd(t, "unpause", "a") for _, url := range urls { HTTPGetWithRetry(t, url, http.StatusOK, 50*time.Millisecond, 5*time.Second) } } func TestPauseServiceNotRunning(t *testing.T) { cli := NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=e2e-pause-svc-not-running", "COMPOSE_FILE=./fixtures/pause/compose.yaml")) cleanup := func() { cli.RunDockerComposeCmd(t, "down", "-v", "--remove-orphans", "-t", "0") } cleanup() t.Cleanup(cleanup) // pause a and verify that it can no longer be hit but b still can res := cli.RunDockerComposeCmdNoCheck(t, "pause", "a") // TODO: `docker pause` errors in this case, should Compose be consistent? res.Assert(t, icmd.Expected{ExitCode: 0}) } func TestPauseServiceAlreadyPaused(t *testing.T) { cli := NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=e2e-pause-svc-already-paused", "COMPOSE_FILE=./fixtures/pause/compose.yaml")) cleanup := func() { cli.RunDockerComposeCmd(t, "down", "-v", "--remove-orphans", "-t", "0") } cleanup() t.Cleanup(cleanup) // launch a and wait for it to come up cli.RunDockerComposeCmd(t, "up", "--menu=false", "--wait", "a") HTTPGetWithRetry(t, urlForService(t, cli, "a", 80), http.StatusOK, 50*time.Millisecond, 10*time.Second) // pause a twice - first time should pass, second time fail cli.RunDockerComposeCmd(t, "pause", "a") res := cli.RunDockerComposeCmdNoCheck(t, "pause", "a") res.Assert(t, icmd.Expected{ExitCode: 1, Err: "already paused"}) } func TestPauseServiceDoesNotExist(t *testing.T) { cli := NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=e2e-pause-svc-not-exist", "COMPOSE_FILE=./fixtures/pause/compose.yaml")) cleanup := func() { cli.RunDockerComposeCmd(t, "down", "-v", "--remove-orphans", "-t", "0") } cleanup() t.Cleanup(cleanup) // pause a and verify that it can no longer be hit but b still can res := cli.RunDockerComposeCmdNoCheck(t, "pause", "does_not_exist") // TODO: `compose down does_not_exist` and similar error, this should too res.Assert(t, icmd.Expected{ExitCode: 0}) } func urlForService(t testing.TB, cli *CLI, service string, targetPort int) string { t.Helper() return fmt.Sprintf( "http://localhost:%d", publishedPortForService(t, cli, service, targetPort), ) } func publishedPortForService(t testing.TB, cli *CLI, service string, targetPort int) int { t.Helper() res := cli.RunDockerComposeCmd(t, "ps", "--format=json", service) var svc struct { Publishers []struct { TargetPort int PublishedPort int } } require.NoError(t, json.Unmarshal([]byte(res.Stdout()), &svc), "Failed to parse `%s` output", res.Cmd.String()) for _, pp := range svc.Publishers { if pp.TargetPort == targetPort { return pp.PublishedPort } } require.Failf(t, "No published port for target port", "Target port: %d\nService: %s", targetPort, res.Combined()) return -1 }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/commit_test.go
pkg/e2e/commit_test.go
/* Copyright 2023 Docker Compose CLI 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 e2e import ( "testing" ) func TestCommit(t *testing.T) { const projectName = "e2e-commit-service" c := NewParallelCLI(t) cleanup := func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--timeout=0", "--remove-orphans") } t.Cleanup(cleanup) cleanup() c.RunDockerComposeCmd(t, "-f", "./fixtures/commit/compose.yaml", "--project-name", projectName, "up", "-d", "service") c.RunDockerComposeCmd( t, "--project-name", projectName, "commit", "-a", "John Hannibal Smith <hannibal@a-team.com>", "-c", "ENV DEBUG=true", "-m", "sample commit", "service", "service:latest", ) } func TestCommitWithReplicas(t *testing.T) { const projectName = "e2e-commit-service-with-replicas" c := NewParallelCLI(t) cleanup := func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--timeout=0", "--remove-orphans") } t.Cleanup(cleanup) cleanup() c.RunDockerComposeCmd(t, "-f", "./fixtures/commit/compose.yaml", "--project-name", projectName, "up", "-d", "service-with-replicas") c.RunDockerComposeCmd( t, "--project-name", projectName, "commit", "-a", "John Hannibal Smith <hannibal@a-team.com>", "-c", "ENV DEBUG=true", "-m", "sample commit", "--index=1", "service-with-replicas", "service-with-replicas:1", ) c.RunDockerComposeCmd( t, "--project-name", projectName, "commit", "-a", "John Hannibal Smith <hannibal@a-team.com>", "-c", "ENV DEBUG=true", "-m", "sample commit", "--index=2", "service-with-replicas", "service-with-replicas:2", ) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/providers_test.go
pkg/e2e/providers_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "bufio" "fmt" "os" "path/filepath" "slices" "strings" "testing" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestDependsOnMultipleProviders(t *testing.T) { provider, err := findExecutable("example-provider") assert.NilError(t, err) path := fmt.Sprintf("%s%s%s", os.Getenv("PATH"), string(os.PathListSeparator), filepath.Dir(provider)) c := NewParallelCLI(t, WithEnv("PATH="+path)) const projectName = "depends-on-multiple-providers" t.Cleanup(func() { c.cleanupWithDown(t, projectName) }) res := c.RunDockerComposeCmd(t, "-f", "fixtures/providers/depends-on-multiple-providers.yaml", "--project-name", projectName, "up") res.Assert(t, icmd.Success) env := getEnv(res.Combined(), false) assert.Check(t, slices.Contains(env, "PROVIDER1_URL=https://magic.cloud/provider1"), env) assert.Check(t, slices.Contains(env, "PROVIDER2_URL=https://magic.cloud/provider2"), env) } func getEnv(out string, run bool) []string { var env []string scanner := bufio.NewScanner(strings.NewReader(out)) for scanner.Scan() { line := scanner.Text() if !run && strings.HasPrefix(line, "test-1 | ") { env = append(env, line[10:]) } if run && strings.Contains(line, "=") && len(strings.Split(line, "=")) == 2 { env = append(env, line) } } slices.Sort(env) return env }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/exec_test.go
pkg/e2e/exec_test.go
/* Copyright 2023 Docker Compose CLI 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 e2e import ( "testing" "gotest.tools/v3/icmd" ) func TestExec(t *testing.T) { const projectName = "e2e-exec" c := NewParallelCLI(t) cleanup := func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--timeout=0", "--remove-orphans") } t.Cleanup(cleanup) cleanup() c.RunDockerComposeCmd(t, "-f", "./fixtures/exec/compose.yaml", "--project-name", projectName, "run", "-d", "test", "cat") res := c.RunDockerComposeCmdNoCheck(t, "--project-name", projectName, "exec", "--index=1", "test", "ps") res.Assert(t, icmd.Expected{Err: "service \"test\" is not running container #1", ExitCode: 1}) res = c.RunDockerComposeCmd(t, "--project-name", projectName, "exec", "test", "ps") res.Assert(t, icmd.Expected{Out: "cat"}) // one-off container was selected c.RunDockerComposeCmd(t, "-f", "./fixtures/exec/compose.yaml", "--project-name", projectName, "up", "-d") res = c.RunDockerComposeCmd(t, "--project-name", projectName, "exec", "test", "ps") res.Assert(t, icmd.Expected{Out: "tail"}) // service container was selected }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/pull_test.go
pkg/e2e/pull_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "strings" "testing" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestComposePull(t *testing.T) { c := NewParallelCLI(t) t.Run("Verify image pulled", func(t *testing.T) { // cleanup existing images c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/simple", "down", "--rmi", "all") res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/simple", "pull") output := res.Combined() assert.Assert(t, strings.Contains(output, "Image alpine:3.14 Pulled")) assert.Assert(t, strings.Contains(output, "Image alpine:3.15 Pulled")) // verify default policy is 'always' for pull command res = c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/simple", "pull") output = res.Combined() assert.Assert(t, strings.Contains(output, "Image alpine:3.14 Pulled")) assert.Assert(t, strings.Contains(output, "Image alpine:3.15 Pulled")) }) t.Run("Verify skipped pull if image is already present locally", func(t *testing.T) { // make sure the required image is present c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/image-present-locally", "pull") res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/image-present-locally", "pull") output := res.Combined() assert.Assert(t, strings.Contains(output, "alpine:3.13.12 Skipped Image is already present locally")) // image with :latest tag gets pulled regardless if pull_policy: missing or if_not_present assert.Assert(t, strings.Contains(output, "alpine:latest Pulled")) }) t.Run("Verify skipped no image to be pulled", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/no-image-name-given", "pull") output := res.Combined() assert.Assert(t, strings.Contains(output, "Skipped No image to be pulled")) }) t.Run("Verify pull failure", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/compose-pull/unknown-image", "pull") res.Assert(t, icmd.Expected{ExitCode: 1, Err: "pull access denied for does_not_exists"}) }) t.Run("Verify ignore pull failure", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/compose-pull/unknown-image", "pull", "--ignore-pull-failures") res.Assert(t, icmd.Expected{Err: "Some service image(s) must be built from source by running:"}) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/compose_run_build_once_test.go
pkg/e2e/compose_run_build_once_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "crypto/rand" "encoding/hex" "fmt" "regexp" "strings" "testing" "gotest.tools/v3/assert" ) // TestRunBuildOnce tests that services with pull_policy: build are only built once // when using 'docker compose run', even when they are dependencies. // This addresses a bug where dependencies were built twice: once in startDependencies // and once in ensureImagesExists. func TestRunBuildOnce(t *testing.T) { c := NewParallelCLI(t) t.Run("dependency with pull_policy build is built only once", func(t *testing.T) { projectName := randomProjectName("build-once") _ = c.RunDockerComposeCmd(t, "-p", projectName, "-f", "./fixtures/run-test/build-once.yaml", "down", "--rmi", "local", "--remove-orphans", "-v") res := c.RunDockerComposeCmd(t, "-p", projectName, "-f", "./fixtures/run-test/build-once.yaml", "--verbose", "run", "--build", "--rm", "curl") output := res.Stdout() nginxBuilds := countServiceBuilds(output, projectName, "nginx") assert.Equal(t, nginxBuilds, 1, "nginx should build once, built %d times\nOutput:\n%s", nginxBuilds, output) assert.Assert(t, strings.Contains(res.Stdout(), "curl service")) c.RunDockerComposeCmd(t, "-p", projectName, "-f", "./fixtures/run-test/build-once.yaml", "down", "--remove-orphans") }) t.Run("nested dependencies build only once each", func(t *testing.T) { projectName := randomProjectName("build-nested") _ = c.RunDockerComposeCmd(t, "-p", projectName, "-f", "./fixtures/run-test/build-once-nested.yaml", "down", "--rmi", "local", "--remove-orphans", "-v") res := c.RunDockerComposeCmd(t, "-p", projectName, "-f", "./fixtures/run-test/build-once-nested.yaml", "--verbose", "run", "--build", "--rm", "app") output := res.Stdout() dbBuilds := countServiceBuilds(output, projectName, "db") apiBuilds := countServiceBuilds(output, projectName, "api") appBuilds := countServiceBuilds(output, projectName, "app") assert.Equal(t, dbBuilds, 1, "db should build once, built %d times\nOutput:\n%s", dbBuilds, output) assert.Equal(t, apiBuilds, 1, "api should build once, built %d times\nOutput:\n%s", apiBuilds, output) assert.Equal(t, appBuilds, 1, "app should build once, built %d times\nOutput:\n%s", appBuilds, output) assert.Assert(t, strings.Contains(output, "App running")) c.RunDockerComposeCmd(t, "-p", projectName, "-f", "./fixtures/run-test/build-once-nested.yaml", "down", "--rmi", "local", "--remove-orphans", "-v") }) t.Run("service with no dependencies builds once", func(t *testing.T) { projectName := randomProjectName("build-simple") _ = c.RunDockerComposeCmd(t, "-p", projectName, "-f", "./fixtures/run-test/build-once-no-deps.yaml", "down", "--rmi", "local", "--remove-orphans") res := c.RunDockerComposeCmd(t, "-p", projectName, "-f", "./fixtures/run-test/build-once-no-deps.yaml", "run", "--build", "--rm", "simple") output := res.Stdout() simpleBuilds := countServiceBuilds(output, projectName, "simple") assert.Equal(t, simpleBuilds, 1, "simple should build once, built %d times\nOutput:\n%s", simpleBuilds, output) assert.Assert(t, strings.Contains(res.Stdout(), "Simple service")) c.RunDockerComposeCmd(t, "-p", projectName, "-f", "./fixtures/run-test/build-once-no-deps.yaml", "down", "--remove-orphans") }) } // countServiceBuilds counts how many times a service was built by matching // the "naming to *{projectName}-{serviceName}* done" pattern in the output func countServiceBuilds(output, projectName, serviceName string) int { pattern := regexp.MustCompile(`naming to .*` + regexp.QuoteMeta(projectName) + `-` + regexp.QuoteMeta(serviceName) + `.* done`) return len(pattern.FindAllString(output, -1)) } // randomProjectName generates a unique project name for parallel test execution // Format: prefix-<8 random hex chars> (e.g., "build-once-3f4a9b2c") func randomProjectName(prefix string) string { b := make([]byte, 4) // 4 bytes = 8 hex chars rand.Read(b) //nolint:errcheck return fmt.Sprintf("%s-%s", prefix, hex.EncodeToString(b)) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/env_file_test.go
pkg/e2e/env_file_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "strings" "testing" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestRawEnvFile(t *testing.T) { c := NewParallelCLI(t) defer c.cleanupWithDown(t, "dotenv") res := c.RunDockerComposeCmd(t, "-f", "./fixtures/dotenv/raw.yaml", "run", "test") assert.Equal(t, strings.TrimSpace(res.Stdout()), "'{\"key\": \"value\"}'") } func TestUnusedMissingEnvFile(t *testing.T) { c := NewParallelCLI(t) defer c.cleanupWithDown(t, "unused_dotenv") c.RunDockerComposeCmd(t, "-f", "./fixtures/env_file/compose.yaml", "up", "-d", "serviceA") // Runtime operations should work even with missing env file c.RunDockerComposeCmd(t, "-f", "./fixtures/env_file/compose.yaml", "ps") c.RunDockerComposeCmd(t, "-f", "./fixtures/env_file/compose.yaml", "logs") c.RunDockerComposeCmd(t, "-f", "./fixtures/env_file/compose.yaml", "down") } func TestRunEnvFile(t *testing.T) { c := NewParallelCLI(t) defer c.cleanupWithDown(t, "run_dotenv") res := c.RunDockerComposeCmd(t, "--project-directory", "./fixtures/env_file", "run", "serviceC", "env") res.Assert(t, icmd.Expected{Out: "FOO=BAR"}) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/cp_test.go
pkg/e2e/cp_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "os" "strings" "testing" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestCopy(t *testing.T) { c := NewParallelCLI(t) const projectName = "copy_e2e" t.Cleanup(func() { c.RunDockerComposeCmd(t, "-f", "./fixtures/cp-test/compose.yaml", "--project-name", projectName, "down") os.Remove("./fixtures/cp-test/from-default.txt") //nolint:errcheck os.Remove("./fixtures/cp-test/from-indexed.txt") //nolint:errcheck os.RemoveAll("./fixtures/cp-test/cp-folder2") //nolint:errcheck }) t.Run("start service", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/cp-test/compose.yaml", "--project-name", projectName, "up", "--scale", "nginx=5", "-d") }) t.Run("make sure service is running", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-p", projectName, "ps") assertServiceStatus(t, projectName, "nginx", "Up", res.Stdout()) }) t.Run("copy to container copies the file to the all containers by default", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/cp-test/compose.yaml", "-p", projectName, "cp", "./fixtures/cp-test/cp-me.txt", "nginx:/tmp/default.txt") res.Assert(t, icmd.Expected{ExitCode: 0}) output := c.RunDockerCmd(t, "exec", projectName+"-nginx-1", "cat", "/tmp/default.txt").Stdout() assert.Assert(t, strings.Contains(output, `hello world`), output) output = c.RunDockerCmd(t, "exec", projectName+"-nginx-2", "cat", "/tmp/default.txt").Stdout() assert.Assert(t, strings.Contains(output, `hello world`), output) output = c.RunDockerCmd(t, "exec", projectName+"-nginx-3", "cat", "/tmp/default.txt").Stdout() assert.Assert(t, strings.Contains(output, `hello world`), output) }) t.Run("copy to container with a given index copies the file to the given container", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/cp-test/compose.yaml", "-p", projectName, "cp", "--index=3", "./fixtures/cp-test/cp-me.txt", "nginx:/tmp/indexed.txt") res.Assert(t, icmd.Expected{ExitCode: 0}) output := c.RunDockerCmd(t, "exec", projectName+"-nginx-3", "cat", "/tmp/indexed.txt").Stdout() assert.Assert(t, strings.Contains(output, `hello world`), output) res = c.RunDockerOrExitError(t, "exec", projectName+"-nginx-2", "cat", "/tmp/indexed.txt") res.Assert(t, icmd.Expected{ExitCode: 1}) }) t.Run("copy from a container copies the file to the host from the first container by default", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/cp-test/compose.yaml", "-p", projectName, "cp", "nginx:/tmp/default.txt", "./fixtures/cp-test/from-default.txt") res.Assert(t, icmd.Expected{ExitCode: 0}) data, err := os.ReadFile("./fixtures/cp-test/from-default.txt") assert.NilError(t, err) assert.Equal(t, `hello world`, string(data)) }) t.Run("copy from a container with a given index copies the file to host", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/cp-test/compose.yaml", "-p", projectName, "cp", "--index=3", "nginx:/tmp/indexed.txt", "./fixtures/cp-test/from-indexed.txt") res.Assert(t, icmd.Expected{ExitCode: 0}) data, err := os.ReadFile("./fixtures/cp-test/from-indexed.txt") assert.NilError(t, err) assert.Equal(t, `hello world`, string(data)) }) t.Run("copy to and from a container also work with folder", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/cp-test/compose.yaml", "-p", projectName, "cp", "./fixtures/cp-test/cp-folder", "nginx:/tmp") res.Assert(t, icmd.Expected{ExitCode: 0}) output := c.RunDockerCmd(t, "exec", projectName+"-nginx-1", "cat", "/tmp/cp-folder/cp-me.txt").Stdout() assert.Assert(t, strings.Contains(output, `hello world from folder`), output) res = c.RunDockerComposeCmd(t, "-f", "./fixtures/cp-test/compose.yaml", "-p", projectName, "cp", "nginx:/tmp/cp-folder", "./fixtures/cp-test/cp-folder2") res.Assert(t, icmd.Expected{ExitCode: 0}) data, err := os.ReadFile("./fixtures/cp-test/cp-folder2/cp-me.txt") assert.NilError(t, err) assert.Equal(t, `hello world from folder`, string(data)) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/main_test.go
pkg/e2e/main_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "os" "testing" ) func TestMain(m *testing.M) { exitCode := m.Run() os.Exit(exitCode) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/compose_up_test.go
pkg/e2e/compose_up_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "strings" "testing" "time" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestUpWait(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-deps-wait" timeout := time.After(30 * time.Second) done := make(chan bool) go func() { //nolint:nolintlint,testifylint // helper asserts inside goroutine; acceptable in this e2e test res := c.RunDockerComposeCmd(t, "-f", "fixtures/dependencies/deps-completed-successfully.yaml", "--project-name", projectName, "up", "--wait", "-d") assert.Assert(t, strings.Contains(res.Combined(), "e2e-deps-wait-oneshot-1"), res.Combined()) done <- true }() select { case <-timeout: t.Fatal("test did not finish in time") case <-done: break } c.RunDockerComposeCmd(t, "--project-name", projectName, "down") } func TestUpExitCodeFrom(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-exit-code-from" res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/start-fail/start-depends_on-long-lived.yaml", "--project-name", projectName, "up", "--menu=false", "--exit-code-from=failure", "failure") res.Assert(t, icmd.Expected{ExitCode: 42}) c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--remove-orphans") } func TestUpExitCodeFromContainerKilled(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-exit-code-from-kill" res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/start-fail/start-depends_on-long-lived.yaml", "--project-name", projectName, "up", "--menu=false", "--exit-code-from=test") res.Assert(t, icmd.Expected{ExitCode: 143}) c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--remove-orphans") } func TestPortRange(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-port-range" reset := func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--remove-orphans", "--timeout=0") } reset() t.Cleanup(reset) res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/port-range/compose.yaml", "--project-name", projectName, "up", "-d") res.Assert(t, icmd.Success) } func TestStdoutStderr(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-stdout-stderr" res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/stdout-stderr/compose.yaml", "--project-name", projectName, "up", "--menu=false") res.Assert(t, icmd.Expected{Out: "log to stdout", Err: "log to stderr"}) c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--remove-orphans") } func TestLoggingDriver(t *testing.T) { c := NewCLI(t) const projectName = "e2e-logging-driver" defer c.cleanupWithDown(t, projectName) host := "HOST=127.0.0.1" res := c.RunDockerCmd(t, "info", "-f", "{{.OperatingSystem}}") os := res.Stdout() if strings.TrimSpace(os) == "Docker Desktop" { host = "HOST=host.docker.internal" } cmd := c.NewDockerComposeCmd(t, "-f", "fixtures/logging-driver/compose.yaml", "--project-name", projectName, "up", "-d") cmd.Env = append(cmd.Env, host, "BAR=foo") icmd.RunCmd(cmd).Assert(t, icmd.Success) cmd = c.NewDockerComposeCmd(t, "-f", "fixtures/logging-driver/compose.yaml", "--project-name", projectName, "up", "-d") cmd.Env = append(cmd.Env, host, "BAR=zot") icmd.RunCmd(cmd).Assert(t, icmd.Success) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/volumes_test.go
pkg/e2e/volumes_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "fmt" "net/http" "os" "path/filepath" "runtime" "strings" "testing" "time" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestLocalComposeVolume(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-volume" t.Run("up with build and no image name, volume", func(t *testing.T) { // ensure local test run does not reuse previously build image c.RunDockerOrExitError(t, "rmi", "compose-e2e-volume-nginx") c.RunDockerOrExitError(t, "volume", "rm", projectName+"-staticVol") c.RunDockerOrExitError(t, "volume", "rm", "myvolume") c.RunDockerComposeCmd(t, "--project-directory", "fixtures/volume-test", "--project-name", projectName, "up", "-d") }) t.Run("access bind mount data", func(t *testing.T) { output := HTTPGetWithRetry(t, "http://localhost:8090", http.StatusOK, 2*time.Second, 20*time.Second) assert.Assert(t, strings.Contains(output, "Hello from Nginx container")) }) t.Run("check container volume specs", func(t *testing.T) { res := c.RunDockerCmd(t, "inspect", "compose-e2e-volume-nginx2-1", "--format", "{{ json .Mounts }}") output := res.Stdout() assert.Assert(t, strings.Contains(output, `"Destination":"/usr/src/app/node_modules","Driver":"local","Mode":"z","RW":true,"Propagation":""`), output) assert.Assert(t, strings.Contains(output, `"Destination":"/myconfig","Mode":"","RW":false,"Propagation":"rprivate"`), output) }) t.Run("check config content", func(t *testing.T) { output := c.RunDockerCmd(t, "exec", "compose-e2e-volume-nginx2-1", "cat", "/myconfig").Stdout() assert.Assert(t, strings.Contains(output, `Hello from Nginx container`), output) }) t.Run("check secrets content", func(t *testing.T) { output := c.RunDockerCmd(t, "exec", "compose-e2e-volume-nginx2-1", "cat", "/run/secrets/mysecret").Stdout() assert.Assert(t, strings.Contains(output, `Hello from Nginx container`), output) }) t.Run("check container bind-mounts specs", func(t *testing.T) { res := c.RunDockerCmd(t, "inspect", "compose-e2e-volume-nginx-1", "--format", "{{ json .Mounts }}") output := res.Stdout() assert.Assert(t, strings.Contains(output, `"Type":"bind"`)) assert.Assert(t, strings.Contains(output, `"Destination":"/usr/share/nginx/html"`)) }) t.Run("should inherit anonymous volumes", func(t *testing.T) { c.RunDockerOrExitError(t, "exec", "compose-e2e-volume-nginx2-1", "touch", "/usr/src/app/node_modules/test") c.RunDockerComposeCmd(t, "--project-directory", "fixtures/volume-test", "--project-name", projectName, "up", "--force-recreate", "-d") c.RunDockerOrExitError(t, "exec", "compose-e2e-volume-nginx2-1", "ls", "/usr/src/app/node_modules/test") }) t.Run("should renew anonymous volumes", func(t *testing.T) { c.RunDockerOrExitError(t, "exec", "compose-e2e-volume-nginx2-1", "touch", "/usr/src/app/node_modules/test") c.RunDockerComposeCmd(t, "--project-directory", "fixtures/volume-test", "--project-name", projectName, "up", "--force-recreate", "--renew-anon-volumes", "-d") c.RunDockerOrExitError(t, "exec", "compose-e2e-volume-nginx2-1", "ls", "/usr/src/app/node_modules/test") }) t.Run("cleanup volume project", func(t *testing.T) { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--volumes") ls := c.RunDockerCmd(t, "volume", "ls").Stdout() assert.Assert(t, !strings.Contains(ls, projectName+"-staticVol")) assert.Assert(t, !strings.Contains(ls, "myvolume")) }) } func TestProjectVolumeBind(t *testing.T) { if composeStandaloneMode { t.Skip() } c := NewParallelCLI(t) const projectName = "compose-e2e-project-volume-bind" t.Run("up on project volume with bind specification", func(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("Running on Windows. Skipping...") } tmpDir, err := os.MkdirTemp("", projectName) assert.NilError(t, err) defer os.RemoveAll(tmpDir) //nolint c.RunDockerComposeCmd(t, "--project-name", projectName, "down") c.RunDockerOrExitError(t, "volume", "rm", "-f", projectName+"_project-data").Assert(t, icmd.Success) cmd := c.NewCmdWithEnv([]string{"TEST_DIR=" + tmpDir}, "docker", "compose", "--project-directory", "fixtures/project-volume-bind-test", "--project-name", projectName, "up", "-d") icmd.RunCmd(cmd).Assert(t, icmd.Success) defer c.RunDockerComposeCmd(t, "--project-name", projectName, "down") c.RunCmd(t, "sh", "-c", "echo SUCCESS > "+filepath.Join(tmpDir, "resultfile")).Assert(t, icmd.Success) ret := c.RunDockerOrExitError(t, "exec", "frontend", "bash", "-c", "cat /data/resultfile").Assert(t, icmd.Success) assert.Assert(t, strings.Contains(ret.Stdout(), "SUCCESS")) }) } func TestUpSwitchVolumes(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-switch-volumes" t.Cleanup(func() { c.cleanupWithDown(t, projectName) c.RunDockerCmd(t, "volume", "rm", "-f", "test_external_volume") c.RunDockerCmd(t, "volume", "rm", "-f", "test_external_volume_2") }) c.RunDockerCmd(t, "volume", "create", "test_external_volume") c.RunDockerCmd(t, "volume", "create", "test_external_volume_2") c.RunDockerComposeCmd(t, "-f", "./fixtures/switch-volumes/compose.yaml", "--project-name", projectName, "up", "-d") res := c.RunDockerCmd(t, "inspect", fmt.Sprintf("%s-app-1", projectName), "-f", "{{ (index .Mounts 0).Name }}") res.Assert(t, icmd.Expected{Out: "test_external_volume"}) c.RunDockerComposeCmd(t, "-f", "./fixtures/switch-volumes/compose2.yaml", "--project-name", projectName, "up", "-d") res = c.RunDockerCmd(t, "inspect", fmt.Sprintf("%s-app-1", projectName), "-f", "{{ (index .Mounts 0).Name }}") res.Assert(t, icmd.Expected{Out: "test_external_volume_2"}) } func TestUpRecreateVolumes(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-recreate-volumes" t.Cleanup(func() { c.cleanupWithDown(t, projectName) }) c.RunDockerComposeCmd(t, "-f", "./fixtures/recreate-volumes/compose.yaml", "--project-name", projectName, "up", "-d") res := c.RunDockerCmd(t, "volume", "inspect", fmt.Sprintf("%s_my_vol", projectName), "-f", "{{ index .Labels \"foo\" }}") res.Assert(t, icmd.Expected{Out: "bar"}) c.RunDockerComposeCmd(t, "-f", "./fixtures/recreate-volumes/compose2.yaml", "--project-name", projectName, "up", "-d", "-y") res = c.RunDockerCmd(t, "volume", "inspect", fmt.Sprintf("%s_my_vol", projectName), "-f", "{{ index .Labels \"foo\" }}") res.Assert(t, icmd.Expected{Out: "zot"}) } func TestUpRecreateVolumes_IgnoreBinds(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-recreate-volumes" t.Cleanup(func() { c.cleanupWithDown(t, projectName) }) c.RunDockerComposeCmd(t, "-f", "./fixtures/recreate-volumes/bind.yaml", "--project-name", projectName, "up", "-d") res := c.RunDockerComposeCmd(t, "-f", "./fixtures/recreate-volumes/bind.yaml", "--project-name", projectName, "up", "-d") assert.Check(t, !strings.Contains(res.Combined(), "Recreated")) } func TestImageVolume(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-image-volume" t.Cleanup(func() { c.cleanupWithDown(t, projectName) }) version := c.RunDockerCmd(t, "version", "-f", "{{.Server.Version}}") major, _, found := strings.Cut(version.Combined(), ".") assert.Assert(t, found) if major == "26" || major == "27" { t.Skip("Skipping test due to docker version < 28") } res := c.RunDockerComposeCmd(t, "-f", "./fixtures/volumes/compose.yaml", "--project-name", projectName, "up", "with_image") out := res.Combined() assert.Check(t, strings.Contains(out, "index.html")) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/assert.go
pkg/e2e/assert.go
/* Copyright 2022 Docker Compose CLI 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 e2e import ( "encoding/json" "strings" "testing" "github.com/stretchr/testify/require" ) // RequireServiceState ensures that the container is in the expected state // (running or exited). func RequireServiceState(t testing.TB, cli *CLI, service string, state string) { t.Helper() psRes := cli.RunDockerComposeCmd(t, "ps", "--all", "--format=json", service) var svc map[string]any require.NoError(t, json.Unmarshal([]byte(psRes.Stdout()), &svc), "Invalid `compose ps` JSON: command output: %s", psRes.Combined()) require.Equal(t, service, svc["Service"], "Found ps output for unexpected service") require.Equalf(t, strings.ToLower(state), strings.ToLower(svc["State"].(string)), "Service %q (%s) not in expected state", service, svc["Name"], ) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/framework.go
pkg/e2e/framework.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "encoding/json" "errors" "fmt" "io" "io/fs" "net/http" "os" "path/filepath" "runtime" "strings" "testing" "time" cp "github.com/otiai10/copy" "github.com/stretchr/testify/require" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" "gotest.tools/v3/poll" "github.com/docker/compose/v5/cmd/compose" ) var ( // DockerExecutableName is the OS dependent Docker CLI binary name DockerExecutableName = "docker" // DockerComposeExecutableName is the OS dependent Docker CLI binary name DockerComposeExecutableName = "docker-" + compose.PluginName // DockerScanExecutableName is the OS dependent Docker Scan plugin binary name DockerScanExecutableName = "docker-scan" // DockerBuildxExecutableName is the Os dependent Buildx plugin binary name DockerBuildxExecutableName = "docker-buildx" // DockerModelExecutableName is the Os dependent Docker-Model plugin binary name DockerModelExecutableName = "docker-model" // WindowsExecutableSuffix is the Windows executable suffix WindowsExecutableSuffix = ".exe" ) func init() { if runtime.GOOS == "windows" { DockerExecutableName += WindowsExecutableSuffix DockerComposeExecutableName += WindowsExecutableSuffix DockerScanExecutableName += WindowsExecutableSuffix DockerBuildxExecutableName += WindowsExecutableSuffix } } // CLI is used to wrap the CLI for end to end testing type CLI struct { // ConfigDir for Docker configuration (set as DOCKER_CONFIG) ConfigDir string // HomeDir for tools that look for user files (set as HOME) HomeDir string // env overrides to apply to every invoked command // // To populate, use WithEnv when creating a CLI instance. env []string } // CLIOption to customize behavior for all commands for a CLI instance. type CLIOption func(c *CLI) // NewParallelCLI marks the parent test as parallel and returns a CLI instance // suitable for usage across child tests. func NewParallelCLI(t *testing.T, opts ...CLIOption) *CLI { t.Helper() t.Parallel() return NewCLI(t, opts...) } // NewCLI creates a CLI instance for running E2E tests. func NewCLI(t testing.TB, opts ...CLIOption) *CLI { t.Helper() configDir := t.TempDir() copyLocalConfig(t, configDir) initializePlugins(t, configDir) initializeContextDir(t, configDir) c := &CLI{ ConfigDir: configDir, HomeDir: t.TempDir(), } for _, opt := range opts { opt(c) } c.RunDockerComposeCmdNoCheck(t, "version") return c } // WithEnv sets environment variables that will be passed to commands. func WithEnv(env ...string) CLIOption { return func(c *CLI) { c.env = append(c.env, env...) } } func copyLocalConfig(t testing.TB, configDir string) { t.Helper() // copy local config.json if exists localConfig := filepath.Join(os.Getenv("HOME"), ".docker", "config.json") // if no config present just continue if _, err := os.Stat(localConfig); err != nil { // copy the local config.json to the test config dir CopyFile(t, localConfig, filepath.Join(configDir, "config.json")) } } // initializePlugins copies the necessary plugin files to the temporary config // directory for the test. func initializePlugins(t testing.TB, configDir string) { t.Cleanup(func() { if t.Failed() { if conf, err := os.ReadFile(filepath.Join(configDir, "config.json")); err == nil { t.Logf("Config: %s\n", string(conf)) } t.Log("Contents of config dir:") for _, p := range dirContents(configDir) { t.Logf(" - %s", p) } } }) require.NoError(t, os.MkdirAll(filepath.Join(configDir, "cli-plugins"), 0o755), "Failed to create cli-plugins directory") composePlugin, err := findExecutable(DockerComposeExecutableName) if errors.Is(err, fs.ErrNotExist) { t.Logf("WARNING: docker-compose cli-plugin not found") } if err == nil { CopyFile(t, composePlugin, filepath.Join(configDir, "cli-plugins", DockerComposeExecutableName)) buildxPlugin, err := findPluginExecutable(DockerBuildxExecutableName) if err != nil { t.Logf("WARNING: docker-buildx cli-plugin not found, using default buildx installation.") } else { CopyFile(t, buildxPlugin, filepath.Join(configDir, "cli-plugins", DockerBuildxExecutableName)) } // We don't need a functional scan plugin, but a valid plugin binary CopyFile(t, composePlugin, filepath.Join(configDir, "cli-plugins", DockerScanExecutableName)) modelPlugin, err := findPluginExecutable(DockerModelExecutableName) if err != nil { t.Logf("WARNING: docker-model cli-plugin not found") } else { CopyFile(t, modelPlugin, filepath.Join(configDir, "cli-plugins", DockerModelExecutableName)) } } } func initializeContextDir(t testing.TB, configDir string) { dockerUserDir := ".docker/contexts" userDir, err := os.UserHomeDir() require.NoError(t, err, "Failed to get user home directory") userContextsDir := filepath.Join(userDir, dockerUserDir) if checkExists(userContextsDir) { dstContexts := filepath.Join(configDir, "contexts") require.NoError(t, cp.Copy(userContextsDir, dstContexts), "Failed to copy contexts directory") } } func checkExists(path string) bool { _, err := os.Stat(path) return err == nil } func dirContents(dir string) []string { var res []string _ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { res = append(res, path) return nil }) return res } func findExecutable(executableName string) (string, error) { bin := os.Getenv("COMPOSE_E2E_BIN_PATH") if bin == "" { _, filename, _, _ := runtime.Caller(0) buildPath := filepath.Join(filepath.Dir(filename), "..", "..", "bin", "build") var err error bin, err = filepath.Abs(filepath.Join(buildPath, executableName)) if err != nil { return "", err } } if _, err := os.Stat(bin); err == nil { return bin, nil } return "", fmt.Errorf("looking for %q: %w", bin, fs.ErrNotExist) } func findPluginExecutable(pluginExecutableName string) (string, error) { dockerUserDir := ".docker/cli-plugins" userDir, err := os.UserHomeDir() if err != nil { return "", err } candidates := []string{ filepath.Join(userDir, dockerUserDir), "/usr/local/lib/docker/cli-plugins", "/usr/local/libexec/docker/cli-plugins", "/usr/lib/docker/cli-plugins", "/usr/libexec/docker/cli-plugins", } for _, path := range candidates { bin, err := filepath.Abs(filepath.Join(path, pluginExecutableName)) if err != nil { return "", err } if _, err := os.Stat(bin); err == nil { return bin, nil } } return "", fmt.Errorf("plugin not found %s: %w", pluginExecutableName, os.ErrNotExist) } // CopyFile copies a file from a sourceFile to a destinationFile setting permissions to 0755 func CopyFile(t testing.TB, sourceFile string, destinationFile string) { t.Helper() src, err := os.Open(sourceFile) require.NoError(t, err, "Failed to open source file: %s") //nolint:errcheck defer src.Close() dst, err := os.OpenFile(destinationFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755) require.NoError(t, err, "Failed to open destination file: %s", destinationFile) //nolint:errcheck defer dst.Close() _, err = io.Copy(dst, src) require.NoError(t, err, "Failed to copy file: %s", sourceFile) } // BaseEnvironment provides the minimal environment variables used across all // Docker / Compose commands. func (c *CLI) BaseEnvironment() []string { env := []string{ "HOME=" + c.HomeDir, "USER=" + os.Getenv("USER"), "DOCKER_CONFIG=" + c.ConfigDir, "KUBECONFIG=invalid", "PATH=" + os.Getenv("PATH"), } dockerContextEnv, ok := os.LookupEnv("DOCKER_CONTEXT") if ok { env = append(env, "DOCKER_CONTEXT="+dockerContextEnv) } if coverdir, ok := os.LookupEnv("GOCOVERDIR"); ok { _, filename, _, _ := runtime.Caller(0) root := filepath.Join(filepath.Dir(filename), "..", "..") coverdir = filepath.Join(root, coverdir) env = append(env, fmt.Sprintf("GOCOVERDIR=%s", coverdir)) } return env } // NewCmd creates a cmd object configured with the test environment set func (c *CLI) NewCmd(command string, args ...string) icmd.Cmd { return icmd.Cmd{ Command: append([]string{command}, args...), Env: append(c.BaseEnvironment(), c.env...), } } // NewCmdWithEnv creates a cmd object configured with the test environment set with additional env vars func (c *CLI) NewCmdWithEnv(envvars []string, command string, args ...string) icmd.Cmd { // base env -> CLI overrides -> cmd overrides cmdEnv := append(c.BaseEnvironment(), c.env...) cmdEnv = append(cmdEnv, envvars...) return icmd.Cmd{ Command: append([]string{command}, args...), Env: cmdEnv, } } // MetricsSocket get the path where test metrics will be sent func (c *CLI) MetricsSocket() string { return filepath.Join(c.ConfigDir, "docker-cli.sock") } // NewDockerCmd creates a docker cmd without running it func (c *CLI) NewDockerCmd(t testing.TB, args ...string) icmd.Cmd { t.Helper() for _, arg := range args { if arg == compose.PluginName { t.Fatal("This test called 'RunDockerCmd' for 'compose'. Please prefer 'RunDockerComposeCmd' to be able to test as a plugin and standalone") } } return c.NewCmd(DockerExecutableName, args...) } // RunDockerOrExitError runs a docker command and returns a result func (c *CLI) RunDockerOrExitError(t testing.TB, args ...string) *icmd.Result { t.Helper() t.Logf("\t[%s] docker %s\n", t.Name(), strings.Join(args, " ")) return icmd.RunCmd(c.NewDockerCmd(t, args...)) } // RunCmd runs a command, expects no error and returns a result func (c *CLI) RunCmd(t testing.TB, args ...string) *icmd.Result { t.Helper() t.Logf("\t[%s] %s\n", t.Name(), strings.Join(args, " ")) assert.Assert(t, len(args) >= 1, "require at least one command in parameters") res := icmd.RunCmd(c.NewCmd(args[0], args[1:]...)) res.Assert(t, icmd.Success) return res } // RunCmdInDir runs a command in a given dir, expects no error and returns a result func (c *CLI) RunCmdInDir(t testing.TB, dir string, args ...string) *icmd.Result { t.Helper() t.Logf("\t[%s] %s\n", t.Name(), strings.Join(args, " ")) assert.Assert(t, len(args) >= 1, "require at least one command in parameters") cmd := c.NewCmd(args[0], args[1:]...) cmd.Dir = dir res := icmd.RunCmd(cmd) res.Assert(t, icmd.Success) return res } // RunDockerCmd runs a docker command, expects no error and returns a result func (c *CLI) RunDockerCmd(t testing.TB, args ...string) *icmd.Result { t.Helper() res := c.RunDockerOrExitError(t, args...) res.Assert(t, icmd.Success) return res } // RunDockerComposeCmd runs a docker compose command, expects no error and returns a result func (c *CLI) RunDockerComposeCmd(t testing.TB, args ...string) *icmd.Result { t.Helper() res := c.RunDockerComposeCmdNoCheck(t, args...) res.Assert(t, icmd.Success) return res } // RunDockerComposeCmdNoCheck runs a docker compose command, don't presume of any expectation and returns a result func (c *CLI) RunDockerComposeCmdNoCheck(t testing.TB, args ...string) *icmd.Result { t.Helper() cmd := c.NewDockerComposeCmd(t, args...) cmd.Stdout = os.Stdout t.Logf("Running command: %s", strings.Join(cmd.Command, " ")) return icmd.RunCmd(cmd) } // NewDockerComposeCmd creates a command object for Compose, either in plugin // or standalone mode (based on build tags). func (c *CLI) NewDockerComposeCmd(t testing.TB, args ...string) icmd.Cmd { t.Helper() if composeStandaloneMode { return c.NewCmd(ComposeStandalonePath(t), args...) } args = append([]string{"compose"}, args...) return c.NewCmd(DockerExecutableName, args...) } // ComposeStandalonePath returns the path to the locally-built Compose // standalone binary from the repo. // // This function will fail the test immediately if invoked when not running // in standalone test mode. func ComposeStandalonePath(t testing.TB) string { t.Helper() if !composeStandaloneMode { require.Fail(t, "Not running in standalone mode") } composeBinary, err := findExecutable(DockerComposeExecutableName) require.NoError(t, err, "Could not find standalone Compose binary (%q)", DockerComposeExecutableName) return composeBinary } // StdoutContains returns a predicate on command result expecting a string in stdout func StdoutContains(expected string) func(*icmd.Result) bool { return func(res *icmd.Result) bool { return strings.Contains(res.Stdout(), expected) } } func IsHealthy(service string) func(res *icmd.Result) bool { return func(res *icmd.Result) bool { type state struct { Name string `json:"name"` Health string `json:"health"` } decoder := json.NewDecoder(strings.NewReader(res.Stdout())) for decoder.More() { ps := state{} err := decoder.Decode(&ps) if err != nil { return false } if ps.Name == service && ps.Health == "healthy" { return true } } return false } } // WaitForCmdResult try to execute a cmd until resulting output matches given predicate func (c *CLI) WaitForCmdResult( t testing.TB, command icmd.Cmd, predicate func(*icmd.Result) bool, timeout time.Duration, delay time.Duration, ) { t.Helper() assert.Assert(t, timeout.Nanoseconds() > delay.Nanoseconds(), "timeout must be greater than delay") var res *icmd.Result checkStopped := func(logt poll.LogT) poll.Result { fmt.Printf("\t[%s] %s\n", t.Name(), strings.Join(command.Command, " ")) res = icmd.RunCmd(command) if !predicate(res) { return poll.Continue("Cmd output did not match requirement: %q", res.Combined()) } return poll.Success() } poll.WaitOn(t, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout)) } // WaitForCondition wait for predicate to execute to true func (c *CLI) WaitForCondition( t testing.TB, predicate func() (bool, string), timeout time.Duration, delay time.Duration, ) { t.Helper() checkStopped := func(logt poll.LogT) poll.Result { pass, description := predicate() if !pass { return poll.Continue("Condition not met: %q", description) } return poll.Success() } poll.WaitOn(t, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout)) } // Lines split output into lines func Lines(output string) []string { return strings.Split(strings.TrimSpace(output), "\n") } // HTTPGetWithRetry performs an HTTP GET on an `endpoint`, using retryDelay also as a request timeout. // In the case of an error or the response status is not the expected one, it retries the same request, // returning the response body as a string (empty if we could not reach it) func HTTPGetWithRetry( t testing.TB, endpoint string, expectedStatus int, retryDelay time.Duration, timeout time.Duration, ) string { t.Helper() var ( r *http.Response err error ) client := &http.Client{ Timeout: retryDelay, } fmt.Printf("\t[%s] GET %s\n", t.Name(), endpoint) checkUp := func(t poll.LogT) poll.Result { r, err = client.Get(endpoint) if err != nil { return poll.Continue("reaching %q: Error %s", endpoint, err.Error()) } if r.StatusCode == expectedStatus { return poll.Success() } return poll.Continue("reaching %q: %d != %d", endpoint, r.StatusCode, expectedStatus) } poll.WaitOn(t, checkUp, poll.WithDelay(retryDelay), poll.WithTimeout(timeout)) if r != nil { b, err := io.ReadAll(r.Body) assert.NilError(t, err) return string(b) } return "" } func (c *CLI) cleanupWithDown(t testing.TB, project string, args ...string) { t.Helper() c.RunDockerComposeCmd(t, append([]string{"-p", project, "down", "-v", "--remove-orphans"}, args...)...) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/logs_test.go
pkg/e2e/logs_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "fmt" "io" "os" "path/filepath" "strings" "testing" "time" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" "gotest.tools/v3/poll" ) func TestLocalComposeLogs(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-logs" t.Run("up", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/logs-test/compose.yaml", "--project-name", projectName, "up", "-d") }) t.Run("logs", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "logs") res.Assert(t, icmd.Expected{Out: `PING localhost`}) res.Assert(t, icmd.Expected{Out: `hello`}) }) t.Run("logs ping", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "logs", "ping") res.Assert(t, icmd.Expected{Out: `PING localhost`}) assert.Assert(t, !strings.Contains(res.Stdout(), "hello")) }) t.Run("logs hello", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "logs", "hello", "ping") res.Assert(t, icmd.Expected{Out: `PING localhost`}) res.Assert(t, icmd.Expected{Out: `hello`}) }) t.Run("logs hello index", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "logs", "--index", "2", "hello") // docker-compose logs hello // logs-test-hello-2 | hello // logs-test-hello-1 | hello t.Log(res.Stdout()) assert.Assert(t, !strings.Contains(res.Stdout(), "hello-1")) assert.Assert(t, strings.Contains(res.Stdout(), "hello-2")) }) t.Run("down", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) } func TestLocalComposeLogsFollow(t *testing.T) { c := NewCLI(t, WithEnv("REPEAT=20")) const projectName = "compose-e2e-logs" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) c.RunDockerComposeCmd(t, "-f", "./fixtures/logs-test/compose.yaml", "--project-name", projectName, "up", "-d", "ping") cmd := c.NewDockerComposeCmd(t, "--project-name", projectName, "logs", "-f") res := icmd.StartCmd(cmd) t.Cleanup(func() { _ = res.Cmd.Process.Kill() }) poll.WaitOn(t, expectOutput(res, "ping-1 "), poll.WithDelay(100*time.Millisecond), poll.WithTimeout(1*time.Second)) c.RunDockerComposeCmd(t, "-f", "./fixtures/logs-test/compose.yaml", "--project-name", projectName, "up", "-d") poll.WaitOn(t, expectOutput(res, "hello-1 "), poll.WithDelay(100*time.Millisecond), poll.WithTimeout(1*time.Second)) c.RunDockerComposeCmd(t, "-f", "./fixtures/logs-test/compose.yaml", "--project-name", projectName, "up", "-d", "--scale", "ping=2", "ping") poll.WaitOn(t, expectOutput(res, "ping-2 "), poll.WithDelay(100*time.Millisecond), poll.WithTimeout(20*time.Second)) } func TestLocalComposeLargeLogs(t *testing.T) { const projectName = "compose-e2e-large_logs" file := filepath.Join(t.TempDir(), "large.txt") c := NewCLI(t, WithEnv("FILE="+file)) t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) f, err := os.Create(file) assert.NilError(t, err) for i := 0; i < 300_000; i++ { _, err := io.WriteString(f, fmt.Sprintf("This is line %d in a laaaarge text file\n", i)) assert.NilError(t, err) } assert.NilError(t, f.Close()) cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/logs-test/cat.yaml", "--project-name", projectName, "up", "--abort-on-container-exit", "--menu=false") cmd.Stdout = io.Discard res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{Out: "test-1 exited with code 0"}) } func expectOutput(res *icmd.Result, expected string) func(t poll.LogT) poll.Result { return func(t poll.LogT) poll.Result { if strings.Contains(res.Stdout(), expected) { return poll.Success() } return poll.Continue("condition not met") } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/config_test.go
pkg/e2e/config_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "testing" "gotest.tools/v3/icmd" ) func TestLocalComposeConfig(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-config" t.Run("yaml", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/config/compose.yaml", "--project-name", projectName, "config") res.Assert(t, icmd.Expected{Out: ` ports: - mode: ingress target: 80 published: "8080" protocol: tcp`}) }) t.Run("json", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/config/compose.yaml", "--project-name", projectName, "config", "--format", "json") res.Assert(t, icmd.Expected{Out: `"published": "8080"`}) }) t.Run("--no-interpolate", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/config/compose.yaml", "--project-name", projectName, "config", "--no-interpolate") res.Assert(t, icmd.Expected{Out: `- ${PORT:-8080}:80`}) }) t.Run("--variables --format json", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/config/compose.yaml", "--project-name", projectName, "config", "--variables", "--format", "json") res.Assert(t, icmd.Expected{Out: `{ "PORT": { "Name": "PORT", "DefaultValue": "8080", "PresenceValue": "", "Required": false } }`}) }) t.Run("--variables --format yaml", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/config/compose.yaml", "--project-name", projectName, "config", "--variables", "--format", "yaml") res.Assert(t, icmd.Expected{Out: `PORT: name: PORT defaultvalue: "8080" presencevalue: "" required: false`}) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/noDeps_test.go
pkg/e2e/noDeps_test.go
//go:build !windows /* Copyright 2022 Docker Compose CLI 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 e2e import ( "fmt" "testing" "gotest.tools/v3/icmd" ) func TestNoDepsVolumeFrom(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-no-deps-volume-from" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) c.RunDockerComposeCmd(t, "-f", "fixtures/no-deps/volume-from.yaml", "--project-name", projectName, "up", "-d") c.RunDockerComposeCmd(t, "-f", "fixtures/no-deps/volume-from.yaml", "--project-name", projectName, "up", "--no-deps", "-d", "app") c.RunDockerCmd(t, "rm", "-f", fmt.Sprintf("%s-db-1", projectName)) res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/no-deps/volume-from.yaml", "--project-name", projectName, "up", "--no-deps", "-d", "app") res.Assert(t, icmd.Expected{ExitCode: 1, Err: "cannot share volume with service db: container missing"}) } func TestNoDepsNetworkMode(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-no-deps-network-mode" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) c.RunDockerComposeCmd(t, "-f", "fixtures/no-deps/network-mode.yaml", "--project-name", projectName, "up", "-d") c.RunDockerComposeCmd(t, "-f", "fixtures/no-deps/network-mode.yaml", "--project-name", projectName, "up", "--no-deps", "-d", "app") c.RunDockerCmd(t, "rm", "-f", fmt.Sprintf("%s-db-1", projectName)) res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/no-deps/network-mode.yaml", "--project-name", projectName, "up", "--no-deps", "-d", "app") res.Assert(t, icmd.Expected{ExitCode: 1, Err: "cannot share network namespace with service db: container missing"}) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/model_test.go
pkg/e2e/model_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "testing" ) func TestComposeModel(t *testing.T) { t.Skip("waiting for docker-model release") c := NewParallelCLI(t) defer c.cleanupWithDown(t, "model-test") c.RunDockerComposeCmd(t, "-f", "./fixtures/model/compose.yaml", "run", "test", "sh", "-c", "curl ${FOO_URL}") }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/ipc_test.go
pkg/e2e/ipc_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "fmt" "strings" "testing" "gotest.tools/v3/icmd" ) func TestIPC(t *testing.T) { c := NewParallelCLI(t) const projectName = "ipc_e2e" var cid string t.Run("create ipc mode container", func(t *testing.T) { res := c.RunDockerCmd(t, "run", "-d", "--rm", "--ipc=shareable", "--name", "ipc_mode_container", "alpine", "top") cid = strings.Trim(res.Stdout(), "\n") }) t.Run("up", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/ipc-test/compose.yaml", "--project-name", projectName, "up", "-d") }) t.Run("check running project", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-p", projectName, "ps") res.Assert(t, icmd.Expected{Out: `shareable`}) }) t.Run("check ipcmode in container inspect", func(t *testing.T) { res := c.RunDockerCmd(t, "inspect", projectName+"-shareable-1") res.Assert(t, icmd.Expected{Out: `"IpcMode": "shareable",`}) res = c.RunDockerCmd(t, "inspect", projectName+"-service-1") res.Assert(t, icmd.Expected{Out: `"IpcMode": "container:`}) res = c.RunDockerCmd(t, "inspect", projectName+"-container-1") res.Assert(t, icmd.Expected{Out: fmt.Sprintf(`"IpcMode": "container:%s",`, cid)}) }) t.Run("down", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) t.Run("remove ipc mode container", func(t *testing.T) { _ = c.RunDockerCmd(t, "rm", "-f", "ipc_mode_container") }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/hooks_test.go
pkg/e2e/hooks_test.go
/* Copyright 2023 Docker Compose CLI 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 e2e import ( "strings" "testing" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestPostStartHookInError(t *testing.T) { c := NewParallelCLI(t) const projectName = "hooks-post-start-failure" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "-v", "--remove-orphans", "-t", "0") }) res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/hooks/poststart/compose-error.yaml", "--project-name", projectName, "up", "-d") res.Assert(t, icmd.Expected{ExitCode: 1}) assert.Assert(t, strings.Contains(res.Combined(), "test hook exited with status 127"), res.Combined()) } func TestPostStartHookSuccess(t *testing.T) { c := NewParallelCLI(t) const projectName = "hooks-post-start-success" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "-v", "--remove-orphans", "-t", "0") }) res := c.RunDockerComposeCmd(t, "-f", "fixtures/hooks/poststart/compose-success.yaml", "--project-name", projectName, "up", "-d") res.Assert(t, icmd.Expected{ExitCode: 0}) } func TestPreStopHookSuccess(t *testing.T) { c := NewParallelCLI(t) const projectName = "hooks-pre-stop-success" t.Cleanup(func() { c.RunDockerComposeCmd(t, "-f", "fixtures/hooks/prestop/compose-success.yaml", "--project-name", projectName, "down", "-v", "--remove-orphans", "-t", "0") }) res := c.RunDockerComposeCmd(t, "-f", "fixtures/hooks/prestop/compose-success.yaml", "--project-name", projectName, "up", "-d") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-f", "fixtures/hooks/prestop/compose-success.yaml", "--project-name", projectName, "down", "-v", "--remove-orphans", "-t", "0") res.Assert(t, icmd.Expected{ExitCode: 0}) } func TestPreStopHookInError(t *testing.T) { c := NewParallelCLI(t) const projectName = "hooks-pre-stop-failure" t.Cleanup(func() { c.RunDockerComposeCmd(t, "-f", "fixtures/hooks/prestop/compose-success.yaml", "--project-name", projectName, "down", "-v", "--remove-orphans", "-t", "0") }) res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/hooks/prestop/compose-error.yaml", "--project-name", projectName, "up", "-d") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/hooks/prestop/compose-error.yaml", "--project-name", projectName, "down", "-v", "--remove-orphans", "-t", "0") res.Assert(t, icmd.Expected{ExitCode: 1}) assert.Assert(t, strings.Contains(res.Combined(), "sample hook exited with status 127")) } func TestPreStopHookSuccessWithPreviousStop(t *testing.T) { c := NewParallelCLI(t) const projectName = "hooks-pre-stop-success-with-previous-stop" t.Cleanup(func() { res := c.RunDockerComposeCmd(t, "-f", "fixtures/hooks/compose.yaml", "--project-name", projectName, "down", "-v", "--remove-orphans", "-t", "0") res.Assert(t, icmd.Expected{ExitCode: 0}) }) res := c.RunDockerComposeCmd(t, "-f", "fixtures/hooks/compose.yaml", "--project-name", projectName, "up", "-d") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-f", "fixtures/hooks/compose.yaml", "--project-name", projectName, "stop", "sample") res.Assert(t, icmd.Expected{ExitCode: 0}) } func TestPostStartAndPreStopHook(t *testing.T) { c := NewParallelCLI(t) const projectName = "hooks-post-start-and-pre-stop" t.Cleanup(func() { res := c.RunDockerComposeCmd(t, "-f", "fixtures/hooks/compose.yaml", "--project-name", projectName, "down", "-v", "--remove-orphans", "-t", "0") res.Assert(t, icmd.Expected{ExitCode: 0}) }) res := c.RunDockerComposeCmd(t, "-f", "fixtures/hooks/compose.yaml", "--project-name", projectName, "up", "-d") res.Assert(t, icmd.Expected{ExitCode: 0}) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/publish_test.go
pkg/e2e/publish_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "fmt" "strings" "testing" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestPublishChecks(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-explicit-profiles" t.Run("publish error env_file", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "-f", "./fixtures/publish/compose-env-file.yml", "-p", projectName, "publish", "test/test") res.Assert(t, icmd.Expected{ExitCode: 1, Err: `service "serviceA" has env_file declared. To avoid leaking sensitive data,`}) }) t.Run("publish multiple errors env_file and environment", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "-f", "./fixtures/publish/compose-multi-env-config.yml", "-p", projectName, "publish", "test/test") // we don't in which order the services will be loaded, so we can't predict the order of the error messages assert.Assert(t, strings.Contains(res.Combined(), `service "serviceB" has env_file declared.`), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), `To avoid leaking sensitive data, you must either explicitly allow the sending of environment variables by using the --with-env flag, or remove sensitive data from your Compose configuration `), res.Combined()) }) t.Run("publish success environment", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/publish/compose-environment.yml", "-p", projectName, "publish", "test/test", "--with-env", "-y", "--dry-run") assert.Assert(t, strings.Contains(res.Combined(), "test/test publishing"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "test/test published"), res.Combined()) }) t.Run("publish success env_file", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/publish/compose-env-file.yml", "-p", projectName, "publish", "test/test", "--with-env", "-y", "--dry-run") assert.Assert(t, strings.Contains(res.Combined(), "test/test publishing"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "test/test published"), res.Combined()) }) t.Run("publish with extends", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/publish/compose-with-extends.yml", "-p", projectName, "publish", "test/test", "--dry-run") assert.Assert(t, strings.Contains(res.Combined(), "test/test published"), res.Combined()) }) t.Run("refuse to publish with bind mount", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/publish/compose-bind-mount.yml", "-p", projectName, "publish", "test/test", "--dry-run") cmd.Stdin = strings.NewReader("n\n") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{ExitCode: 0}) out := res.Combined() assert.Assert(t, strings.Contains(out, "you are about to publish bind mounts declaration within your OCI artifact."), out) assert.Assert(t, strings.Contains(out, "e2e/fixtures/publish:/user-data"), out) assert.Assert(t, strings.Contains(out, "Are you ok to publish these bind mount declarations?"), out) assert.Assert(t, !strings.Contains(out, "serviceA published"), out) }) t.Run("publish with bind mount", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/publish/compose-bind-mount.yml", "-p", projectName, "publish", "test/test", "--dry-run") cmd.Stdin = strings.NewReader("y\n") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{ExitCode: 0}) assert.Assert(t, strings.Contains(res.Combined(), "you are about to publish bind mounts declaration within your OCI artifact."), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "Are you ok to publish these bind mount declarations?"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "e2e/fixtures/publish:/user-data"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "test/test published"), res.Combined()) }) t.Run("refuse to publish with build section only", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "-f", "./fixtures/publish/compose-build-only.yml", "-p", projectName, "publish", "test/test", "--with-env", "-y", "--dry-run") res.Assert(t, icmd.Expected{ExitCode: 1}) assert.Assert(t, strings.Contains(res.Combined(), "your Compose stack cannot be published as it only contains a build section for service(s):"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "serviceA"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "serviceB"), res.Combined()) }) t.Run("refuse to publish with local include", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "-f", "./fixtures/publish/compose-local-include.yml", "-p", projectName, "publish", "test/test", "--dry-run") res.Assert(t, icmd.Expected{ExitCode: 1, Err: "cannot publish compose file with local includes"}) }) t.Run("detect sensitive data", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/publish/compose-sensitive.yml", "-p", projectName, "publish", "test/test", "--with-env", "--dry-run") cmd.Stdin = strings.NewReader("n\n") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{ExitCode: 0}) output := res.Combined() assert.Assert(t, strings.Contains(output, "you are about to publish sensitive data within your OCI artifact.\n"), output) assert.Assert(t, strings.Contains(output, "please double check that you are not leaking sensitive data"), output) assert.Assert(t, strings.Contains(output, "AWS Client ID\n\"services.serviceA.environment.AWS_ACCESS_KEY_ID\": A3TX1234567890ABCDEF"), output) assert.Assert(t, strings.Contains(output, "AWS Secret Key\n\"services.serviceA.environment.AWS_SECRET_ACCESS_KEY\": aws\"12345+67890/abcdefghijklm+NOPQRSTUVWXYZ+\""), output) assert.Assert(t, strings.Contains(output, "Github authentication\n\"GITHUB_TOKEN\": ghp_1234567890abcdefghijklmnopqrstuvwxyz"), output) assert.Assert(t, strings.Contains(output, "JSON Web Token\n\"\": eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."+ "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw"), output) assert.Assert(t, strings.Contains(output, "Private Key\n\"\": -----BEGIN DSA PRIVATE KEY-----\nwxyz+ABC=\n-----END DSA PRIVATE KEY-----"), output) }) } func TestPublish(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-publish" const registryName = projectName + "-registry" c.RunDockerCmd(t, "run", "--name", registryName, "-P", "-d", "registry:3") port := c.RunDockerCmd(t, "inspect", "--format", `{{ (index (index .NetworkSettings.Ports "5000/tcp") 0).HostPort }}`, registryName).Stdout() registry := "localhost:" + strings.TrimSpace(port) t.Cleanup(func() { c.RunDockerCmd(t, "rm", "--force", registryName) }) res := c.RunDockerComposeCmd(t, "-f", "./fixtures/publish/oci/compose.yaml", "-f", "./fixtures/publish/oci/compose-override.yaml", "-p", projectName, "publish", "--with-env", "--yes", "--insecure-registry", registry+"/test:test") res.Assert(t, icmd.Expected{ExitCode: 0}) // docker exec -it compose-e2e-publish-registry tree /var/lib/registry/docker/registry/v2/ cmd := c.NewDockerComposeCmd(t, "--verbose", "--project-name=oci", "--insecure-registry", registry, "-f", fmt.Sprintf("oci://%s/test:test", registry), "config") res = icmd.RunCmd(cmd, func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "XDG_CACHE_HOME="+t.TempDir()) }) res.Assert(t, icmd.Expected{ExitCode: 0}) assert.Equal(t, res.Stdout(), `name: oci services: app: environment: HELLO: WORLD image: alpine networks: default: null networks: default: name: oci_default `) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/compose_environment_test.go
pkg/e2e/compose_environment_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "strings" "testing" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestEnvPriority(t *testing.T) { c := NewParallelCLI(t) t.Run("up", func(t *testing.T) { c.RunDockerOrExitError(t, "rmi", "env-compose-priority") c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose-with-env.yaml", "up", "-d", "--build") }) // Full options activated // 1. Command Line (docker compose run --env <KEY[=VAL]>) <-- Result expected (From OS Environment) // 2. Compose File (service::environment section) // 3. Compose File (service::env_file section file) // 4. Container Image ENV directive // 5. Variable is not defined t.Run("compose file priority", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose-with-env.yaml", "--env-file", "./fixtures/environment/env-priority/.env.override", "run", "--rm", "-e", "WHEREAMI", "env-compose-priority") cmd.Env = append(cmd.Env, "WHEREAMI=shell") res := icmd.RunCmd(cmd) assert.Equal(t, strings.TrimSpace(res.Stdout()), "shell") }) // Full options activated // 1. Command Line (docker compose run --env <KEY[=VAL]>) <-- Result expected // 2. Compose File (service::environment section) // 3. Compose File (service::env_file section file) // 4. Container Image ENV directive // 5. Variable is not defined t.Run("compose file priority", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose-with-env.yaml", "--env-file", "./fixtures/environment/env-priority/.env.override", "run", "--rm", "-e", "WHEREAMI=shell", "env-compose-priority") res := icmd.RunCmd(cmd) assert.Equal(t, strings.TrimSpace(res.Stdout()), "shell") }) // No Compose file, all other options // 1. Command Line (docker compose run --env <KEY[=VAL]>) <-- Result expected (From OS Environment) // 2. Compose File (service::environment section) // 3. Compose File (service::env_file section file) // 4. Container Image ENV directive // 5. Variable is not defined t.Run("shell priority", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose.yaml", "--env-file", "./fixtures/environment/env-priority/.env.override", "run", "--rm", "-e", "WHEREAMI", "env-compose-priority") cmd.Env = append(cmd.Env, "WHEREAMI=shell") res := icmd.RunCmd(cmd) assert.Equal(t, strings.TrimSpace(res.Stdout()), "shell") }) // No Compose file, all other options with env variable from OS environment // 1. Command Line (docker compose run --env <KEY[=VAL]>) <-- Result expected (From environment) // 2. Compose File (service::environment section) // 3. Compose File (service::env_file section file) // 4. Container Image ENV directive // 5. Variable is not defined t.Run("shell priority file with default value", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose.yaml", "--env-file", "./fixtures/environment/env-priority/.env.override.with.default", "run", "--rm", "-e", "WHEREAMI", "env-compose-priority") cmd.Env = append(cmd.Env, "WHEREAMI=shell") res := icmd.RunCmd(cmd) assert.Equal(t, strings.TrimSpace(res.Stdout()), "shell") }) // No Compose file, all other options with env variable from OS environment // 1. Command Line (docker compose run --env <KEY[=VAL]>) <-- Result expected (From environment default value from file in --env-file) // 2. Compose File (service::environment section) // 3. Compose File (service::env_file section file) // 4. Container Image ENV directive // 5. Variable is not defined t.Run("shell priority implicitly set", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose.yaml", "--env-file", "./fixtures/environment/env-priority/.env.override.with.default", "run", "--rm", "-e", "WHEREAMI", "env-compose-priority") res := icmd.RunCmd(cmd) assert.Equal(t, strings.TrimSpace(res.Stdout()), "EnvFileDefaultValue") }) // No Compose file, all other options with env variable from OS environment // 1. Command Line (docker compose run --env <KEY[=VAL]>) <-- Result expected (From environment default value from file in COMPOSE_ENV_FILES) // 2. Compose File (service::environment section) // 3. Compose File (service::env_file section file) // 4. Container Image ENV directive // 5. Variable is not defined t.Run("shell priority from COMPOSE_ENV_FILES variable", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose.yaml", "run", "--rm", "-e", "WHEREAMI", "env-compose-priority") cmd.Env = append(cmd.Env, "COMPOSE_ENV_FILES=./fixtures/environment/env-priority/.env.override.with.default") res := icmd.RunCmd(cmd) stdout := res.Stdout() assert.Equal(t, strings.TrimSpace(stdout), "EnvFileDefaultValue") }) // No Compose file and env variable pass to the run command // 1. Command Line (docker compose run --env <KEY[=VAL]>) <-- Result expected // 2. Compose File (service::environment section) // 3. Compose File (service::env_file section file) // 4. Container Image ENV directive // 5. Variable is not defined t.Run("shell priority from run command", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose.yaml", "--env-file", "./fixtures/environment/env-priority/.env.override", "run", "--rm", "-e", "WHEREAMI=shell-run", "env-compose-priority") assert.Equal(t, strings.TrimSpace(res.Stdout()), "shell-run") }) // No Compose file & no env variable but override env file // 1. Command Line (docker compose run --env <KEY[=VAL]>) <-- Result expected (From environment patched by .env as a default --env-file value) // 2. Compose File (service::environment section) // 3. Compose File (service::env_file section file) // 4. Container Image ENV directive // 5. Variable is not defined t.Run("override env file from compose", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose-with-env-file.yaml", "run", "--rm", "-e", "WHEREAMI", "env-compose-priority") assert.Equal(t, strings.TrimSpace(res.Stdout()), "Env File") }) // No Compose file & no env variable but override by default env file // 1. Command Line (docker compose run --env <KEY[=VAL]>) <-- Result expected (From environment patched by --env-file value) // 2. Compose File (service::environment section) // 3. Compose File (service::env_file section file) // 4. Container Image ENV directive // 5. Variable is not defined t.Run("override env file", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose.yaml", "--env-file", "./fixtures/environment/env-priority/.env.override", "run", "--rm", "-e", "WHEREAMI", "env-compose-priority") assert.Equal(t, strings.TrimSpace(res.Stdout()), "override") }) // No Compose file & no env variable but override env file // 1. Command Line (docker compose run --env <KEY[=VAL]>) <-- Result expected (From environment patched by --env-file value) // 2. Compose File (service::environment section) // 3. Compose File (service::env_file section file) // 4. Container Image ENV directive // 5. Variable is not defined t.Run("env file", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose.yaml", "run", "--rm", "-e", "WHEREAMI", "env-compose-priority") assert.Equal(t, strings.TrimSpace(res.Stdout()), "Env File") }) // No Compose file & no env variable, using an empty override env file // 1. Command Line (docker compose run --env <KEY[=VAL]>) // 2. Compose File (service::environment section) // 3. Compose File (service::env_file section file) // 4. Container Image ENV directive <-- Result expected // 5. Variable is not defined t.Run("use Dockerfile", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/env-priority/compose.yaml", "--env-file", "./fixtures/environment/env-priority/.env.empty", "run", "--rm", "-e", "WHEREAMI", "env-compose-priority") assert.Equal(t, strings.TrimSpace(res.Stdout()), "Dockerfile") }) t.Run("down", func(t *testing.T) { c.RunDockerComposeCmd(t, "--project-name", "env-priority", "down") }) } func TestEnvInterpolation(t *testing.T) { c := NewParallelCLI(t) t.Run("shell priority from run command", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "-f", "./fixtures/environment/env-interpolation/compose.yaml", "config") cmd.Env = append(cmd.Env, "WHEREAMI=shell") res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{Out: `IMAGE: default_env:shell`}) }) t.Run("shell priority from run command using default value fallback", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/env-interpolation-default-value/compose.yaml", "config"). Assert(t, icmd.Expected{Out: `IMAGE: default_env:EnvFileDefaultValue`}) }) } func TestCommentsInEnvFile(t *testing.T) { c := NewParallelCLI(t) t.Run("comments in env files", func(t *testing.T) { c.RunDockerOrExitError(t, "rmi", "env-file-comments") c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/env-file-comments/compose.yaml", "up", "-d", "--build") res := c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/env-file-comments/compose.yaml", "run", "--rm", "-e", "COMMENT", "-e", "NO_COMMENT", "env-file-comments") res.Assert(t, icmd.Expected{Out: `COMMENT=1234`}) res.Assert(t, icmd.Expected{Out: `NO_COMMENT=1234#5`}) c.RunDockerComposeCmd(t, "--project-name", "env-file-comments", "down", "--rmi", "all") }) } func TestUnsetEnv(t *testing.T) { c := NewParallelCLI(t) t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", "empty-variable", "down", "--rmi", "all") }) t.Run("override env variable", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/empty-variable/compose.yaml", "build") res := c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/empty-variable/compose.yaml", "run", "-e", "EMPTY=hello", "--rm", "empty-variable") res.Assert(t, icmd.Expected{Out: `=hello=`}) }) t.Run("unset env variable", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/environment/empty-variable/compose.yaml", "run", "--rm", "empty-variable") res.Assert(t, icmd.Expected{Out: `==`}) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/profiles_test.go
pkg/e2e/profiles_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "strings" "testing" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) const ( profiledService = "profiled-service" regularService = "regular-service" ) func TestExplicitProfileUsage(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-explicit-profiles" const profileName = "test-profile" t.Run("compose up with profile", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "--profile", profileName, "up", "-d") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps") res.Assert(t, icmd.Expected{Out: regularService}) res.Assert(t, icmd.Expected{Out: profiledService}) }) t.Run("compose stop with profile", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "--profile", profileName, "stop") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps", "--status", "running") assert.Assert(t, !strings.Contains(res.Combined(), regularService)) assert.Assert(t, !strings.Contains(res.Combined(), profiledService)) }) t.Run("compose start with profile", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "--profile", profileName, "start") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps", "--status", "running") res.Assert(t, icmd.Expected{Out: regularService}) res.Assert(t, icmd.Expected{Out: profiledService}) }) t.Run("compose restart with profile", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "--profile", profileName, "restart") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps", "--status", "running") res.Assert(t, icmd.Expected{Out: regularService}) res.Assert(t, icmd.Expected{Out: profiledService}) }) t.Run("down", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) t.Run("check containers after down", func(t *testing.T) { res := c.RunDockerCmd(t, "ps") assert.Assert(t, !strings.Contains(res.Combined(), projectName), res.Combined()) }) } func TestNoProfileUsage(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-no-profiles" t.Run("compose up without profile", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "up", "-d") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps") res.Assert(t, icmd.Expected{Out: regularService}) assert.Assert(t, !strings.Contains(res.Combined(), profiledService)) }) t.Run("compose stop without profile", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "stop") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps", "--status", "running") assert.Assert(t, !strings.Contains(res.Combined(), regularService)) assert.Assert(t, !strings.Contains(res.Combined(), profiledService)) }) t.Run("compose start without profile", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "start") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps", "--status", "running") res.Assert(t, icmd.Expected{Out: regularService}) assert.Assert(t, !strings.Contains(res.Combined(), profiledService)) }) t.Run("compose restart without profile", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "restart") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps", "--status", "running") res.Assert(t, icmd.Expected{Out: regularService}) assert.Assert(t, !strings.Contains(res.Combined(), profiledService)) }) t.Run("down", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) t.Run("check containers after down", func(t *testing.T) { res := c.RunDockerCmd(t, "ps") assert.Assert(t, !strings.Contains(res.Combined(), projectName), res.Combined()) }) } func TestActiveProfileViaTargetedService(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-via-target-service-profiles" const profileName = "test-profile" t.Run("compose up with service name", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "up", profiledService, "-d") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps") assert.Assert(t, !strings.Contains(res.Combined(), regularService)) res.Assert(t, icmd.Expected{Out: profiledService}) res = c.RunDockerComposeCmd(t, "-p", projectName, "--profile", profileName, "ps") assert.Assert(t, !strings.Contains(res.Combined(), regularService)) res.Assert(t, icmd.Expected{Out: profiledService}) }) t.Run("compose stop with service name", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "stop", profiledService) res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps", "--status", "running") assert.Assert(t, !strings.Contains(res.Combined(), regularService)) assert.Assert(t, !strings.Contains(res.Combined(), profiledService)) }) t.Run("compose start with service name", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "start", profiledService) res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps", "--status", "running") assert.Assert(t, !strings.Contains(res.Combined(), regularService)) res.Assert(t, icmd.Expected{Out: profiledService}) }) t.Run("compose restart with service name", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "-p", projectName, "restart") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps", "--status", "running") assert.Assert(t, !strings.Contains(res.Combined(), regularService)) res.Assert(t, icmd.Expected{Out: profiledService}) }) t.Run("down", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) t.Run("check containers after down", func(t *testing.T) { res := c.RunDockerCmd(t, "ps") assert.Assert(t, !strings.Contains(res.Combined(), projectName), res.Combined()) }) } func TestDotEnvProfileUsage(t *testing.T) { c := NewParallelCLI(t) const projectName = "compose-e2e-dotenv-profiles" const profileName = "test-profile" t.Cleanup(func() { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) t.Run("compose up with profile", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/compose.yaml", "--env-file", "./fixtures/profiles/test-profile.env", "-p", projectName, "--profile", profileName, "up", "-d") res.Assert(t, icmd.Expected{ExitCode: 0}) res = c.RunDockerComposeCmd(t, "-p", projectName, "ps") res.Assert(t, icmd.Expected{Out: regularService}) res.Assert(t, icmd.Expected{Out: profiledService}) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/export_test.go
pkg/e2e/export_test.go
/* Copyright 2023 Docker Compose CLI 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 e2e import ( "testing" ) func TestExport(t *testing.T) { const projectName = "e2e-export-service" c := NewParallelCLI(t) cleanup := func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--timeout=0", "--remove-orphans") } t.Cleanup(cleanup) cleanup() c.RunDockerComposeCmd(t, "-f", "./fixtures/export/compose.yaml", "--project-name", projectName, "up", "-d", "service") c.RunDockerComposeCmd(t, "--project-name", projectName, "export", "-o", "service.tar", "service") } func TestExportWithReplicas(t *testing.T) { const projectName = "e2e-export-service-with-replicas" c := NewParallelCLI(t) cleanup := func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "--timeout=0", "--remove-orphans") } t.Cleanup(cleanup) cleanup() c.RunDockerComposeCmd(t, "-f", "./fixtures/export/compose.yaml", "--project-name", projectName, "up", "-d", "service-with-replicas") c.RunDockerComposeCmd(t, "--project-name", projectName, "export", "-o", "r1.tar", "--index=1", "service-with-replicas") c.RunDockerComposeCmd(t, "--project-name", projectName, "export", "-o", "r2.tar", "--index=2", "service-with-replicas") }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/secrets_test.go
pkg/e2e/secrets_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "testing" "gotest.tools/v3/icmd" ) func TestSecretFromEnv(t *testing.T) { c := NewParallelCLI(t) defer c.cleanupWithDown(t, "env-secret") t.Run("compose run", func(t *testing.T) { res := icmd.RunCmd(c.NewDockerComposeCmd(t, "-f", "./fixtures/env-secret/compose.yaml", "run", "foo"), func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "SECRET=BAR") }) res.Assert(t, icmd.Expected{Out: "BAR"}) }) t.Run("secret uid", func(t *testing.T) { res := icmd.RunCmd(c.NewDockerComposeCmd(t, "-f", "./fixtures/env-secret/compose.yaml", "run", "foo", "ls", "-al", "/var/run/secrets/bar"), func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "SECRET=BAR") }) res.Assert(t, icmd.Expected{Out: "-r--r----- 1 1005 1005"}) }) } func TestSecretFromInclude(t *testing.T) { c := NewParallelCLI(t) defer c.cleanupWithDown(t, "env-secret-include") t.Run("compose run", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/env-secret/compose.yaml", "run", "included") res.Assert(t, icmd.Expected{Out: "this-is-secret"}) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/restart_test.go
pkg/e2e/restart_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "fmt" "strings" "testing" "time" testify "github.com/stretchr/testify/assert" "gotest.tools/v3/assert" ) func assertServiceStatus(t *testing.T, projectName, service, status string, ps string) { // match output with random spaces like: // e2e-start-stop-db-1 alpine:latest "echo hello" db 1 minutes ago Exited (0) 1 minutes ago regx := fmt.Sprintf("%s-%s-1.+%s\\s+.+%s.+", projectName, service, service, status) testify.Regexp(t, regx, ps) } func TestRestart(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-restart" t.Run("Up a project", func(t *testing.T) { // This is just to ensure the containers do NOT exist c.RunDockerComposeCmd(t, "--project-name", projectName, "down") res := c.RunDockerComposeCmd(t, "-f", "./fixtures/restart-test/compose.yaml", "--project-name", projectName, "up", "-d") assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-restart-restart-1 Started"), res.Combined()) c.WaitForCmdResult(t, c.NewDockerComposeCmd(t, "--project-name", projectName, "ps", "-a", "--format", "json"), StdoutContains(`"State":"exited"`), 10*time.Second, 1*time.Second) res = c.RunDockerComposeCmd(t, "--project-name", projectName, "ps", "-a") assertServiceStatus(t, projectName, "restart", "Exited", res.Stdout()) c.RunDockerComposeCmd(t, "-f", "./fixtures/restart-test/compose.yaml", "--project-name", projectName, "restart") // Give the same time but it must NOT exit time.Sleep(time.Second) res = c.RunDockerComposeCmd(t, "--project-name", projectName, "ps") assertServiceStatus(t, projectName, "restart", "Up", res.Stdout()) // Clean up c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) } func TestRestartWithDependencies(t *testing.T) { c := NewCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=e2e-restart-deps", )) baseService := "nginx" depWithRestart := "with-restart" depNoRestart := "no-restart" t.Cleanup(func() { c.RunDockerComposeCmd(t, "down", "--remove-orphans") }) c.RunDockerComposeCmd(t, "-f", "./fixtures/restart-test/compose-depends-on.yaml", "up", "-d") res := c.RunDockerComposeCmd(t, "restart", baseService) out := res.Combined() assert.Assert(t, strings.Contains(out, fmt.Sprintf("Container e2e-restart-deps-%s-1 Restarting", baseService)), out) assert.Assert(t, strings.Contains(out, fmt.Sprintf("Container e2e-restart-deps-%s-1 Healthy", baseService)), out) assert.Assert(t, strings.Contains(out, fmt.Sprintf("Container e2e-restart-deps-%s-1 Started", depWithRestart)), out) assert.Assert(t, !strings.Contains(out, depNoRestart), out) c = NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=e2e-restart-deps", "LABEL=recreate", )) res = c.RunDockerComposeCmd(t, "-f", "./fixtures/restart-test/compose-depends-on.yaml", "up", "-d") out = res.Combined() assert.Assert(t, strings.Contains(out, fmt.Sprintf("Container e2e-restart-deps-%s-1 Stopped", depWithRestart)), out) assert.Assert(t, strings.Contains(out, fmt.Sprintf("Container e2e-restart-deps-%s-1 Recreated", baseService)), out) assert.Assert(t, strings.Contains(out, fmt.Sprintf("Container e2e-restart-deps-%s-1 Healthy", baseService)), out) assert.Assert(t, strings.Contains(out, fmt.Sprintf("Container e2e-restart-deps-%s-1 Started", depWithRestart)), out) assert.Assert(t, strings.Contains(out, fmt.Sprintf("Container e2e-restart-deps-%s-1 Running", depNoRestart)), out) } func TestRestartWithProfiles(t *testing.T) { c := NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=e2e-restart-profiles", )) t.Cleanup(func() { c.RunDockerComposeCmd(t, "down", "--remove-orphans") }) c.RunDockerComposeCmd(t, "-f", "./fixtures/restart-test/compose.yaml", "--profile", "test", "up", "-d") res := c.RunDockerComposeCmd(t, "restart", "test") fmt.Println(res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "Container e2e-restart-profiles-test-1 Started"), res.Combined()) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/orphans_test.go
pkg/e2e/orphans_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "strings" "testing" "gotest.tools/v3/assert" ) func TestRemoveOrphans(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-orphans" defer c.cleanupWithDown(t, projectName) c.RunDockerComposeCmd(t, "-f", "./fixtures/orphans/compose.yaml", "-p", projectName, "run", "orphan") res := c.RunDockerComposeCmd(t, "-p", projectName, "ps", "--all") assert.Check(t, strings.Contains(res.Combined(), "compose-e2e-orphans-orphan-run-")) c.RunDockerComposeCmd(t, "-f", "./fixtures/orphans/compose.yaml", "-p", projectName, "up", "-d") res = c.RunDockerComposeCmd(t, "-p", projectName, "ps", "--all") assert.Check(t, !strings.Contains(res.Combined(), "compose-e2e-orphans-orphan-run-")) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/e2e_config_plugin.go
pkg/e2e/e2e_config_plugin.go
//go:build !standalone /* Copyright 2020 Docker Compose CLI 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 e2e const composeStandaloneMode = false
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/build_test.go
pkg/e2e/build_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "fmt" "net/http" "os" "regexp" "runtime" "strconv" "strings" "testing" "time" "github.com/stretchr/testify/require" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" "gotest.tools/v3/poll" ) func TestLocalComposeBuild(t *testing.T) { for _, env := range []string{"DOCKER_BUILDKIT=0", "DOCKER_BUILDKIT=1"} { c := NewCLI(t, WithEnv(strings.Split(env, ",")...)) t.Run(env+" build named and unnamed images", func(t *testing.T) { // ensure local test run does not reuse previously build image c.RunDockerOrExitError(t, "rmi", "-f", "build-test-nginx") c.RunDockerOrExitError(t, "rmi", "-f", "custom-nginx") res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test", "build") res.Assert(t, icmd.Expected{Out: "COPY static /usr/share/nginx/html"}) c.RunDockerCmd(t, "image", "inspect", "build-test-nginx") c.RunDockerCmd(t, "image", "inspect", "custom-nginx") }) t.Run(env+" build with build-arg", func(t *testing.T) { // ensure local test run does not reuse previously build image c.RunDockerOrExitError(t, "rmi", "-f", "build-test-nginx") c.RunDockerOrExitError(t, "rmi", "-f", "custom-nginx") c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test", "build", "--build-arg", "FOO=BAR") res := c.RunDockerCmd(t, "image", "inspect", "build-test-nginx") res.Assert(t, icmd.Expected{Out: `"FOO": "BAR"`}) }) t.Run(env+" build with build-arg set by env", func(t *testing.T) { // ensure local test run does not reuse previously build image c.RunDockerOrExitError(t, "rmi", "-f", "build-test-nginx") c.RunDockerOrExitError(t, "rmi", "-f", "custom-nginx") icmd.RunCmd(c.NewDockerComposeCmd(t, "--project-directory", "fixtures/build-test", "build", "--build-arg", "FOO"), func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "FOO=BAR") }).Assert(t, icmd.Success) res := c.RunDockerCmd(t, "image", "inspect", "build-test-nginx") res.Assert(t, icmd.Expected{Out: `"FOO": "BAR"`}) }) t.Run(env+" build with multiple build-args ", func(t *testing.T) { // ensure local test run does not reuse previously build image c.RunDockerOrExitError(t, "rmi", "-f", "multi-args-multiargs") cmd := c.NewDockerComposeCmd(t, "--project-directory", "fixtures/build-test/multi-args", "build") icmd.RunCmd(cmd, func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "DOCKER_BUILDKIT=0") }) res := c.RunDockerCmd(t, "image", "inspect", "multi-args-multiargs") res.Assert(t, icmd.Expected{Out: `"RESULT": "SUCCESS"`}) }) t.Run(env+" build as part of up", func(t *testing.T) { // ensure local test run does not reuse previously build image c.RunDockerOrExitError(t, "rmi", "-f", "build-test-nginx") c.RunDockerOrExitError(t, "rmi", "-f", "custom-nginx") res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test", "up", "-d") t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test", "down") }) res.Assert(t, icmd.Expected{Out: "COPY static /usr/share/nginx/html"}) res.Assert(t, icmd.Expected{Out: "COPY static2 /usr/share/nginx/html"}) output := HTTPGetWithRetry(t, "http://localhost:8070", http.StatusOK, 2*time.Second, 20*time.Second) assert.Assert(t, strings.Contains(output, "Hello from Nginx container")) c.RunDockerCmd(t, "image", "inspect", "build-test-nginx") c.RunDockerCmd(t, "image", "inspect", "custom-nginx") }) t.Run(env+" no rebuild when up again", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test", "up", "-d") assert.Assert(t, !strings.Contains(res.Stdout(), "COPY static")) }) t.Run(env+" rebuild when up --build", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test", "up", "-d", "--build") res.Assert(t, icmd.Expected{Out: "COPY static /usr/share/nginx/html"}) res.Assert(t, icmd.Expected{Out: "COPY static2 /usr/share/nginx/html"}) }) t.Run(env+" build --push ignored for unnamed images", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test", "build", "--push", "nginx") assert.Assert(t, !strings.Contains(res.Stdout(), "failed to push"), res.Stdout()) }) t.Run(env+" build --quiet", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test", "build", "--quiet") res.Assert(t, icmd.Expected{Out: ""}) }) t.Run(env+" cleanup build project", func(t *testing.T) { c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test", "down") c.RunDockerOrExitError(t, "rmi", "-f", "build-test-nginx") c.RunDockerOrExitError(t, "rmi", "-f", "custom-nginx") }) } } func TestBuildSSH(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("Running on Windows. Skipping...") } c := NewParallelCLI(t) t.Run("build failed with ssh default value", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/build-test", "build", "--ssh", "") res.Assert(t, icmd.Expected{ ExitCode: 1, Err: "invalid empty ssh agent socket: make sure SSH_AUTH_SOCK is set", }) }) t.Run("build succeed with ssh from Compose file", func(t *testing.T) { c.RunDockerOrExitError(t, "rmi", "build-test-ssh") c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test/ssh", "build") c.RunDockerCmd(t, "image", "inspect", "build-test-ssh") }) t.Run("build succeed with ssh from CLI", func(t *testing.T) { c.RunDockerOrExitError(t, "rmi", "build-test-ssh") c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/ssh/compose-without-ssh.yaml", "--project-directory", "fixtures/build-test/ssh", "build", "--no-cache", "--ssh", "fake-ssh=./fixtures/build-test/ssh/fake_rsa") c.RunDockerCmd(t, "image", "inspect", "build-test-ssh") }) /* FIXME disabled waiting for https://github.com/moby/buildkit/issues/5558 t.Run("build failed with wrong ssh key id from CLI", func(t *testing.T) { c.RunDockerOrExitError(t, "rmi", "build-test-ssh") res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/build-test/ssh/compose-without-ssh.yaml", "--project-directory", "fixtures/build-test/ssh", "build", "--no-cache", "--ssh", "wrong-ssh=./fixtures/build-test/ssh/fake_rsa") res.Assert(t, icmd.Expected{ ExitCode: 1, Err: "unset ssh forward key fake-ssh", }) }) */ t.Run("build succeed as part of up with ssh from Compose file", func(t *testing.T) { c.RunDockerOrExitError(t, "rmi", "build-test-ssh") c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test/ssh", "up", "-d", "--build") t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test/ssh", "down") }) c.RunDockerCmd(t, "image", "inspect", "build-test-ssh") }) } func TestBuildSecrets(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("skipping test on windows") } c := NewParallelCLI(t) t.Run("build with secrets", func(t *testing.T) { // ensure local test run does not reuse previously build image c.RunDockerOrExitError(t, "rmi", "build-test-secret") cmd := c.NewDockerComposeCmd(t, "--project-directory", "fixtures/build-test/secrets", "build") res := icmd.RunCmd(cmd, func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "SOME_SECRET=bar") }) res.Assert(t, icmd.Success) }) } func TestBuildTags(t *testing.T) { c := NewParallelCLI(t) t.Run("build with tags", func(t *testing.T) { // ensure local test run does not reuse previously build image c.RunDockerOrExitError(t, "rmi", "build-test-tags") c.RunDockerComposeCmd(t, "--project-directory", "./fixtures/build-test/tags", "build", "--no-cache") res := c.RunDockerCmd(t, "image", "inspect", "build-test-tags") expectedOutput := `"RepoTags": [ "docker/build-test-tags:1.0.0", "build-test-tags:latest", "other-image-name:v1.0.0" ], ` res.Assert(t, icmd.Expected{Out: expectedOutput}) }) } func TestBuildImageDependencies(t *testing.T) { doTest := func(t *testing.T, cli *CLI, args ...string) { resetState := func() { cli.RunDockerComposeCmd(t, "down", "--rmi=all", "-t=0") res := cli.RunDockerOrExitError(t, "image", "rm", "build-dependencies-service") if res.Error != nil { require.Contains(t, res.Stderr(), `No such image: build-dependencies-service`) } } resetState() t.Cleanup(resetState) // the image should NOT exist now res := cli.RunDockerOrExitError(t, "image", "inspect", "build-dependencies-service") res.Assert(t, icmd.Expected{ ExitCode: 1, Err: "No such image: build-dependencies-service", }) res = cli.RunDockerComposeCmd(t, args...) t.Log(res.Combined()) res = cli.RunDockerCmd(t, "image", "inspect", "--format={{ index .RepoTags 0 }}", "build-dependencies-service") res.Assert(t, icmd.Expected{Out: "build-dependencies-service:latest"}) res = cli.RunDockerComposeCmd(t, "down", "-t0", "--rmi=all", "--remove-orphans") t.Log(res.Combined()) res = cli.RunDockerOrExitError(t, "image", "inspect", "build-dependencies-service") res.Assert(t, icmd.Expected{ ExitCode: 1, Err: "No such image: build-dependencies-service", }) } t.Run("ClassicBuilder", func(t *testing.T) { cli := NewCLI(t, WithEnv( "DOCKER_BUILDKIT=0", "COMPOSE_FILE=./fixtures/build-dependencies/classic.yaml", )) doTest(t, cli, "build") doTest(t, cli, "build", "--with-dependencies", "service") }) t.Run("Bake by additional contexts", func(t *testing.T) { cli := NewCLI(t, WithEnv( "DOCKER_BUILDKIT=1", "COMPOSE_BAKE=1", "COMPOSE_FILE=./fixtures/build-dependencies/compose.yaml", )) doTest(t, cli, "--verbose", "build") doTest(t, cli, "--verbose", "build", "service") doTest(t, cli, "--verbose", "up", "--build", "service") }) } func TestBuildPlatformsWithCorrectBuildxConfig(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("Running on Windows. Skipping...") } c := NewParallelCLI(t) // declare builder result := c.RunDockerCmd(t, "buildx", "create", "--name", "build-platform", "--use", "--bootstrap") assert.NilError(t, result.Error) t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test/platforms", "down") _ = c.RunDockerCmd(t, "buildx", "rm", "-f", "build-platform") }) t.Run("platform not supported by builder", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/build-test/platforms", "-f", "fixtures/build-test/platforms/compose-unsupported-platform.yml", "build") res.Assert(t, icmd.Expected{ ExitCode: 1, Err: "no match for platform", }) }) t.Run("multi-arch build ok", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/build-test/platforms", "build") assert.NilError(t, res.Error, res.Stderr()) res.Assert(t, icmd.Expected{Out: "I am building for linux/arm64"}) res.Assert(t, icmd.Expected{Out: "I am building for linux/amd64"}) }) t.Run("multi-arch multi service builds ok", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/build-test/platforms", "-f", "fixtures/build-test/platforms/compose-multiple-platform-builds.yaml", "build") assert.NilError(t, res.Error, res.Stderr()) res.Assert(t, icmd.Expected{Out: "I'm Service A and I am building for linux/arm64"}) res.Assert(t, icmd.Expected{Out: "I'm Service A and I am building for linux/amd64"}) res.Assert(t, icmd.Expected{Out: "I'm Service B and I am building for linux/arm64"}) res.Assert(t, icmd.Expected{Out: "I'm Service B and I am building for linux/amd64"}) res.Assert(t, icmd.Expected{Out: "I'm Service C and I am building for linux/arm64"}) res.Assert(t, icmd.Expected{Out: "I'm Service C and I am building for linux/amd64"}) }) t.Run("multi-arch up --build", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/build-test/platforms", "up", "--build", "--menu=false") assert.NilError(t, res.Error, res.Stderr()) res.Assert(t, icmd.Expected{Out: "platforms-1 exited with code 0"}) }) t.Run("use DOCKER_DEFAULT_PLATFORM value when up --build", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "--project-directory", "fixtures/build-test/platforms", "up", "--build", "--menu=false") res := icmd.RunCmd(cmd, func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "DOCKER_DEFAULT_PLATFORM=linux/amd64") }) assert.NilError(t, res.Error, res.Stderr()) res.Assert(t, icmd.Expected{Out: "I am building for linux/amd64"}) assert.Assert(t, !strings.Contains(res.Stdout(), "I am building for linux/arm64")) }) t.Run("use service platform value when no build platforms defined ", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/build-test/platforms", "-f", "fixtures/build-test/platforms/compose-service-platform-and-no-build-platforms.yaml", "build") assert.NilError(t, res.Error, res.Stderr()) res.Assert(t, icmd.Expected{Out: "I am building for linux/386"}) }) } func TestBuildPrivileged(t *testing.T) { c := NewParallelCLI(t) // declare builder result := c.RunDockerCmd(t, "buildx", "create", "--name", "build-privileged", "--use", "--bootstrap", "--buildkitd-flags", `'--allow-insecure-entitlement=security.insecure'`) assert.NilError(t, result.Error) t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test/privileged", "down") _ = c.RunDockerCmd(t, "buildx", "rm", "-f", "build-privileged") }) t.Run("use build privileged mode to run insecure build command", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test/privileged", "build") capEffRe := regexp.MustCompile("CapEff:\t([0-9a-f]+)") matches := capEffRe.FindStringSubmatch(res.Stdout()) assert.Equal(t, 2, len(matches), "Did not match CapEff in output, matches: %v", matches) capEff, err := strconv.ParseUint(matches[1], 16, 64) assert.NilError(t, err, "Parsing CapEff: %s", matches[1]) // NOTE: can't use constant from x/sys/unix or tests won't compile on macOS/Windows // #define CAP_SYS_ADMIN 21 // https://github.com/torvalds/linux/blob/v6.1/include/uapi/linux/capability.h#L278 const capSysAdmin = 0x15 if capEff&capSysAdmin != capSysAdmin { t.Fatalf("CapEff %s is missing CAP_SYS_ADMIN", matches[1]) } }) } func TestBuildPlatformsStandardErrors(t *testing.T) { c := NewParallelCLI(t) t.Run("no platform support with Classic Builder", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "--project-directory", "fixtures/build-test/platforms", "build") res := icmd.RunCmd(cmd, func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "DOCKER_BUILDKIT=0") }) res.Assert(t, icmd.Expected{ ExitCode: 1, Err: "the classic builder doesn't support multi-arch build, set DOCKER_BUILDKIT=1 to use BuildKit", }) }) t.Run("builder does not support multi-arch", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/build-test/platforms", "build") res.Assert(t, icmd.Expected{ ExitCode: 1, Err: "Multi-platform build is not supported for the docker driver.", }) }) t.Run("service platform not defined in platforms build section", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/build-test/platforms", "-f", "fixtures/build-test/platforms/compose-service-platform-not-in-build-platforms.yaml", "build") res.Assert(t, icmd.Expected{ ExitCode: 1, Err: `service.build.platforms MUST include service.platform "linux/riscv64"`, }) }) t.Run("DOCKER_DEFAULT_PLATFORM value not defined in platforms build section", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "--project-directory", "fixtures/build-test/platforms", "build") res := icmd.RunCmd(cmd, func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "DOCKER_DEFAULT_PLATFORM=windows/amd64") }) res.Assert(t, icmd.Expected{ ExitCode: 1, Err: `service "platforms" build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: windows/amd64`, }) }) t.Run("no privileged support with Classic Builder", func(t *testing.T) { cmd := c.NewDockerComposeCmd(t, "--project-directory", "fixtures/build-test/privileged", "build") res := icmd.RunCmd(cmd, func(cmd *icmd.Cmd) { cmd.Env = append(cmd.Env, "DOCKER_BUILDKIT=0") }) res.Assert(t, icmd.Expected{ ExitCode: 1, Err: "the classic builder doesn't support privileged mode, set DOCKER_BUILDKIT=1 to use BuildKit", }) }) } func TestBuildBuilder(t *testing.T) { c := NewParallelCLI(t) builderName := "build-with-builder" // declare builder result := c.RunDockerCmd(t, "buildx", "create", "--name", builderName, "--use", "--bootstrap") assert.NilError(t, result.Error) t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test/", "down") _ = c.RunDockerCmd(t, "buildx", "rm", "-f", builderName) }) t.Run("use specific builder to run build command", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/build-test", "build", "--builder", builderName) assert.NilError(t, res.Error, res.Stderr()) }) t.Run("error when using specific builder to run build command", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/build-test", "build", "--builder", "unknown-builder") res.Assert(t, icmd.Expected{ ExitCode: 1, Err: fmt.Sprintf(`no builder %q found`, "unknown-builder"), }) }) } func TestBuildEntitlements(t *testing.T) { c := NewParallelCLI(t) // declare builder result := c.RunDockerCmd(t, "buildx", "create", "--name", "build-insecure", "--use", "--bootstrap", "--buildkitd-flags", `'--allow-insecure-entitlement=security.insecure'`) assert.NilError(t, result.Error) t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test/entitlements", "down") _ = c.RunDockerCmd(t, "buildx", "rm", "-f", "build-insecure") }) t.Run("use build privileged mode to run insecure build command", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/build-test/entitlements", "build") capEffRe := regexp.MustCompile("CapEff:\t([0-9a-f]+)") matches := capEffRe.FindStringSubmatch(res.Stdout()) assert.Equal(t, 2, len(matches), "Did not match CapEff in output, matches: %v", matches) capEff, err := strconv.ParseUint(matches[1], 16, 64) assert.NilError(t, err, "Parsing CapEff: %s", matches[1]) // NOTE: can't use constant from x/sys/unix or tests won't compile on macOS/Windows // #define CAP_SYS_ADMIN 21 // https://github.com/torvalds/linux/blob/v6.1/include/uapi/linux/capability.h#L278 const capSysAdmin = 0x15 if capEff&capSysAdmin != capSysAdmin { t.Fatalf("CapEff %s is missing CAP_SYS_ADMIN", matches[1]) } }) } func TestBuildDependsOn(t *testing.T) { c := NewParallelCLI(t) t.Cleanup(func() { c.RunDockerComposeCmd(t, "-f", "fixtures/build-dependencies/compose-depends_on.yaml", "down", "--rmi=local") }) res := c.RunDockerComposeCmd(t, "-f", "fixtures/build-dependencies/compose-depends_on.yaml", "--progress=plain", "up", "test2") out := res.Combined() assert.Check(t, strings.Contains(out, "test1 Built")) } func TestBuildSubset(t *testing.T) { c := NewParallelCLI(t) t.Cleanup(func() { c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/subset/compose.yaml", "down", "--rmi=local") }) res := c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/subset/compose.yaml", "build", "main") out := res.Combined() assert.Check(t, strings.Contains(out, "main Built")) } func TestBuildDependentImage(t *testing.T) { c := NewParallelCLI(t) t.Cleanup(func() { c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/dependencies/compose.yaml", "down", "--rmi=local") }) res := c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/dependencies/compose.yaml", "build", "firstbuild") out := res.Combined() assert.Check(t, strings.Contains(out, "firstbuild Built")) res = c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/dependencies/compose.yaml", "build", "secondbuild") out = res.Combined() assert.Check(t, strings.Contains(out, "secondbuild Built")) } func TestBuildSubDependencies(t *testing.T) { c := NewParallelCLI(t) t.Cleanup(func() { c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/sub-dependencies/compose.yaml", "down", "--rmi=local") }) res := c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/sub-dependencies/compose.yaml", "build", "main") out := res.Combined() assert.Check(t, strings.Contains(out, "main Built")) res = c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/sub-dependencies/compose.yaml", "up", "--build", "main") out = res.Combined() assert.Check(t, strings.Contains(out, "main Built")) } func TestBuildLongOutputLine(t *testing.T) { c := NewParallelCLI(t) t.Cleanup(func() { c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/long-output-line/compose.yaml", "down", "--rmi=local") }) res := c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/long-output-line/compose.yaml", "build", "long-line") out := res.Combined() assert.Check(t, strings.Contains(out, "long-line Built")) res = c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/long-output-line/compose.yaml", "up", "--build", "long-line") out = res.Combined() assert.Check(t, strings.Contains(out, "long-line Built")) } func TestBuildDependentImageWithProfile(t *testing.T) { c := NewParallelCLI(t) t.Cleanup(func() { c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/profiles/compose.yaml", "down", "--rmi=local") }) res := c.RunDockerComposeCmd(t, "-f", "fixtures/build-test/profiles/compose.yaml", "build", "secret-build-test") out := res.Combined() assert.Check(t, strings.Contains(out, "secret-build-test Built")) } func TestBuildTLS(t *testing.T) { t.Helper() c := NewParallelCLI(t) const dindBuilder = "e2e-dind-builder" tmp := t.TempDir() t.Cleanup(func() { c.RunDockerCmd(t, "rm", "-f", dindBuilder) c.RunDockerCmd(t, "context", "rm", dindBuilder) }) c.RunDockerCmd(t, "run", "--name", dindBuilder, "--privileged", "-p", "2376:2376", "-d", "docker:dind") poll.WaitOn(t, func(_ poll.LogT) poll.Result { res := c.RunDockerCmd(t, "logs", dindBuilder) if strings.Contains(res.Combined(), "API listen on [::]:2376") { return poll.Success() } return poll.Continue("waiting for Docker daemon to be running") }, poll.WithTimeout(10*time.Second)) time.Sleep(1 * time.Second) // wait for dind setup c.RunDockerCmd(t, "cp", dindBuilder+":/certs/client", tmp) c.RunDockerCmd(t, "context", "create", dindBuilder, "--docker", fmt.Sprintf("host=tcp://localhost:2376,ca=%s/client/ca.pem,cert=%s/client/cert.pem,key=%s/client/key.pem,skip-tls-verify=1", tmp, tmp, tmp)) cmd := c.NewDockerComposeCmd(t, "-f", "fixtures/build-test/minimal/compose.yaml", "build") cmd.Env = append(cmd.Env, "DOCKER_CONTEXT="+dindBuilder) cmd.Stdout = os.Stdout res := icmd.RunCmd(cmd) res.Assert(t, icmd.Expected{Err: "Built"}) } func TestBuildEscaped(t *testing.T) { c := NewParallelCLI(t) res := c.RunDockerComposeCmd(t, "--project-directory", "./fixtures/build-test/escaped", "build", "--no-cache", "foo") res.Assert(t, icmd.Expected{Out: "foo is ${bar}"}) res = c.RunDockerComposeCmd(t, "--project-directory", "./fixtures/build-test/escaped", "build", "--no-cache", "echo") res.Assert(t, icmd.Success) res = c.RunDockerComposeCmd(t, "--project-directory", "./fixtures/build-test/escaped", "build", "--no-cache", "arg") res.Assert(t, icmd.Success) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/cascade_test.go
pkg/e2e/cascade_test.go
//go:build !windows /* Copyright 2022 Docker Compose CLI 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 e2e import ( "strings" "testing" "gotest.tools/v3/assert" ) func TestCascadeStop(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-cascade-stop" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) res := c.RunDockerComposeCmd(t, "-f", "./fixtures/cascade/compose.yaml", "--project-name", projectName, "up", "--abort-on-container-exit") assert.Assert(t, strings.Contains(res.Combined(), "exit-1 exited with code 0"), res.Combined()) // no --exit-code-from, so this is not an error assert.Equal(t, res.ExitCode, 0) } func TestCascadeFail(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-cascade-fail" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) res := c.RunDockerComposeCmdNoCheck(t, "-f", "./fixtures/cascade/compose.yaml", "--project-name", projectName, "up", "--abort-on-container-failure") assert.Assert(t, strings.Contains(res.Combined(), "exit-1 exited with code 0"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), "fail-1 exited with code 111"), res.Combined()) // failing exit code should be propagated assert.Equal(t, res.ExitCode, 111) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/networks_test.go
pkg/e2e/networks_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "fmt" "net/http" "strings" "testing" "time" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) func TestNetworks(t *testing.T) { // fixture is shared with TestNetworkModes and is not safe to run concurrently const projectName = "network-e2e" c := NewCLI(t, WithEnv( "COMPOSE_PROJECT_NAME="+projectName, "COMPOSE_FILE=./fixtures/network-test/compose.yaml", )) c.RunDockerComposeCmd(t, "down", "-t0", "-v") c.RunDockerComposeCmd(t, "up", "-d") res := c.RunDockerComposeCmd(t, "ps") res.Assert(t, icmd.Expected{Out: `web`}) endpoint := "http://localhost:80" output := HTTPGetWithRetry(t, endpoint+"/words/noun", http.StatusOK, 2*time.Second, 20*time.Second) assert.Assert(t, strings.Contains(output, `"word":`)) res = c.RunDockerCmd(t, "network", "ls") res.Assert(t, icmd.Expected{Out: projectName + "_dbnet"}) res.Assert(t, icmd.Expected{Out: "microservices"}) res = c.RunDockerComposeCmd(t, "port", "words", "8080") res.Assert(t, icmd.Expected{Out: `0.0.0.0:8080`}) c.RunDockerComposeCmd(t, "down", "-t0", "-v") res = c.RunDockerCmd(t, "network", "ls") assert.Assert(t, !strings.Contains(res.Combined(), projectName), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), "microservices"), res.Combined()) } func TestNetworkAliases(t *testing.T) { c := NewParallelCLI(t) const projectName = "network_alias_e2e" defer c.cleanupWithDown(t, projectName) t.Run("up", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/network-alias/compose.yaml", "--project-name", projectName, "up", "-d") }) t.Run("curl alias", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/network-alias/compose.yaml", "--project-name", projectName, "exec", "-T", "container1", "curl", "http://alias-of-container2/") assert.Assert(t, strings.Contains(res.Stdout(), "Welcome to nginx!"), res.Stdout()) }) t.Run("curl links", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/network-alias/compose.yaml", "--project-name", projectName, "exec", "-T", "container1", "curl", "http://container/") assert.Assert(t, strings.Contains(res.Stdout(), "Welcome to nginx!"), res.Stdout()) }) t.Run("down", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) } func TestNetworkLinks(t *testing.T) { c := NewParallelCLI(t) const projectName = "network_link_e2e" t.Run("up", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/network-links/compose.yaml", "--project-name", projectName, "up", "-d") }) t.Run("curl links in default bridge network", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/network-links/compose.yaml", "--project-name", projectName, "exec", "-T", "container2", "curl", "http://container1/") assert.Assert(t, strings.Contains(res.Stdout(), "Welcome to nginx!"), res.Stdout()) }) t.Run("down", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) } func TestIPAMConfig(t *testing.T) { c := NewParallelCLI(t) const projectName = "ipam_e2e" t.Run("ensure we do not reuse previous networks", func(t *testing.T) { c.RunDockerOrExitError(t, "network", "rm", projectName+"_default") }) t.Run("up", func(t *testing.T) { c.RunDockerComposeCmd(t, "-f", "./fixtures/ipam/compose.yaml", "--project-name", projectName, "up", "-d") }) t.Run("ensure service get fixed IP assigned", func(t *testing.T) { res := c.RunDockerCmd(t, "inspect", projectName+"-foo-1", "-f", fmt.Sprintf(`{{ $network := index .NetworkSettings.Networks "%s_default" }}{{ $network.IPAMConfig.IPv4Address }}`, projectName)) res.Assert(t, icmd.Expected{Out: "10.1.0.100"}) }) t.Run("down", func(t *testing.T) { _ = c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) } func TestNetworkModes(t *testing.T) { // fixture is shared with TestNetworks and is not safe to run concurrently c := NewCLI(t) const projectName = "network_mode_service_run" defer c.cleanupWithDown(t, projectName) t.Run("run with service mode dependency", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "-f", "./fixtures/network-test/compose.yaml", "--project-name", projectName, "run", "-T", "mydb", "echo", "success") res.Assert(t, icmd.Expected{Out: "success"}) }) } func TestNetworkConfigChanged(t *testing.T) { t.Skip("unstable") // fixture is shared with TestNetworks and is not safe to run concurrently c := NewCLI(t) const projectName = "network_config_change" c.RunDockerComposeCmd(t, "-f", "./fixtures/network-test/compose.subnet.yaml", "--project-name", projectName, "up", "-d") t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) res := c.RunDockerComposeCmd(t, "--project-name", projectName, "exec", "test", "hostname", "-i") res.Assert(t, icmd.Expected{Out: "172.99.0."}) res.Combined() cmd := c.NewCmdWithEnv([]string{"SUBNET=192.168.0.0/16"}, "docker", "compose", "-f", "./fixtures/network-test/compose.subnet.yaml", "--project-name", projectName, "up", "-d") res = icmd.RunCmd(cmd) res.Assert(t, icmd.Success) out := res.Combined() fmt.Println(out) res = c.RunDockerComposeCmd(t, "--project-name", projectName, "exec", "test", "hostname", "-i") res.Assert(t, icmd.Expected{Out: "192.168.0."}) } func TestMacAddress(t *testing.T) { c := NewCLI(t) const projectName = "network_mac_address" c.RunDockerComposeCmd(t, "-f", "./fixtures/network-test/mac_address.yaml", "--project-name", projectName, "up", "-d") t.Cleanup(func() { c.cleanupWithDown(t, projectName) }) res := c.RunDockerCmd(t, "inspect", fmt.Sprintf("%s-test-1", projectName), "-f", "{{ (index .NetworkSettings.Networks \"network_mac_address_default\" ).MacAddress }}") res.Assert(t, icmd.Expected{Out: "00:e0:84:35:d0:e8"}) } func TestInterfaceName(t *testing.T) { c := NewCLI(t) version := c.RunDockerCmd(t, "version", "-f", "{{.Server.Version}}") major, _, found := strings.Cut(version.Combined(), ".") assert.Assert(t, found) if major == "26" || major == "27" { t.Skip("Skipping test due to docker version < 28") } const projectName = "network_interface_name" res := c.RunDockerComposeCmd(t, "-f", "./fixtures/network-interface-name/compose.yaml", "--project-name", projectName, "run", "test") t.Cleanup(func() { c.cleanupWithDown(t, projectName) }) res.Assert(t, icmd.Expected{Out: "foobar@"}) } func TestNetworkRecreate(t *testing.T) { c := NewCLI(t) const projectName = "network_recreate" t.Cleanup(func() { c.cleanupWithDown(t, projectName) }) c.RunDockerComposeCmd(t, "-f", "./fixtures/network-recreate/compose.yaml", "--project-name", projectName, "up", "-d") c = NewCLI(t, WithEnv("FOO=bar")) res := c.RunDockerComposeCmd(t, "-f", "./fixtures/network-recreate/compose.yaml", "--project-name", projectName, "--progress=plain", "up", "-d") err := res.Stderr() fmt.Println(err) res.Assert(t, icmd.Expected{Err: ` Container network_recreate-web-1 Stopped Network network_recreate_test Removed Network network_recreate_test Creating Network network_recreate_test Created Container network_recreate-web-1 Starting Container network_recreate-web-1 Started`}) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/bridge_test.go
pkg/e2e/bridge_test.go
/* Copyright 2020 Docker Compose CLI 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 e2e import ( "fmt" "path/filepath" "strings" "testing" "gotest.tools/v3/assert" ) func TestConvertAndTransformList(t *testing.T) { c := NewParallelCLI(t) const projectName = "bridge" const bridgeImageVersion = "v0.0.3" tmpDir := t.TempDir() t.Run("kubernetes manifests", func(t *testing.T) { kubedir := filepath.Join(tmpDir, "kubernetes") res := c.RunDockerComposeCmd(t, "-f", "./fixtures/bridge/compose.yaml", "--project-name", projectName, "bridge", "convert", "--output", kubedir, "--transformation", fmt.Sprintf("docker/compose-bridge-kubernetes:%s", bridgeImageVersion)) assert.NilError(t, res.Error) assert.Equal(t, res.ExitCode, 0) res = c.RunCmd(t, "diff", "-r", kubedir, "./fixtures/bridge/expected-kubernetes") assert.NilError(t, res.Error, res.Combined()) }) t.Run("helm charts", func(t *testing.T) { helmDir := filepath.Join(tmpDir, "helm") res := c.RunDockerComposeCmd(t, "-f", "./fixtures/bridge/compose.yaml", "--project-name", projectName, "bridge", "convert", "--output", helmDir, "--transformation", fmt.Sprintf("docker/compose-bridge-helm:%s", bridgeImageVersion)) assert.NilError(t, res.Error) assert.Equal(t, res.ExitCode, 0) res = c.RunCmd(t, "diff", "-r", helmDir, "./fixtures/bridge/expected-helm") assert.NilError(t, res.Error, res.Combined()) }) t.Run("list transformers images", func(t *testing.T) { res := c.RunDockerComposeCmd(t, "--project-name", projectName, "bridge", "transformations", "ls") assert.Assert(t, strings.Contains(res.Stdout(), "docker/compose-bridge-helm"), res.Combined()) assert.Assert(t, strings.Contains(res.Stdout(), "docker/compose-bridge-kubernetes"), res.Combined()) }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/e2e/up_test.go
pkg/e2e/up_test.go
//go:build !windows /* Copyright 2022 Docker Compose CLI 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 e2e import ( "context" "errors" "fmt" "os/exec" "strings" "syscall" "testing" "time" "github.com/stretchr/testify/require" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" "github.com/docker/compose/v5/pkg/utils" ) func TestUpServiceUnhealthy(t *testing.T) { c := NewParallelCLI(t) const projectName = "e2e-start-fail" res := c.RunDockerComposeCmdNoCheck(t, "-f", "fixtures/start-fail/compose.yaml", "--project-name", projectName, "up", "-d") res.Assert(t, icmd.Expected{ExitCode: 1, Err: `container e2e-start-fail-fail-1 is unhealthy`}) c.RunDockerComposeCmd(t, "--project-name", projectName, "down") } func TestUpDependenciesNotStopped(t *testing.T) { c := NewParallelCLI(t, WithEnv( "COMPOSE_PROJECT_NAME=up-deps-stop", )) reset := func() { c.RunDockerComposeCmdNoCheck(t, "down", "-t=0", "--remove-orphans", "-v") } reset() t.Cleanup(reset) t.Log("Launching orphan container (background)") c.RunDockerComposeCmd(t, "-f=./fixtures/ups-deps-stop/orphan.yaml", "up", "--wait", "--detach", "orphan", ) RequireServiceState(t, c, "orphan", "running") t.Log("Launching app container with implicit dependency") upOut := &utils.SafeBuffer{} testCmd := c.NewDockerComposeCmd(t, "-f=./fixtures/ups-deps-stop/compose.yaml", "up", "--menu=false", "app", ) ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) t.Cleanup(cancel) cmd, err := StartWithNewGroupID(ctx, testCmd, upOut, nil) assert.NilError(t, err, "Failed to run compose up") t.Log("Waiting for containers to be in running state") upOut.RequireEventuallyContains(t, "hello app") RequireServiceState(t, c, "app", "running") RequireServiceState(t, c, "dependency", "running") t.Log("Simulating Ctrl-C") require.NoError(t, syscall.Kill(-cmd.Process.Pid, syscall.SIGINT), "Failed to send SIGINT to compose up process") t.Log("Waiting for `compose up` to exit") err = cmd.Wait() if err != nil { var exitErr *exec.ExitError errors.As(err, &exitErr) if exitErr.ExitCode() == -1 { t.Fatalf("`compose up` was killed: %v", err) } require.Equal(t, 130, exitErr.ExitCode()) } RequireServiceState(t, c, "app", "exited") // dependency should still be running RequireServiceState(t, c, "dependency", "running") RequireServiceState(t, c, "orphan", "running") } func TestUpWithBuildDependencies(t *testing.T) { c := NewParallelCLI(t) t.Run("up with service using image build by an another service", func(t *testing.T) { // ensure local test run does not reuse previously build image c.RunDockerOrExitError(t, "rmi", "built-image-dependency") res := c.RunDockerComposeCmd(t, "--project-directory", "fixtures/dependencies", "-f", "fixtures/dependencies/service-image-depends-on.yaml", "up", "-d") t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-directory", "fixtures/dependencies", "-f", "fixtures/dependencies/service-image-depends-on.yaml", "down", "--rmi", "all") }) res.Assert(t, icmd.Success) }) } func TestUpWithDependencyExit(t *testing.T) { c := NewParallelCLI(t) t.Run("up with dependency to exit before being healthy", func(t *testing.T) { res := c.RunDockerComposeCmdNoCheck(t, "--project-directory", "fixtures/dependencies", "-f", "fixtures/dependencies/dependency-exit.yaml", "up", "-d") t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", "dependencies", "down") }) res.Assert(t, icmd.Expected{ExitCode: 1, Err: "dependency failed to start: container dependencies-db-1 exited (1)"}) }) } func TestScaleDoesntRecreate(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-scale" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) c.RunDockerComposeCmd(t, "-f", "fixtures/simple-composefile/compose.yaml", "--project-name", projectName, "up", "-d") res := c.RunDockerComposeCmd(t, "-f", "fixtures/simple-composefile/compose.yaml", "--project-name", projectName, "up", "--scale", "simple=2", "-d") assert.Check(t, !strings.Contains(res.Combined(), "Recreated")) } func TestUpWithDependencyNotRequired(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-dependency-not-required" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down") }) res := c.RunDockerComposeCmd(t, "-f", "./fixtures/dependencies/deps-not-required.yaml", "--project-name", projectName, "--profile", "not-required", "up", "-d") assert.Assert(t, strings.Contains(res.Combined(), "foo"), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), " optional dependency \"bar\" failed to start"), res.Combined()) } func TestUpWithAllResources(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-all-resources" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "-v") }) res := c.RunDockerComposeCmd(t, "-f", "./fixtures/resources/compose.yaml", "--all-resources", "--project-name", projectName, "up") assert.Assert(t, strings.Contains(res.Combined(), fmt.Sprintf(`Volume %s_my_vol Created`, projectName)), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), fmt.Sprintf(`Network %s_my_net Created`, projectName)), res.Combined()) } func TestUpProfile(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-up-profile" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "--profile", "test", "down", "-v") }) res := c.RunDockerComposeCmd(t, "-f", "./fixtures/profiles/docker-compose.yaml", "--project-name", projectName, "up", "foo") assert.Assert(t, strings.Contains(res.Combined(), `Container db_c Created`), res.Combined()) assert.Assert(t, strings.Contains(res.Combined(), `Container foo_c Created`), res.Combined()) assert.Assert(t, !strings.Contains(res.Combined(), `Container bar_c Created`), res.Combined()) } func TestUpImageID(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-up-image-id" digest := strings.TrimSpace(c.RunDockerCmd(t, "image", "inspect", "alpine", "-f", "{{ .ID }}").Stdout()) _, id, _ := strings.Cut(digest, ":") t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "-v") }) c = NewCLI(t, WithEnv(fmt.Sprintf("ID=%s", id))) c.RunDockerComposeCmd(t, "-f", "./fixtures/simple-composefile/id.yaml", "--project-name", projectName, "up") } func TestUpStopWithLogsMixed(t *testing.T) { c := NewCLI(t) const projectName = "compose-e2e-stop-logs" t.Cleanup(func() { c.RunDockerComposeCmd(t, "--project-name", projectName, "down", "-v") }) res := c.RunDockerComposeCmd(t, "-f", "./fixtures/stop/compose.yaml", "--project-name", projectName, "up", "--abort-on-container-exit") // assert we still get service2 logs after service 1 Stopped event res.Assert(t, icmd.Expected{ Err: "Container compose-e2e-stop-logs-service1-1 Stopped", }) // assert we get stop hook logs res.Assert(t, icmd.Expected{Out: "service2-1 -> | stop hook running...\nservice2-1 | 64 bytes"}) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/dryrun/dryrunclient.go
pkg/dryrun/dryrunclient.go
/* Copyright 2020 Docker Compose CLI 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 dryrun import ( "bytes" "context" "crypto/rand" "encoding/json" "errors" "fmt" "io" "net" "net/http" "runtime" "strings" "sync" "github.com/docker/buildx/builder" "github.com/docker/buildx/util/imagetools" "github.com/docker/cli/cli/command" moby "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/build" "github.com/docker/docker/api/types/checkpoint" containerType "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/events" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/system" "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" "github.com/docker/docker/pkg/jsonmessage" specs "github.com/opencontainers/image-spec/specs-go/v1" ) var _ client.APIClient = &DryRunClient{} // DryRunClient implements APIClient by delegating to implementation functions. This allows lazy init and per-method overrides type DryRunClient struct { apiClient client.APIClient containers []containerType.Summary execs sync.Map resolver *imagetools.Resolver } type execDetails struct { container string command []string } // NewDryRunClient produces a DryRunClient func NewDryRunClient(apiClient client.APIClient, cli command.Cli) (*DryRunClient, error) { b, err := builder.New(cli, builder.WithSkippedValidation()) if err != nil { return nil, err } configFile, err := b.ImageOpt() if err != nil { return nil, err } return &DryRunClient{ apiClient: apiClient, containers: []containerType.Summary{}, execs: sync.Map{}, resolver: imagetools.New(configFile), }, nil } func getCallingFunction() string { pc, _, _, _ := runtime.Caller(2) fullName := runtime.FuncForPC(pc).Name() return fullName[strings.LastIndex(fullName, ".")+1:] } // All methods and functions which need to be overridden for dry run. func (d *DryRunClient) ContainerAttach(ctx context.Context, container string, options containerType.AttachOptions) (moby.HijackedResponse, error) { return moby.HijackedResponse{}, errors.New("interactive run is not supported in dry-run mode") } func (d *DryRunClient) ContainerCreate(ctx context.Context, config *containerType.Config, hostConfig *containerType.HostConfig, networkingConfig *network.NetworkingConfig, platform *specs.Platform, containerName string, ) (containerType.CreateResponse, error) { d.containers = append(d.containers, containerType.Summary{ ID: containerName, Names: []string{containerName}, Labels: config.Labels, HostConfig: struct { NetworkMode string `json:",omitempty"` Annotations map[string]string `json:",omitempty"` }{}, }) return containerType.CreateResponse{ID: containerName}, nil } func (d *DryRunClient) ContainerInspect(ctx context.Context, container string) (containerType.InspectResponse, error) { containerJSON, err := d.apiClient.ContainerInspect(ctx, container) if err != nil { id := "dryRunId" for _, c := range d.containers { if c.ID == container { id = container } } return containerType.InspectResponse{ ContainerJSONBase: &containerType.ContainerJSONBase{ ID: id, Name: container, State: &containerType.State{ Status: containerType.StateRunning, // needed for --wait option Health: &containerType.Health{ Status: containerType.Healthy, // needed for healthcheck control }, }, }, Mounts: nil, Config: &containerType.Config{}, NetworkSettings: &containerType.NetworkSettings{}, }, nil } return containerJSON, err } func (d *DryRunClient) ContainerKill(ctx context.Context, container, signal string) error { return nil } func (d *DryRunClient) ContainerList(ctx context.Context, options containerType.ListOptions) ([]containerType.Summary, error) { caller := getCallingFunction() switch caller { case "start": return d.containers, nil case "getContainers": if len(d.containers) == 0 { var err error d.containers, err = d.apiClient.ContainerList(ctx, options) return d.containers, err } } return d.apiClient.ContainerList(ctx, options) } func (d *DryRunClient) ContainerPause(ctx context.Context, container string) error { return nil } func (d *DryRunClient) ContainerRemove(ctx context.Context, container string, options containerType.RemoveOptions) error { return nil } func (d *DryRunClient) ContainerRename(ctx context.Context, container, newContainerName string) error { return nil } func (d *DryRunClient) ContainerRestart(ctx context.Context, container string, options containerType.StopOptions) error { return nil } func (d *DryRunClient) ContainerStart(ctx context.Context, container string, options containerType.StartOptions) error { return nil } func (d *DryRunClient) ContainerStop(ctx context.Context, container string, options containerType.StopOptions) error { return nil } func (d *DryRunClient) ContainerUnpause(ctx context.Context, container string) error { return nil } func (d *DryRunClient) CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, containerType.PathStat, error) { rc := io.NopCloser(strings.NewReader("")) if _, err := d.ContainerStatPath(ctx, container, srcPath); err != nil { return rc, containerType.PathStat{}, fmt.Errorf("could not find the file %s in container %s", srcPath, container) } return rc, containerType.PathStat{}, nil } func (d *DryRunClient) CopyToContainer(ctx context.Context, container, path string, content io.Reader, options containerType.CopyToContainerOptions) error { return nil } func (d *DryRunClient) ImageBuild(ctx context.Context, reader io.Reader, options build.ImageBuildOptions) (build.ImageBuildResponse, error) { rc := io.NopCloser(bytes.NewReader(nil)) return build.ImageBuildResponse{ Body: rc, }, nil } func (d *DryRunClient) ImageInspect(ctx context.Context, imageName string, options ...client.ImageInspectOption) (image.InspectResponse, error) { caller := getCallingFunction() switch caller { case "pullServiceImage", "buildContainerVolumes": return image.InspectResponse{ID: "dryRunId"}, nil default: return d.apiClient.ImageInspect(ctx, imageName, options...) } } // Deprecated: Use [DryRunClient.ImageInspect] instead; raw response can be obtained by [client.ImageInspectWithRawResponse] option. func (d *DryRunClient) ImageInspectWithRaw(ctx context.Context, imageName string) (image.InspectResponse, []byte, error) { var buf bytes.Buffer resp, err := d.ImageInspect(ctx, imageName, client.ImageInspectWithRawResponse(&buf)) if err != nil { return image.InspectResponse{}, nil, err } return resp, buf.Bytes(), err } func (d *DryRunClient) ImagePull(ctx context.Context, ref string, options image.PullOptions) (io.ReadCloser, error) { if _, _, err := d.resolver.Resolve(ctx, ref); err != nil { return nil, err } rc := io.NopCloser(strings.NewReader("")) return rc, nil } func (d *DryRunClient) ImagePush(ctx context.Context, ref string, options image.PushOptions) (io.ReadCloser, error) { if _, _, err := d.resolver.Resolve(ctx, ref); err != nil { return nil, err } jsonMessage, err := json.Marshal(&jsonmessage.JSONMessage{ Status: "Pushed", Progress: &jsonmessage.JSONProgress{ Current: 100, Total: 100, Start: 0, HideCounts: false, Units: "Mb", }, ID: ref, }) if err != nil { return nil, err } rc := io.NopCloser(bytes.NewReader(jsonMessage)) return rc, nil } func (d *DryRunClient) ImageRemove(ctx context.Context, imageName string, options image.RemoveOptions) ([]image.DeleteResponse, error) { return nil, nil } func (d *DryRunClient) NetworkConnect(ctx context.Context, networkName, container string, config *network.EndpointSettings) error { return nil } func (d *DryRunClient) NetworkCreate(ctx context.Context, name string, options network.CreateOptions) (network.CreateResponse, error) { return network.CreateResponse{ ID: name, Warning: "", }, nil } func (d *DryRunClient) NetworkDisconnect(ctx context.Context, networkName, container string, force bool) error { return nil } func (d *DryRunClient) NetworkRemove(ctx context.Context, networkName string) error { return nil } func (d *DryRunClient) VolumeCreate(ctx context.Context, options volume.CreateOptions) (volume.Volume, error) { return volume.Volume{ ClusterVolume: nil, Driver: options.Driver, Labels: options.Labels, Name: options.Name, Options: options.DriverOpts, }, nil } func (d *DryRunClient) VolumeRemove(ctx context.Context, volumeID string, force bool) error { return nil } func (d *DryRunClient) ContainerExecCreate(ctx context.Context, container string, config containerType.ExecOptions) (containerType.ExecCreateResponse, error) { b := make([]byte, 32) _, _ = rand.Read(b) id := fmt.Sprintf("%x", b) d.execs.Store(id, execDetails{ container: container, command: config.Cmd, }) return containerType.ExecCreateResponse{ ID: id, }, nil } func (d *DryRunClient) ContainerExecStart(ctx context.Context, execID string, config containerType.ExecStartOptions) error { _, ok := d.execs.LoadAndDelete(execID) if !ok { return fmt.Errorf("invalid exec ID %q", execID) } return nil } // Functions delegated to original APIClient (not used by Compose or not modifying the Compose stack) func (d *DryRunClient) ConfigList(ctx context.Context, options swarm.ConfigListOptions) ([]swarm.Config, error) { return d.apiClient.ConfigList(ctx, options) } func (d *DryRunClient) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (swarm.ConfigCreateResponse, error) { return d.apiClient.ConfigCreate(ctx, config) } func (d *DryRunClient) ConfigRemove(ctx context.Context, id string) error { return d.apiClient.ConfigRemove(ctx, id) } func (d *DryRunClient) ConfigInspectWithRaw(ctx context.Context, name string) (swarm.Config, []byte, error) { return d.apiClient.ConfigInspectWithRaw(ctx, name) } func (d *DryRunClient) ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error { return d.apiClient.ConfigUpdate(ctx, id, version, config) } func (d *DryRunClient) ContainerCommit(ctx context.Context, container string, options containerType.CommitOptions) (containerType.CommitResponse, error) { return d.apiClient.ContainerCommit(ctx, container, options) } func (d *DryRunClient) ContainerDiff(ctx context.Context, container string) ([]containerType.FilesystemChange, error) { return d.apiClient.ContainerDiff(ctx, container) } func (d *DryRunClient) ContainerExecAttach(ctx context.Context, execID string, config containerType.ExecStartOptions) (moby.HijackedResponse, error) { return moby.HijackedResponse{}, errors.New("interactive exec is not supported in dry-run mode") } func (d *DryRunClient) ContainerExecInspect(ctx context.Context, execID string) (containerType.ExecInspect, error) { return d.apiClient.ContainerExecInspect(ctx, execID) } func (d *DryRunClient) ContainerExecResize(ctx context.Context, execID string, options containerType.ResizeOptions) error { return d.apiClient.ContainerExecResize(ctx, execID, options) } func (d *DryRunClient) ContainerExport(ctx context.Context, container string) (io.ReadCloser, error) { return d.apiClient.ContainerExport(ctx, container) } func (d *DryRunClient) ContainerInspectWithRaw(ctx context.Context, container string, getSize bool) (containerType.InspectResponse, []byte, error) { return d.apiClient.ContainerInspectWithRaw(ctx, container, getSize) } func (d *DryRunClient) ContainerLogs(ctx context.Context, container string, options containerType.LogsOptions) (io.ReadCloser, error) { return d.apiClient.ContainerLogs(ctx, container, options) } func (d *DryRunClient) ContainerResize(ctx context.Context, container string, options containerType.ResizeOptions) error { return d.apiClient.ContainerResize(ctx, container, options) } func (d *DryRunClient) ContainerStatPath(ctx context.Context, container, path string) (containerType.PathStat, error) { return d.apiClient.ContainerStatPath(ctx, container, path) } func (d *DryRunClient) ContainerStats(ctx context.Context, container string, stream bool) (containerType.StatsResponseReader, error) { return d.apiClient.ContainerStats(ctx, container, stream) } func (d *DryRunClient) ContainerStatsOneShot(ctx context.Context, container string) (containerType.StatsResponseReader, error) { return d.apiClient.ContainerStatsOneShot(ctx, container) } func (d *DryRunClient) ContainerTop(ctx context.Context, container string, arguments []string) (containerType.TopResponse, error) { return d.apiClient.ContainerTop(ctx, container, arguments) } func (d *DryRunClient) ContainerUpdate(ctx context.Context, container string, updateConfig containerType.UpdateConfig) (containerType.UpdateResponse, error) { return d.apiClient.ContainerUpdate(ctx, container, updateConfig) } func (d *DryRunClient) ContainerWait(ctx context.Context, container string, condition containerType.WaitCondition) (<-chan containerType.WaitResponse, <-chan error) { return d.apiClient.ContainerWait(ctx, container, condition) } func (d *DryRunClient) ContainersPrune(ctx context.Context, pruneFilters filters.Args) (containerType.PruneReport, error) { return d.apiClient.ContainersPrune(ctx, pruneFilters) } func (d *DryRunClient) DistributionInspect(ctx context.Context, imageName, encodedRegistryAuth string) (registry.DistributionInspect, error) { return d.apiClient.DistributionInspect(ctx, imageName, encodedRegistryAuth) } func (d *DryRunClient) BuildCachePrune(ctx context.Context, opts build.CachePruneOptions) (*build.CachePruneReport, error) { return d.apiClient.BuildCachePrune(ctx, opts) } func (d *DryRunClient) BuildCancel(ctx context.Context, id string) error { return d.apiClient.BuildCancel(ctx, id) } func (d *DryRunClient) ImageCreate(ctx context.Context, parentReference string, options image.CreateOptions) (io.ReadCloser, error) { return d.apiClient.ImageCreate(ctx, parentReference, options) } func (d *DryRunClient) ImageHistory(ctx context.Context, imageName string, options ...client.ImageHistoryOption) ([]image.HistoryResponseItem, error) { return d.apiClient.ImageHistory(ctx, imageName, options...) } func (d *DryRunClient) ImageImport(ctx context.Context, source image.ImportSource, ref string, options image.ImportOptions) (io.ReadCloser, error) { return d.apiClient.ImageImport(ctx, source, ref, options) } func (d *DryRunClient) ImageList(ctx context.Context, options image.ListOptions) ([]image.Summary, error) { return d.apiClient.ImageList(ctx, options) } func (d *DryRunClient) ImageLoad(ctx context.Context, input io.Reader, options ...client.ImageLoadOption) (image.LoadResponse, error) { return d.apiClient.ImageLoad(ctx, input, options...) } func (d *DryRunClient) ImageSearch(ctx context.Context, term string, options registry.SearchOptions) ([]registry.SearchResult, error) { return d.apiClient.ImageSearch(ctx, term, options) } func (d *DryRunClient) ImageSave(ctx context.Context, images []string, options ...client.ImageSaveOption) (io.ReadCloser, error) { return d.apiClient.ImageSave(ctx, images, options...) } func (d *DryRunClient) ImageTag(ctx context.Context, imageName, ref string) error { return d.apiClient.ImageTag(ctx, imageName, ref) } func (d *DryRunClient) ImagesPrune(ctx context.Context, pruneFilter filters.Args) (image.PruneReport, error) { return d.apiClient.ImagesPrune(ctx, pruneFilter) } func (d *DryRunClient) NodeInspectWithRaw(ctx context.Context, nodeID string) (swarm.Node, []byte, error) { return d.apiClient.NodeInspectWithRaw(ctx, nodeID) } func (d *DryRunClient) NodeList(ctx context.Context, options swarm.NodeListOptions) ([]swarm.Node, error) { return d.apiClient.NodeList(ctx, options) } func (d *DryRunClient) NodeRemove(ctx context.Context, nodeID string, options swarm.NodeRemoveOptions) error { return d.apiClient.NodeRemove(ctx, nodeID, options) } func (d *DryRunClient) NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error { return d.apiClient.NodeUpdate(ctx, nodeID, version, node) } func (d *DryRunClient) NetworkInspect(ctx context.Context, networkName string, options network.InspectOptions) (network.Inspect, error) { return d.apiClient.NetworkInspect(ctx, networkName, options) } func (d *DryRunClient) NetworkInspectWithRaw(ctx context.Context, networkName string, options network.InspectOptions) (network.Inspect, []byte, error) { return d.apiClient.NetworkInspectWithRaw(ctx, networkName, options) } func (d *DryRunClient) NetworkList(ctx context.Context, options network.ListOptions) ([]network.Inspect, error) { return d.apiClient.NetworkList(ctx, options) } func (d *DryRunClient) NetworksPrune(ctx context.Context, pruneFilter filters.Args) (network.PruneReport, error) { return d.apiClient.NetworksPrune(ctx, pruneFilter) } func (d *DryRunClient) PluginList(ctx context.Context, filter filters.Args) (moby.PluginsListResponse, error) { return d.apiClient.PluginList(ctx, filter) } func (d *DryRunClient) PluginRemove(ctx context.Context, name string, options moby.PluginRemoveOptions) error { return d.apiClient.PluginRemove(ctx, name, options) } func (d *DryRunClient) PluginEnable(ctx context.Context, name string, options moby.PluginEnableOptions) error { return d.apiClient.PluginEnable(ctx, name, options) } func (d *DryRunClient) PluginDisable(ctx context.Context, name string, options moby.PluginDisableOptions) error { return d.apiClient.PluginDisable(ctx, name, options) } func (d *DryRunClient) PluginInstall(ctx context.Context, name string, options moby.PluginInstallOptions) (io.ReadCloser, error) { return d.apiClient.PluginInstall(ctx, name, options) } func (d *DryRunClient) PluginUpgrade(ctx context.Context, name string, options moby.PluginInstallOptions) (io.ReadCloser, error) { return d.apiClient.PluginUpgrade(ctx, name, options) } func (d *DryRunClient) PluginPush(ctx context.Context, name string, registryAuth string) (io.ReadCloser, error) { return d.apiClient.PluginPush(ctx, name, registryAuth) } func (d *DryRunClient) PluginSet(ctx context.Context, name string, args []string) error { return d.apiClient.PluginSet(ctx, name, args) } func (d *DryRunClient) PluginInspectWithRaw(ctx context.Context, name string) (*moby.Plugin, []byte, error) { return d.apiClient.PluginInspectWithRaw(ctx, name) } func (d *DryRunClient) PluginCreate(ctx context.Context, createContext io.Reader, options moby.PluginCreateOptions) error { return d.apiClient.PluginCreate(ctx, createContext, options) } func (d *DryRunClient) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options swarm.ServiceCreateOptions) (swarm.ServiceCreateResponse, error) { return d.apiClient.ServiceCreate(ctx, service, options) } func (d *DryRunClient) ServiceInspectWithRaw(ctx context.Context, serviceID string, options swarm.ServiceInspectOptions) (swarm.Service, []byte, error) { return d.apiClient.ServiceInspectWithRaw(ctx, serviceID, options) } func (d *DryRunClient) ServiceList(ctx context.Context, options swarm.ServiceListOptions) ([]swarm.Service, error) { return d.apiClient.ServiceList(ctx, options) } func (d *DryRunClient) ServiceRemove(ctx context.Context, serviceID string) error { return d.apiClient.ServiceRemove(ctx, serviceID) } func (d *DryRunClient) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options swarm.ServiceUpdateOptions) (swarm.ServiceUpdateResponse, error) { return d.apiClient.ServiceUpdate(ctx, serviceID, version, service, options) } func (d *DryRunClient) ServiceLogs(ctx context.Context, serviceID string, options containerType.LogsOptions) (io.ReadCloser, error) { return d.apiClient.ServiceLogs(ctx, serviceID, options) } func (d *DryRunClient) TaskLogs(ctx context.Context, taskID string, options containerType.LogsOptions) (io.ReadCloser, error) { return d.apiClient.TaskLogs(ctx, taskID, options) } func (d *DryRunClient) TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) { return d.apiClient.TaskInspectWithRaw(ctx, taskID) } func (d *DryRunClient) TaskList(ctx context.Context, options swarm.TaskListOptions) ([]swarm.Task, error) { return d.apiClient.TaskList(ctx, options) } func (d *DryRunClient) SwarmInit(ctx context.Context, req swarm.InitRequest) (string, error) { return d.apiClient.SwarmInit(ctx, req) } func (d *DryRunClient) SwarmJoin(ctx context.Context, req swarm.JoinRequest) error { return d.apiClient.SwarmJoin(ctx, req) } func (d *DryRunClient) SwarmGetUnlockKey(ctx context.Context) (swarm.UnlockKeyResponse, error) { return d.apiClient.SwarmGetUnlockKey(ctx) } func (d *DryRunClient) SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error { return d.apiClient.SwarmUnlock(ctx, req) } func (d *DryRunClient) SwarmLeave(ctx context.Context, force bool) error { return d.apiClient.SwarmLeave(ctx, force) } func (d *DryRunClient) SwarmInspect(ctx context.Context) (swarm.Swarm, error) { return d.apiClient.SwarmInspect(ctx) } func (d *DryRunClient) SwarmUpdate(ctx context.Context, version swarm.Version, swarmSpec swarm.Spec, flags swarm.UpdateFlags) error { return d.apiClient.SwarmUpdate(ctx, version, swarmSpec, flags) } func (d *DryRunClient) SecretList(ctx context.Context, options swarm.SecretListOptions) ([]swarm.Secret, error) { return d.apiClient.SecretList(ctx, options) } func (d *DryRunClient) SecretCreate(ctx context.Context, secret swarm.SecretSpec) (swarm.SecretCreateResponse, error) { return d.apiClient.SecretCreate(ctx, secret) } func (d *DryRunClient) SecretRemove(ctx context.Context, id string) error { return d.apiClient.SecretRemove(ctx, id) } func (d *DryRunClient) SecretInspectWithRaw(ctx context.Context, name string) (swarm.Secret, []byte, error) { return d.apiClient.SecretInspectWithRaw(ctx, name) } func (d *DryRunClient) SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error { return d.apiClient.SecretUpdate(ctx, id, version, secret) } func (d *DryRunClient) Events(ctx context.Context, options events.ListOptions) (<-chan events.Message, <-chan error) { return d.apiClient.Events(ctx, options) } func (d *DryRunClient) Info(ctx context.Context) (system.Info, error) { return d.apiClient.Info(ctx) } func (d *DryRunClient) RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error) { return d.apiClient.RegistryLogin(ctx, auth) } func (d *DryRunClient) DiskUsage(ctx context.Context, options moby.DiskUsageOptions) (moby.DiskUsage, error) { return d.apiClient.DiskUsage(ctx, options) } func (d *DryRunClient) Ping(ctx context.Context) (moby.Ping, error) { return d.apiClient.Ping(ctx) } func (d *DryRunClient) VolumeInspect(ctx context.Context, volumeID string) (volume.Volume, error) { return d.apiClient.VolumeInspect(ctx, volumeID) } func (d *DryRunClient) VolumeInspectWithRaw(ctx context.Context, volumeID string) (volume.Volume, []byte, error) { return d.apiClient.VolumeInspectWithRaw(ctx, volumeID) } func (d *DryRunClient) VolumeList(ctx context.Context, opts volume.ListOptions) (volume.ListResponse, error) { return d.apiClient.VolumeList(ctx, opts) } func (d *DryRunClient) VolumesPrune(ctx context.Context, pruneFilter filters.Args) (volume.PruneReport, error) { return d.apiClient.VolumesPrune(ctx, pruneFilter) } func (d *DryRunClient) VolumeUpdate(ctx context.Context, volumeID string, version swarm.Version, options volume.UpdateOptions) error { return d.apiClient.VolumeUpdate(ctx, volumeID, version, options) } func (d *DryRunClient) ClientVersion() string { return d.apiClient.ClientVersion() } func (d *DryRunClient) DaemonHost() string { return d.apiClient.DaemonHost() } func (d *DryRunClient) HTTPClient() *http.Client { return d.apiClient.HTTPClient() } func (d *DryRunClient) ServerVersion(ctx context.Context) (moby.Version, error) { return d.apiClient.ServerVersion(ctx) } func (d *DryRunClient) NegotiateAPIVersion(ctx context.Context) { d.apiClient.NegotiateAPIVersion(ctx) } func (d *DryRunClient) NegotiateAPIVersionPing(ping moby.Ping) { d.apiClient.NegotiateAPIVersionPing(ping) } func (d *DryRunClient) DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error) { return d.apiClient.DialHijack(ctx, url, proto, meta) } func (d *DryRunClient) Dialer() func(context.Context) (net.Conn, error) { return d.apiClient.Dialer() } func (d *DryRunClient) Close() error { return d.apiClient.Close() } func (d *DryRunClient) CheckpointCreate(ctx context.Context, container string, options checkpoint.CreateOptions) error { return d.apiClient.CheckpointCreate(ctx, container, options) } func (d *DryRunClient) CheckpointDelete(ctx context.Context, container string, options checkpoint.DeleteOptions) error { return d.apiClient.CheckpointDelete(ctx, container, options) } func (d *DryRunClient) CheckpointList(ctx context.Context, container string, options checkpoint.ListOptions) ([]checkpoint.Summary, error) { return d.apiClient.CheckpointList(ctx, container, options) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/api/errors_test.go
pkg/api/errors_test.go
/* Copyright 2020 Docker Compose CLI 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 api import ( "errors" "fmt" "testing" "gotest.tools/v3/assert" ) func TestIsNotFound(t *testing.T) { err := fmt.Errorf(`object "name": %w`, ErrNotFound) assert.Assert(t, IsNotFoundError(err)) assert.Assert(t, !IsNotFoundError(errors.New("another error"))) } func TestIsAlreadyExists(t *testing.T) { err := fmt.Errorf(`object "name": %w`, ErrAlreadyExists) assert.Assert(t, IsAlreadyExistsError(err)) assert.Assert(t, !IsAlreadyExistsError(errors.New("another error"))) } func TestIsForbidden(t *testing.T) { err := fmt.Errorf(`object "name": %w`, ErrForbidden) assert.Assert(t, IsForbiddenError(err)) assert.Assert(t, !IsForbiddenError(errors.New("another error"))) } func TestIsUnknown(t *testing.T) { err := fmt.Errorf(`object "name": %w`, ErrUnknown) assert.Assert(t, IsUnknownError(err)) assert.Assert(t, !IsUnknownError(errors.New("another error"))) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/api/api.go
pkg/api/api.go
/* Copyright 2020 Docker Compose CLI 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 api import ( "context" "fmt" "io" "slices" "strings" "time" "github.com/compose-spec/compose-go/v2/cli" "github.com/compose-spec/compose-go/v2/types" "github.com/containerd/platforms" "github.com/docker/cli/opts" "github.com/docker/docker/api/types/volume" ) // LoadListener receives events during project loading. // Events include: // - "extends": when a service extends another (metadata: service info) // - "include": when including external compose files (metadata: {"path": StringList}) // // Multiple listeners can be registered, and all will be notified of events. type LoadListener func(event string, metadata map[string]any) // ProjectLoadOptions configures how a Compose project should be loaded type ProjectLoadOptions struct { // ProjectName to use, or empty to infer from directory ProjectName string // ConfigPaths are paths to compose files ConfigPaths []string // WorkingDir is the project directory WorkingDir string // EnvFiles are paths to .env files EnvFiles []string // Profiles to activate Profiles []string // Services to select (empty = all) Services []string // Offline mode disables remote resource loading Offline bool // All includes all resources (not just those used by services) All bool // Compatibility enables v1 compatibility mode Compatibility bool // ProjectOptionsFns are compose-go project options to apply. // Use cli.WithInterpolation(false), cli.WithNormalization(false), etc. // This is optional - pass nil or empty slice to use defaults. ProjectOptionsFns []cli.ProjectOptionsFn // LoadListeners receive events during project loading. // All registered listeners will be notified of events. // This is optional - pass nil or empty slice if not needed. LoadListeners []LoadListener OCI OCIOptions } type OCIOptions struct { InsecureRegistries []string } // Compose is the API interface one can use to programmatically use docker/compose in a third-party software // Use [compose.NewComposeService] to get an actual instance type Compose interface { // Build executes the equivalent to a `compose build` Build(ctx context.Context, project *types.Project, options BuildOptions) error // Push executes the equivalent to a `compose push` Push(ctx context.Context, project *types.Project, options PushOptions) error // Pull executes the equivalent of a `compose pull` Pull(ctx context.Context, project *types.Project, options PullOptions) error // Create executes the equivalent to a `compose create` Create(ctx context.Context, project *types.Project, options CreateOptions) error // Start executes the equivalent to a `compose start` Start(ctx context.Context, projectName string, options StartOptions) error // Restart restarts containers Restart(ctx context.Context, projectName string, options RestartOptions) error // Stop executes the equivalent to a `compose stop` Stop(ctx context.Context, projectName string, options StopOptions) error // Up executes the equivalent to a `compose up` Up(ctx context.Context, project *types.Project, options UpOptions) error // Down executes the equivalent to a `compose down` Down(ctx context.Context, projectName string, options DownOptions) error // Logs executes the equivalent to a `compose logs` Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error // Ps executes the equivalent to a `compose ps` Ps(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error) // List executes the equivalent to a `docker stack ls` List(ctx context.Context, options ListOptions) ([]Stack, error) // Kill executes the equivalent to a `compose kill` Kill(ctx context.Context, projectName string, options KillOptions) error // RunOneOffContainer creates a service oneoff container and starts its dependencies RunOneOffContainer(ctx context.Context, project *types.Project, opts RunOptions) (int, error) // Remove executes the equivalent to a `compose rm` Remove(ctx context.Context, projectName string, options RemoveOptions) error // Exec executes a command in a running service container Exec(ctx context.Context, projectName string, options RunOptions) (int, error) // Attach STDIN,STDOUT,STDERR to a running service container Attach(ctx context.Context, projectName string, options AttachOptions) error // Copy copies a file/folder between a service container and the local filesystem Copy(ctx context.Context, projectName string, options CopyOptions) error // Pause executes the equivalent to a `compose pause` Pause(ctx context.Context, projectName string, options PauseOptions) error // UnPause executes the equivalent to a `compose unpause` UnPause(ctx context.Context, projectName string, options PauseOptions) error // Top executes the equivalent to a `compose top` Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error) // Events executes the equivalent to a `compose events` Events(ctx context.Context, projectName string, options EventsOptions) error // Port executes the equivalent to a `compose port` Port(ctx context.Context, projectName string, service string, port uint16, options PortOptions) (string, int, error) // Publish executes the equivalent to a `compose publish` Publish(ctx context.Context, project *types.Project, repository string, options PublishOptions) error // Images executes the equivalent of a `compose images` Images(ctx context.Context, projectName string, options ImagesOptions) (map[string]ImageSummary, error) // Watch services' development context and sync/notify/rebuild/restart on changes Watch(ctx context.Context, project *types.Project, options WatchOptions) error // Viz generates a graphviz graph of the project services Viz(ctx context.Context, project *types.Project, options VizOptions) (string, error) // Wait blocks until at least one of the services' container exits Wait(ctx context.Context, projectName string, options WaitOptions) (int64, error) // Scale manages numbers of container instances running per service Scale(ctx context.Context, project *types.Project, options ScaleOptions) error // Export a service container's filesystem as a tar archive Export(ctx context.Context, projectName string, options ExportOptions) error // Create a new image from a service container's changes Commit(ctx context.Context, projectName string, options CommitOptions) error // Generate generates a Compose Project from existing containers Generate(ctx context.Context, options GenerateOptions) (*types.Project, error) // Volumes executes the equivalent to a `docker volume ls` Volumes(ctx context.Context, project string, options VolumesOptions) ([]VolumesSummary, error) // LoadProject loads and validates a Compose project from configuration files. LoadProject(ctx context.Context, options ProjectLoadOptions) (*types.Project, error) } type VolumesOptions struct { Services []string } type VolumesSummary = *volume.Volume type ScaleOptions struct { Services []string } type WaitOptions struct { // Services passed in the command line to be waited Services []string // Executes a down when a container exits DownProjectOnContainerExit bool } type VizOptions struct { // IncludeNetworks if true, network names a container is attached to should appear in the graph node IncludeNetworks bool // IncludePorts if true, ports a container exposes should appear in the graph node IncludePorts bool // IncludeImageName if true, name of the image used to create a container should appear in the graph node IncludeImageName bool // Indentation string to be used to indent graphviz code, e.g. "\t", " " Indentation string } // WatchLogger is a reserved name to log watch events const WatchLogger = "#watch" // WatchOptions group options of the Watch API type WatchOptions struct { Build *BuildOptions LogTo LogConsumer Prune bool Services []string } // BuildOptions group options of the Build API type BuildOptions struct { // Pull always attempt to pull a newer version of the image Pull bool // Push pushes service images Push bool // Progress set type of progress output ("auto", "plain", "tty") Progress string // Args set build-time args Args types.MappingWithEquals // NoCache disables cache use NoCache bool // Quiet make the build process not output to the console Quiet bool // Services passed in the command line to be built Services []string // Deps also build selected services dependencies Deps bool // Ssh authentications passed in the command line SSHs []types.SSHKey // Memory limit for the build container Memory int64 // Builder name passed in the command line Builder string // Print don't actually run builder but print equivalent build config Print bool // Check let builder validate build configuration Check bool // Attestations allows to enable attestations generation Attestations bool // Provenance generate a provenance attestation Provenance string // SBOM generate a SBOM attestation SBOM string // Out is the stream to write build progress Out io.Writer } // Apply mutates project according to build options func (o BuildOptions) Apply(project *types.Project) error { platform := project.Environment["DOCKER_DEFAULT_PLATFORM"] for name, service := range project.Services { if service.Provider == nil && service.Image == "" && service.Build == nil { return fmt.Errorf("invalid service %q. Must specify either image or build", name) } if service.Build == nil { continue } if platform != "" { if len(service.Build.Platforms) > 0 && !slices.Contains(service.Build.Platforms, platform) { return fmt.Errorf("service %q build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: %s", name, platform) } service.Platform = platform } if service.Platform != "" { if len(service.Build.Platforms) > 0 && !slices.Contains(service.Build.Platforms, service.Platform) { return fmt.Errorf("service %q build configuration does not support platform: %s", name, service.Platform) } } service.Build.Pull = service.Build.Pull || o.Pull service.Build.NoCache = service.Build.NoCache || o.NoCache project.Services[name] = service } return nil } // CreateOptions group options of the Create API type CreateOptions struct { Build *BuildOptions // Services defines the services user interacts with Services []string // Remove legacy containers for services that are not defined in the project RemoveOrphans bool // Ignore legacy containers for services that are not defined in the project IgnoreOrphans bool // Recreate define the strategy to apply on existing containers Recreate string // RecreateDependencies define the strategy to apply on dependencies services RecreateDependencies string // Inherit reuse anonymous volumes from previous container Inherit bool // Timeout set delay to wait for container to gracefully stop before sending SIGKILL Timeout *time.Duration // QuietPull makes the pulling process quiet QuietPull bool } // StartOptions group options of the Start API type StartOptions struct { // Project is the compose project used to define this app. Might be nil if user ran command just with project name Project *types.Project // Attach to container and forward logs if not nil Attach LogConsumer // AttachTo set the services to attach to AttachTo []string // OnExit defines behavior when a container stops OnExit Cascade // ExitCodeFrom return exit code from specified service ExitCodeFrom string // Wait won't return until containers reached the running|healthy state Wait bool WaitTimeout time.Duration // Services passed in the command line to be started Services []string Watch bool NavigationMenu bool } type Cascade int const ( CascadeIgnore Cascade = iota CascadeStop Cascade = iota CascadeFail Cascade = iota ) // RestartOptions group options of the Restart API type RestartOptions struct { // Project is the compose project used to define this app. Might be nil if user ran command just with project name Project *types.Project // Timeout override container restart timeout Timeout *time.Duration // Services passed in the command line to be restarted Services []string // NoDeps ignores services dependencies NoDeps bool } // StopOptions group options of the Stop API type StopOptions struct { // Project is the compose project used to define this app. Might be nil if user ran command just with project name Project *types.Project // Timeout override container stop timeout Timeout *time.Duration // Services passed in the command line to be stopped Services []string } // UpOptions group options of the Up API type UpOptions struct { Create CreateOptions Start StartOptions } // DownOptions group options of the Down API type DownOptions struct { // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels RemoveOrphans bool // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name Project *types.Project // Timeout override container stop timeout Timeout *time.Duration // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag Images string // Volumes remove volumes, both declared in the `volumes` section and anonymous ones Volumes bool // Services passed in the command line to be stopped Services []string } // ConfigOptions group options of the Config API type ConfigOptions struct { // Format define the output format used to dump converted application model (json|yaml) Format string // Output defines the path to save the application model Output string // Resolve image reference to digests ResolveImageDigests bool } // PushOptions group options of the Push API type PushOptions struct { Quiet bool IgnoreFailures bool ImageMandatory bool } // PullOptions group options of the Pull API type PullOptions struct { Quiet bool IgnoreFailures bool IgnoreBuildable bool } // ImagesOptions group options of the Images API type ImagesOptions struct { Services []string } // KillOptions group options of the Kill API type KillOptions struct { // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels RemoveOrphans bool // Project is the compose project used to define this app. Might be nil if user ran command just with project name Project *types.Project // Services passed in the command line to be killed Services []string // Signal to send to containers Signal string // All can be set to true to try to kill all found containers, independently of their state All bool } // RemoveOptions group options of the Remove API type RemoveOptions struct { // Project is the compose project used to define this app. Might be nil if user ran command just with project name Project *types.Project // Stop option passed in the command line Stop bool // Volumes remove anonymous volumes Volumes bool // Force don't ask to confirm removal Force bool // Services passed in the command line to be removed Services []string } // RunOptions group options of the Run API type RunOptions struct { CreateOptions // Project is the compose project used to define this app. Might be nil if user ran command just with project name Project *types.Project Name string Service string Command []string Entrypoint []string Detach bool AutoRemove bool Tty bool Interactive bool WorkingDir string User string Environment []string CapAdd []string CapDrop []string Labels types.Labels Privileged bool UseNetworkAliases bool NoDeps bool // used by exec Index int } // AttachOptions group options of the Attach API type AttachOptions struct { Project *types.Project Service string Index int DetachKeys string NoStdin bool Proxy bool } // EventsOptions group options of the Events API type EventsOptions struct { Services []string Consumer func(event Event) error Since string Until string } // Event is a container runtime event served by Events API type Event struct { Timestamp time.Time Service string Container string Status string Attributes map[string]string } // PortOptions group options of the Port API type PortOptions struct { Protocol string Index int } // OCIVersion controls manifest generation to ensure compatibility // with different registries. // // Currently, this is not exposed as an option to the user – Compose uses // OCI 1.0 mode automatically for ECR registries based on domain and OCI 1.1 // for all other registries. // // There are likely other popular registries that do not support the OCI 1.1 // format, so it might make sense to expose this as a CLI flag or see if // there's a way to generically probe the registry for support level. type OCIVersion string const ( OCIVersion1_0 OCIVersion = "1.0" OCIVersion1_1 OCIVersion = "1.1" ) // PublishOptions group options of the Publish API type PublishOptions struct { ResolveImageDigests bool Application bool WithEnvironment bool OCIVersion OCIVersion // Use plain HTTP to access registry. Should only be used for testing purpose InsecureRegistry bool } func (e Event) String() string { t := e.Timestamp.Format("2006-01-02 15:04:05.000000") var attr []string for k, v := range e.Attributes { attr = append(attr, fmt.Sprintf("%s=%s", k, v)) } return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", ")) } // ListOptions group options of the ls API type ListOptions struct { All bool } // PsOptions group options of the Ps API type PsOptions struct { Project *types.Project All bool Services []string } // CopyOptions group options of the cp API type CopyOptions struct { Source string Destination string All bool Index int FollowLink bool CopyUIDGID bool } // PortPublisher hold status about published port type PortPublisher struct { URL string TargetPort int PublishedPort int Protocol string } // ContainerSummary hold high-level description of a container type ContainerSummary struct { ID string Name string Names []string Image string Command string Project string Service string Created int64 State string Status string Health string ExitCode int Publishers PortPublishers Labels map[string]string SizeRw int64 `json:",omitempty"` SizeRootFs int64 `json:",omitempty"` Mounts []string Networks []string LocalVolumes int } // PortPublishers is a slice of PortPublisher type PortPublishers []PortPublisher // Len implements sort.Interface func (p PortPublishers) Len() int { return len(p) } // Less implements sort.Interface func (p PortPublishers) Less(i, j int) bool { left := p[i] right := p[j] if left.URL != right.URL { return left.URL < right.URL } if left.TargetPort != right.TargetPort { return left.TargetPort < right.TargetPort } if left.PublishedPort != right.PublishedPort { return left.PublishedPort < right.PublishedPort } return left.Protocol < right.Protocol } // Swap implements sort.Interface func (p PortPublishers) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // ContainerProcSummary holds container processes top data type ContainerProcSummary struct { ID string Name string Processes [][]string Titles []string Service string Replica string } // ImageSummary holds container image description type ImageSummary struct { ID string Repository string Tag string Platform platforms.Platform Size int64 Created *time.Time LastTagTime time.Time } // ServiceStatus hold status about a service type ServiceStatus struct { ID string Name string Replicas int Desired int Ports []string Publishers []PortPublisher } // LogOptions defines optional parameters for the `Log` API type LogOptions struct { Project *types.Project Index int Services []string Tail string Since string Until string Follow bool Timestamps bool } // PauseOptions group options of the Pause API type PauseOptions struct { // Services passed in the command line to be started Services []string // Project is the compose project used to define this app. Might be nil if user ran command just with project name Project *types.Project } // ExportOptions group options of the Export API type ExportOptions struct { Service string Index int Output string } // CommitOptions group options of the Commit API type CommitOptions struct { Service string Reference string Pause bool Comment string Author string Changes opts.ListOpts Index int } type GenerateOptions struct { // ProjectName to set in the Compose file ProjectName string // Containers passed in the command line to be used as reference for service definition Containers []string } const ( // STARTING indicates that stack is being deployed STARTING string = "Starting" // RUNNING indicates that stack is deployed and services are running RUNNING string = "Running" // UPDATING indicates that some stack resources are being recreated UPDATING string = "Updating" // REMOVING indicates that stack is being deleted REMOVING string = "Removing" // UNKNOWN indicates unknown stack state UNKNOWN string = "Unknown" // FAILED indicates that stack deployment failed FAILED string = "Failed" ) const ( // RecreateDiverged to recreate services which configuration diverges from compose model RecreateDiverged = "diverged" // RecreateForce to force service container being recreated RecreateForce = "force" // RecreateNever to never recreate existing service containers RecreateNever = "never" ) // Stack holds the name and state of a compose application/stack type Stack struct { ID string Name string Status string ConfigFiles string Reason string } // LogConsumer is a callback to process log messages from services type LogConsumer interface { Log(containerName, message string) Err(containerName, message string) Status(container, msg string) } // ContainerEventListener is a callback to process ContainerEvent from services type ContainerEventListener func(event ContainerEvent) // ContainerEvent notify an event has been collected on source container implementing Service type ContainerEvent struct { Type int Time int64 Container *ContainerSummary // Source is the name of the container _without the project prefix_. // // This is only suitable for display purposes within Compose, as it's // not guaranteed to be unique across services. Source string ID string Service string Line string // ExitCode is only set on ContainerEventExited events ExitCode int Restarting bool } const ( // ContainerEventLog is a ContainerEvent of type log on stdout. Line is set ContainerEventLog = iota // ContainerEventErr is a ContainerEvent of type log on stderr. Line is set ContainerEventErr // ContainerEventStarted let consumer know a container has been started ContainerEventStarted // ContainerEventRestarted let consumer know a container has been restarted ContainerEventRestarted // ContainerEventStopped is a ContainerEvent of type stopped. ContainerEventStopped // ContainerEventCreated let consumer know a new container has been created ContainerEventCreated // ContainerEventRecreated let consumer know container stopped but his being replaced ContainerEventRecreated // ContainerEventExited is a ContainerEvent of type exit. ExitCode is set ContainerEventExited // UserCancel user canceled compose up, we are stopping containers HookEventLog ) // Separator is used for naming components var Separator = "-" // GetImageNameOrDefault computes the default image name for a service, used to tag built images func GetImageNameOrDefault(service types.ServiceConfig, projectName string) string { imageName := service.Image if imageName == "" { imageName = projectName + Separator + service.Name } return imageName }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/api/errors.go
pkg/api/errors.go
/* Copyright 2020 Docker Compose CLI 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 api import ( "errors" ) const ( // ExitCodeLoginRequired exit code when command cannot execute because it requires cloud login // This will be used by VSCode to detect when creating context if the user needs to login first ExitCodeLoginRequired = 5 ) var ( // ErrNotFound is returned when an object is not found ErrNotFound = errors.New("not found") // ErrAlreadyExists is returned when an object already exists ErrAlreadyExists = errors.New("already exists") // ErrForbidden is returned when an operation is not permitted ErrForbidden = errors.New("forbidden") // ErrUnknown is returned when the error type is unmapped ErrUnknown = errors.New("unknown") // ErrNotImplemented is returned when a backend doesn't implement an action ErrNotImplemented = errors.New("not implemented") // ErrUnsupportedFlag is returned when a backend doesn't support a flag ErrUnsupportedFlag = errors.New("unsupported flag") // ErrCanceled is returned when the command was canceled by user ErrCanceled = errors.New("canceled") // ErrParsingFailed is returned when a string cannot be parsed ErrParsingFailed = errors.New("parsing failed") // ErrNoResources is returned when operation didn't selected any resource ErrNoResources = errors.New("no resources") ) // IsNotFoundError returns true if the unwrapped error is ErrNotFound func IsNotFoundError(err error) bool { return errors.Is(err, ErrNotFound) } // IsAlreadyExistsError returns true if the unwrapped error is ErrAlreadyExists func IsAlreadyExistsError(err error) bool { return errors.Is(err, ErrAlreadyExists) } // IsForbiddenError returns true if the unwrapped error is ErrForbidden func IsForbiddenError(err error) bool { return errors.Is(err, ErrForbidden) } // IsUnknownError returns true if the unwrapped error is ErrUnknown func IsUnknownError(err error) bool { return errors.Is(err, ErrUnknown) } // IsErrUnsupportedFlag returns true if the unwrapped error is ErrUnsupportedFlag func IsErrUnsupportedFlag(err error) bool { return errors.Is(err, ErrUnsupportedFlag) } // IsErrNotImplemented returns true if the unwrapped error is ErrNotImplemented func IsErrNotImplemented(err error) bool { return errors.Is(err, ErrNotImplemented) } // IsErrParsingFailed returns true if the unwrapped error is ErrParsingFailed func IsErrParsingFailed(err error) bool { return errors.Is(err, ErrParsingFailed) } // IsErrCanceled returns true if the unwrapped error is ErrCanceled func IsErrCanceled(err error) bool { return errors.Is(err, ErrCanceled) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/api/api_test.go
pkg/api/api_test.go
/* Copyright 2020 Docker Compose CLI 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 api import ( "testing" "github.com/compose-spec/compose-go/v2/types" "gotest.tools/v3/assert" ) func TestRunOptionsEnvironmentMap(t *testing.T) { opts := RunOptions{ Environment: []string{ "FOO=BAR", "ZOT=", "QIX", }, } env := types.NewMappingWithEquals(opts.Environment) assert.Equal(t, *env["FOO"], "BAR") assert.Equal(t, *env["ZOT"], "") assert.Check(t, env["QIX"] == nil) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/api/labels.go
pkg/api/labels.go
/* Copyright 2020 Docker Compose CLI 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 api import ( "github.com/hashicorp/go-version" "github.com/docker/compose/v5/internal" ) const ( // ProjectLabel allow to track resource related to a compose project ProjectLabel = "com.docker.compose.project" // ServiceLabel allow to track resource related to a compose service ServiceLabel = "com.docker.compose.service" // ConfigHashLabel stores configuration hash for a compose service ConfigHashLabel = "com.docker.compose.config-hash" // ContainerNumberLabel stores the container index of a replicated service ContainerNumberLabel = "com.docker.compose.container-number" // VolumeLabel allow to track resource related to a compose volume VolumeLabel = "com.docker.compose.volume" // NetworkLabel allow to track resource related to a compose network NetworkLabel = "com.docker.compose.network" // WorkingDirLabel stores absolute path to compose project working directory WorkingDirLabel = "com.docker.compose.project.working_dir" // ConfigFilesLabel stores absolute path to compose project configuration files ConfigFilesLabel = "com.docker.compose.project.config_files" // EnvironmentFileLabel stores absolute path to compose project env file set by `--env-file` EnvironmentFileLabel = "com.docker.compose.project.environment_file" // OneoffLabel stores value 'True' for one-off containers created by `compose run` OneoffLabel = "com.docker.compose.oneoff" // SlugLabel stores unique slug used for one-off container identity SlugLabel = "com.docker.compose.slug" // ImageDigestLabel stores digest of the container image used to run service ImageDigestLabel = "com.docker.compose.image" // DependenciesLabel stores service dependencies DependenciesLabel = "com.docker.compose.depends_on" // VersionLabel stores the compose tool version used to build/run application VersionLabel = "com.docker.compose.version" // ImageBuilderLabel stores the builder (classic or BuildKit) used to produce the image. ImageBuilderLabel = "com.docker.compose.image.builder" // ContainerReplaceLabel is set when container is created to replace another container (recreated) ContainerReplaceLabel = "com.docker.compose.replace" ) // ComposeVersion is the compose tool version as declared by label VersionLabel var ComposeVersion string func init() { v, err := version.NewVersion(internal.Version) if err == nil { ComposeVersion = v.Core().String() } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/api/labels_test.go
pkg/api/labels_test.go
/* Copyright 2020 Docker Compose CLI 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 api import ( "testing" "github.com/hashicorp/go-version" "gotest.tools/v3/assert" "github.com/docker/compose/v5/internal" ) func TestComposeVersionInitialization(t *testing.T) { v, err := version.NewVersion(internal.Version) if err != nil { assert.Equal(t, "", ComposeVersion, "ComposeVersion should be empty for a non-semver internal version (e.g. 'devel')") } else { expected := v.Core().String() assert.Equal(t, expected, ComposeVersion, "ComposeVersion should be the core of internal.Version") } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/api/env.go
pkg/api/env.go
/* Copyright 2020 Docker Compose CLI 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 api // ComposeCompatibility try to mimic compose v1 as much as possible const ComposeCompatibility = "COMPOSE_COMPATIBILITY"
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/api/context.go
pkg/api/context.go
/* Copyright 2020 Docker Compose CLI 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 api // ContextInfo provides Docker context information for advanced scenarios type ContextInfo interface { // CurrentContext returns the name of the current Docker context // Returns "default" for simple clients without context support CurrentContext() string // ServerOSType returns the Docker daemon's operating system (linux/windows/darwin) // Used for OS-specific compatibility checks ServerOSType() string // BuildKitEnabled determines whether BuildKit should be used for builds // Checks DOCKER_BUILDKIT env var, config, and daemon capabilities BuildKitEnabled() (bool, error) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/api/event.go
pkg/api/event.go
/* Copyright 2020 Docker Compose CLI 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 api import ( "context" ) // EventStatus indicates the status of an action type EventStatus int const ( // Working means that the current task is working Working EventStatus = iota // Done means that the current task is done Done // Warning means that the current task has warning Warning // Error means that the current task has errored Error ) // ResourceCompose is a special resource ID used when event applies to all resources in the application const ResourceCompose = "Compose" const ( StatusError = "Error" StatusCreating = "Creating" StatusStarting = "Starting" StatusStarted = "Started" StatusWaiting = "Waiting" StatusHealthy = "Healthy" StatusExited = "Exited" StatusRestarting = "Restarting" StatusRestarted = "Restarted" StatusRunning = "Running" StatusCreated = "Created" StatusStopping = "Stopping" StatusStopped = "Stopped" StatusKilling = "Killing" StatusKilled = "Killed" StatusRemoving = "Removing" StatusRemoved = "Removed" StatusBuilding = "Building" StatusBuilt = "Built" StatusPulling = "Pulling" StatusPulled = "Pulled" StatusCommitting = "Committing" StatusCommitted = "Committed" StatusCopying = "Copying" StatusCopied = "Copied" StatusExporting = "Exporting" StatusExported = "Exported" StatusDownloading = "Downloading" StatusDownloadComplete = "Download complete" StatusConfiguring = "Configuring" StatusConfigured = "Configured" ) // Resource represents status change and progress for a compose resource. type Resource struct { ID string ParentID string Text string Details string Status EventStatus Current int64 Percent int Total int64 } func (e *Resource) StatusText() string { switch e.Status { case Working: return "Working" case Warning: return "Warning" case Done: return "Done" default: return "Error" } } // EventProcessor is notified about Compose operations and tasks type EventProcessor interface { // Start is triggered as a Compose operation is starting with context Start(ctx context.Context, operation string) // On notify about (sub)task and progress processing operation On(events ...Resource) // Done is triggered as a Compose operation completed Done(operation string, success bool) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/pkg/compose/start.go
pkg/compose/start.go
/* Copyright 2020 Docker Compose CLI 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 compose import ( "context" "errors" "fmt" "strings" "github.com/compose-spec/compose-go/v2/types" containerType "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" "github.com/docker/compose/v5/pkg/api" ) func (s *composeService) Start(ctx context.Context, projectName string, options api.StartOptions) error { return Run(ctx, func(ctx context.Context) error { return s.start(ctx, strings.ToLower(projectName), options, nil) }, "start", s.events) } func (s *composeService) start(ctx context.Context, projectName string, options api.StartOptions, listener api.ContainerEventListener) error { project := options.Project if project == nil { var containers Containers containers, err := s.getContainers(ctx, projectName, oneOffExclude, true) if err != nil { return err } project, err = s.projectFromName(containers, projectName, options.AttachTo...) if err != nil { return err } } var containers Containers containers, err := s.apiClient().ContainerList(ctx, containerType.ListOptions{ Filters: filters.NewArgs( projectFilter(project.Name), oneOffFilter(false), ), All: true, }) if err != nil { return err } err = InDependencyOrder(ctx, project, func(c context.Context, name string) error { service, err := project.GetService(name) if err != nil { return err } return s.startService(ctx, project, service, containers, listener, options.WaitTimeout) }) if err != nil { return err } if options.Wait { depends := types.DependsOnConfig{} for _, s := range project.Services { depends[s.Name] = types.ServiceDependency{ Condition: getDependencyCondition(s, project), Required: true, } } if options.WaitTimeout > 0 { withTimeout, cancel := context.WithTimeout(ctx, options.WaitTimeout) ctx = withTimeout defer cancel() } err = s.waitDependencies(ctx, project, project.Name, depends, containers, 0) if err != nil { if errors.Is(ctx.Err(), context.DeadlineExceeded) { return fmt.Errorf("application not healthy after %s", options.WaitTimeout) } return err } } return nil } // getDependencyCondition checks if service is depended on by other services // with service_completed_successfully condition, and applies that condition // instead, or --wait will never finish waiting for one-shot containers func getDependencyCondition(service types.ServiceConfig, project *types.Project) string { for _, services := range project.Services { for dependencyService, dependencyConfig := range services.DependsOn { if dependencyService == service.Name && dependencyConfig.Condition == types.ServiceConditionCompletedSuccessfully { return types.ServiceConditionCompletedSuccessfully } } } return ServiceConditionRunningOrHealthy }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false