Skip to content
Snippets Groups Projects
Commit 4d89017b authored by Neil-Jocelyn Schark's avatar Neil-Jocelyn Schark
Browse files

test removal from csbi

parent e0128a14
No related branches found
No related tags found
1 merge request!1262Repair gosdn 1 (includes removing of CSBI, as it is not used anymore)
Pipeline #266829 passed
This commit is part of merge request !1262. Comments created here will be created in the context of that merge request.
Showing
with 0 additions and 1158 deletions
repository-base-path: "./models"
orchestrator-shutown-timeout: "1min"
docker-orchestrator-network: "gosdn-csbi-arista-base-net"
# syntax = docker/dockerfile:1.2
FROM golang:1.17-alpine AS installer
WORKDIR /build
RUN apk add --no-cache git make build-base
RUN apk add --update --no-cache alpine-sdk
COPY go.mod .
COPY go.sum .
RUN go mod download
FROM installer as builder
COPY . .
RUN --mount=type=cache,target=/root/.cache/go-build \
GOOS=linux CGO_ENABLED=0 go build -o executor ./cmd/executor/executor.go
FROM alpine
COPY --from=builder /build/executor .
COPY --from=builder /build/cmd/executor/experiment.yaml .
ENTRYPOINT [ "./executor" ]
CMD [""]
Copyright © 2021 Manuel Kieweg <mail@manuelkieweg.de>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Containerised Southbound Interface
arista-exp-eos-vxlan-config
ietf-yang-types
openconfig-aaa
openconfig-igmp-types
openconfig-qos
openconfig-bfd
openconfig-hercules-interfaces
arista-cli
openconfig-policy-types
openconfig-inet-types
openconfig-hercules-platform
openconfig-procmon
openconfig-platform-transceiver
openconfig-if-ip
openconfig-ospfv2
openconfig-platform-linecard
openconfig-alarm-types
arista-exp-eos-l2protocolforwarding
openconfig-routing-policy
openconfig-platform-types
openconfig-transport-types
openconfig-relay-agent
openconfig-isis-lsdb-types
openconfig-platform-psu
openconfig-isis-types
openconfig-segment-routing
openconfig-openflow
openconfig-interfaces
openconfig-alarms
openconfig-packet-match-types
ietf-netconf
openconfig-system-logging
openconfig-bgp-policy
openconfig-aft-types
openconfig-network-instance
arista-eos-types
openconfig-ospf-types
openconfig-if-ethernet
openconfig-lldp-types
openconfig-bgp
openconfig-rib-bgp
openconfig-mpls-rsvp
openconfig-aaa-types
openconfig-extensions
openconfig-mpls-sr
arista-exp-eos-varp-intf
openconfig-messages
openconfig-mpls-ldp
arista-exp-eos-multicast
arista-exp-eos-varp-net-inst
arista-exp-eos-igmpsnooping
openconfig-license
arista-exp-eos
openconfig-packet-match
arista-exp-eos-qos-acl-config
arista-gnoi-cert
arista-exp-eos-evpn
openconfig-ospf-policy
openconfig-isis
arista-exp-eos-qos
openconfig-aft
openconfig-system
openconfig-mpls-types
ietf-inet-types
arista-exp-eos-vxlan
openconfig-hercules-qos
openconfig-segment-routing-types
openconfig-if-aggregate
openconfig-qos-types
openconfig-vlan-types
openconfig-yang-types
openconfig-network-instance-types
openconfig-lldp
openconfig-vlan
openconfig-pf-srte
openconfig-rib-bgp-types
ietf-interfaces
openconfig-srte-policy
arista-exp-eos-qos-config
openconfig-system-management
openconfig-bgp-types
openconfig-pim
openconfig-lacp
openconfig-local-routing
openconfig-system-terminal
openconfig-if-poe
openconfig-platform-cpu
openconfig-platform-fan
openconfig-platform-port
openconfig-if-types
ietf-netconf-monitoring
arista-exp-eos-mlag
openconfig-pim-types
openconfig-if-tunnel
openconfig-platform
arista-rpc-netconf
vlan-translation
iana-if-type
openconfig-openflow-types
openconfig-mpls
openconfig-network-instance-l3
openconfig-igmp
openconfig-acl
openconfig-policy-forwarding
openconfig-types
\ No newline at end of file
package csbi
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"path/filepath"
"time"
spb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/southbound"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/archive"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
)
// nolint
type ErrorLine struct {
Error string `json:"error"`
ErrorDetail ErrorDetail `json:"errorDetail"`
}
// nolint
type ErrorDetail struct {
Message string `json:"message"`
}
func buildImage(d Deployment, dockerClient *client.Client) (err error) {
labels := prometheus.Labels{"type": spb.Type_TYPE_CONTAINERISED.String()}
start := promStartHook(labels, buildsTotal)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*300)
defer cancel()
p := filepath.Join(d.ID.String(), "/")
tar, err := archive.TarWithOptions(p, &archive.TarOptions{})
if err != nil {
return err
}
opts := types.ImageBuildOptions{
Dockerfile: "Dockerfile",
Tags: []string{d.Name},
Remove: true,
}
res, err := dockerClient.ImageBuild(ctx, tar, opts)
if err != nil {
return err
}
defer func() {
if ferr := res.Body.Close(); ferr != nil {
fErrString := ferr.Error()
err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString)
}
}()
err = printImageBody(res.Body)
if err != nil {
return err
}
promEndHook(labels, start, buildDurationSecondsTotal, buildDurationSeconds)
return nil
}
func printImageBody(rd io.Reader) error {
var lastLine string
scanner := bufio.NewScanner(rd)
for scanner.Scan() {
lastLine = scanner.Text()
fmt.Println(scanner.Text())
}
errLine := &ErrorLine{}
err := json.Unmarshal([]byte(lastLine), errLine)
if errLine.Error != "" {
return errors.New(errLine.Error)
} else if err != nil {
log.Error(err)
}
return scanner.Err()
}
build-docker:
before_script:
- echo "override global before script"
stage: build
allow_failure: false
needs: []
rules:
- if: $CI_COMMIT_BRANCH == "develop" && $CI_NIGHTLY == null
variables:
TAG: $CI_REGISTRY_IMAGE:develop
BUILDARGS: -race
- if: $CI_NIGHTLY == "develop"
variables:
TAG: $CI_REGISTRY_IMAGE:nightly-develop
BUILDARGS: -race
- if: $CI_NIGHTLY == "mainline"
variables:
TAG: $CI_REGISTRY_IMAGE:nightly
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
variables:
TAG: $CI_REGISTRY_IMAGE:merge-request
BUILDARGS: -race
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_NIGHTLY == null
variables:
TAG: $CI_REGISTRY_IMAGE:latest
- if: '$CI_COMMIT_BRANCH'
variables:
TAG: $CI_REGISTRY_IMAGE:branch
script:
- echo "$CI_REGISTRY_PASSWORD" | docker login -u $CI_REGISTRY_USER --password-stdin $CI_REGISTRY
- DOCKER_BUILDKIT=1 docker build -t $DOCKER_IMAGE_SHA .
- docker push $DOCKER_IMAGE_SHA
- docker tag $DOCKER_IMAGE_SHA $TAG
- docker push $TAG
- docker build --target installer -t ${CI_REGISTRY_IMAGE}:testing_${CI_PIPELINE_ID} .
- docker push ${CI_REGISTRY_IMAGE}:testing_${CI_PIPELINE_ID}
code-quality:
image: golangci/golangci-lint:v1.56.0-alpine
stage: test
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_BRANCH == "develop"
script:
# writes golangci-lint output to gl-code-quality-report.json
- golangci-lint run --config build/ci/.golangci-config/.golangci.yml --out-format code-climate | tee gl-code-quality-report.json
artifacts:
reports:
codequality: gl-code-quality-report.json
paths:
- gl-code-quality-report.json
run:
timeout: 10m
issues-exit-code: 1
# directories to be ignored by linters
skip-dirs:
- forks
- test
skip-dirs-default: true
skip-files:
- http.go
# output settings -> code-climate for GitLab
output:
format: code-climate
print-issued-lines: true
print-linter-name: true
uniq-by-line: true
path-prefix: ""
# custom settings for linters
linters-settings:
gocyclo:
min-complexity: 15
golint:
min-confidence: 0.8
# enable the specific needed linters
linters:
disable-all: true
enable:
- gofmt
- goimports
- revive
- gocyclo
- govet
issues:
exclude-use-default: false
max-issues-per-linter: 0
max-same-issues: 0
sast:
variables:
SAST_ANALYZER_IMAGE_TAG: '2'
SAST_EXCLUDED_PATHS: spec, test, tests, tmp
SEARCH_MAX_DEPTH: '4'
include:
- template: Security/SAST.gitlab-ci.yml
- template: Dependency-Scanning.gitlab-ci.yml
- template: Security/License-Scanning.gitlab-ci.yml
.test: &test
image: ${CI_REGISTRY_IMAGE}:testing_${CI_PIPELINE_ID}
stage: test
variables:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH
- if: $CI_NIGHTLY
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
allow_failure: true
unit-test:
script:
- go test $(go list ./...) -coverprofile=coverage.out
after_script:
- go tool cover -func=coverage.out
<<: *test
\ No newline at end of file
package csbi
import (
"io"
"testing"
"github.com/docker/docker/client"
)
func Test_buildImage(t *testing.T) {
type args struct {
d Deployment
dockerClient *client.Client
}
tests := []struct {
name string
args args
wantErr bool
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := buildImage(tt.args.d, tt.args.dockerClient); (err != nil) != tt.wantErr {
t.Errorf("buildImage() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func Test_print(t *testing.T) {
type args struct {
rd io.Reader
}
tests := []struct {
name string
args args
wantErr bool
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := printImageBody(tt.args.rd); (err != nil) != tt.wantErr {
t.Errorf("print() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
/*
Copyright © 2021 Manuel Kieweg <mail@manuelkieweg.de>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package main
import "code.fbi.h-da.de/danet/gosdn/csbi/cmd"
func main() {
cmd.Execute()
}
package main
import (
"context"
"fmt"
"net"
spb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/southbound"
"code.fbi.h-da.de/danet/gosdn/csbi"
"code.fbi.h-da.de/danet/gosdn/csbi/config"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"google.golang.org/grpc/peer"
)
func init() {
log.SetLevel(log.DebugLevel)
viper.SetConfigName(".csbi")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
log.Fatal(fmt.Errorf("error reading config: %w", err))
}
log.WithFields(viper.AllSettings()).Debug("current viper config")
}
func main() {
repo := csbi.NewRepository(config.RepositoryBasePath())
p := &peer.Peer{
Addr: &net.IPAddr{IP: net.IPv4zero},
}
_, err := csbi.Generate(peer.NewContext(context.Background(), p), nil, repo, spb.Type_TYPE_CONTAINERISED)
if err != nil {
log.Fatal(err)
}
}
package main
import (
"code.fbi.h-da.de/danet/gosdn/csbi"
)
func main() {
csbi.Run(":55056")
}
/*
Copyright © 2021 Manuel Kieweg <mail@manuelkieweg.de>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
// deployCmd represents the deploy command.
var deployCmd = &cobra.Command{
Use: "deploy",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("deploy called")
},
}
func init() {
rootCmd.AddCommand(deployCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// deployCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// deployCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
/*
Copyright © 2021 Manuel Kieweg <mail@manuelkieweg.de>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
// discoverCmd represents the discover command.
var discoverCmd = &cobra.Command{
Use: "discover",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("discover called")
},
}
func init() {
rootCmd.AddCommand(discoverCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// discoverCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// discoverCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
package main
//import (
// "bufio"
// "encoding/json"
// "fmt"
// "net"
// "net/http"
// "os"
// "strings"
// "time"
//
// "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/southbound"
// "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/transport"
// "code.fbi.h-da.de/danet/gosdn/controller/api"
// "code.fbi.h-da.de/danet/gosdn/controller/interfaces/networkdomain"
// "github.com/google/uuid"
// dto "github.com/prometheus/client_model/go"
// "github.com/prometheus/common/expfmt"
// "github.com/prometheus/prom2json"
//
// log "github.com/sirupsen/logrus"
//
// "github.com/spf13/viper"
//)
//
//const plugin = southbound.Type_TYPE_PLUGIN
//const containerised = southbound.Type_TYPE_CONTAINERISED
//
//type experiment struct {
// execMode southbound.Type
// iterations int
//}
//
//type config struct {
// gnmiTarget string `yaml:"gnmi-target"`
// ceosTarget string `yaml:"ceos-target"`
// controller string `yaml:"controller"`
//}
//
//type result struct{}
//
//var sbiID uuid.UUID
//var pndID uuid.UUID
//
//var pnd networkdomain.NetworkDomain
//
//var targets = []string{
// "clab-thesis-gosdn:8080",
// "clab-thesis-orchestrator:9338",
//}
//
//var experiments = []experiment{
// {
// execMode: plugin,
// iterations: 1,
// },
// {
// execMode: containerised,
// iterations: 1,
// },
// {
// execMode: plugin,
// iterations: 10,
// },
// {
// execMode: containerised,
// iterations: 10,
// },
// {
// execMode: plugin,
// iterations: 20,
// },
// {
// execMode: containerised,
// iterations: 20,
// },
// {
// execMode: plugin,
// iterations: 40,
// },
// {
// execMode: containerised,
// iterations: 40,
// },
// {
// execMode: plugin,
// iterations: 60,
// },
// {
// execMode: containerised,
// iterations: 60,
// },
// {
// execMode: plugin,
// iterations: 80,
// },
// {
// execMode: containerised,
// iterations: 80,
// },
//}
//
//func newCollector(targets []string, path string) *metricsCollector {
// f, err := os.Create(path)
// if err != nil {
// log.Fatal(err)
// }
// return &metricsCollector{
// targets: targets,
// f: f,
// ticker: time.NewTicker(1 * time.Second),
// mfChan: make(chan *dto.MetricFamily, 1024),
// stopChan: make(chan bool),
// }
//}
//
//type metricsCollector struct {
// targets []string
// f *os.File
// stopChan chan bool
// ticker *time.Ticker
// mfChan chan *dto.MetricFamily
// results []*prom2json.Family
//}
//
//func (mc *metricsCollector) start() {
// go func() {
// for {
// select {
// case <-mc.ticker.C:
// for _, target := range mc.targets {
// if err := mc.collect(target); err != nil {
// log.Error(err)
// }
// }
// case <-mc.stopChan:
// close(mc.mfChan)
// return
// }
// }
// }()
// go func() {
// for mf := range mc.mfChan {
// mc.results = append(mc.results, prom2json.NewFamily(mf))
// }
// }()
//}
//
//func (mc *metricsCollector) stop() {
// mc.stopChan <- true
// writers := make(map[string]*fileWriter)
// for _, result := range mc.results {
// writer, ok := writers[result.Name]
// if !ok {
// path := fmt.Sprintf("/out/prom-%v-%v.csv", time.Now().UTC().Format(time.RFC3339), result.Name)
// writer = newFileWriter(path)
// writers[result.Name] = writer
// }
// switch result.Type {
// case "GAUGE", "COUNTER":
// if err := writeMetric(writer, result); err != nil {
// log.Error(err)
// }
// case "HISTOGRAM":
// if err := writeHistogram(writer, result); err != nil {
// log.Error(err)
// }
// default:
// }
// }
// for _, v := range writers {
// v.close()
// }
// jsonText, err := json.Marshal(mc.results)
// if err != nil {
// log.Error()
// }
//
// n, err := mc.f.Write(jsonText)
// if err != nil {
// log.Error(err)
// }
// log.WithField("n", n).Info("wrote prom json")
//}
//
//func (mc *metricsCollector) collect(target string) error {
// resp, err := http.Get("http://" + target + "/metrics")
// if err != nil {
// return err
// }
// defer resp.Body.Close()
// var parser expfmt.TextParser
// mfs, err := parser.TextToMetricFamilies(resp.Body)
// if err != nil {
// return err
// }
// for k, v := range mfs {
// if strings.Contains(k, "go_memstats") ||
// strings.Contains(k, "code_generations_total") ||
// strings.Contains(k, "duration_seconds") ||
// strings.Contains(k, "errors") ||
// strings.Contains(k, "grpc_requests_total") {
// mc.mfChan <- v
// }
// }
// return nil
//}
//
//func writeMetric(writer *fileWriter, result *prom2json.Family) error {
// b := strings.Builder{}
// b.WriteString(result.Name)
// b.WriteRune(';')
// b.WriteString(result.Type)
// for _, m := range result.Metrics {
// b.WriteRune(';')
// metric, ok := m.(prom2json.Metric)
// if !ok {
// return fmt.Errorf("invalid type assertion")
// }
// b.WriteString(metric.TimestampMs)
// b.WriteRune(';')
// for k, v := range metric.Labels {
// b.WriteString(k)
// b.WriteRune(';')
// b.WriteString(v)
// b.WriteRune(';')
// }
// b.WriteString(metric.Value)
// }
// b.WriteRune('\n')
// writer.write(b.String())
// return nil
//}
//
//func writeHistogram(writer *fileWriter, result *prom2json.Family) error {
// b := strings.Builder{}
// b.WriteString(result.Name)
// b.WriteRune(';')
// b.WriteString(result.Type)
// for _, m := range result.Metrics {
// b.WriteRune(';')
// hist, ok := m.(prom2json.Histogram)
// if !ok {
// return fmt.Errorf("invalid type assertion")
// }
// b.WriteString(hist.TimestampMs)
// b.WriteRune(';')
// for k, v := range hist.Labels {
// b.WriteString(k)
// b.WriteRune(';')
// b.WriteString(v)
// b.WriteRune(';')
// }
// for k, v := range hist.Buckets {
// b.WriteString(k)
// b.WriteRune(';')
// b.WriteString(v)
// b.WriteRune(';')
// }
// b.WriteString(hist.Count)
// b.WriteRune(';')
// b.WriteString(hist.Count)
// }
// b.WriteRune('\n')
// writer.write(b.String())
// return nil
//}
//
//func newFileWriter(path string) *fileWriter {
// f, err := os.Create(path)
// if err != nil {
// log.Fatal(err)
// }
// return &fileWriter{
// f: f,
// w: bufio.NewWriter(f),
// }
//}
//
//type fileWriter struct {
// f *os.File
// w *bufio.Writer
//}
//
//func (fw *fileWriter) write(out string) {
// _, err := fw.w.WriteString(out)
// if err != nil {
// log.Error(err)
// }
//}
//
//func (fw *fileWriter) close() {
// fw.w.Flush()
// fw.f.Close()
//}
//
//func main() {
// c, err := readConfig()
// if err != nil {
// log.Fatal(err)
// }
//
// log.Info("sleeping 10s")
// time.Sleep(10 * time.Second)
// if err := api.Init(c.controller); err != nil {
// log.Fatal(err)
// }
//
// pndID = uuid.MustParse(viper.GetString("CLI_PND"))
// sbiID = uuid.MustParse(viper.GetString("CLI_SBI"))
//
// pnd, err = api.NewAdapter(pndID.String(), c.controller)
// if err != nil {
// log.Fatal(err)
// }
//
// addr, err := net.ResolveTCPAddr("tcp", c.ceosTarget)
// if err != nil {
// log.Error(err)
// }
// var connected bool
// var conn net.Conn
// for !connected {
// conn, err = net.DialTCP("tcp", nil, addr)
// if err != nil {
// log.Warn("waiting for cEOS. Retry in 10s...")
// time.Sleep(10 * time.Second)
// continue
// }
// connected = true
// }
// if err := conn.Close(); err != nil {
// log.Error()
// }
//
// for i, exp := range experiments {
// log.WithFields(log.Fields{
// "iterations": exp.iterations,
// "exec": exp.execMode,
// }).Infof("starting experiment %v of %v\n", (i + 1), len(experiments))
// err := executeExperiment(exp, c)
// if err != nil {
// log.Error(err)
// }
// log.Info("wait 10s for clean up")
// time.Sleep(10 * time.Second)
// }
//}
//
//func readConfig() (*config, error) {
// viper.SetConfigFile("./experiment.yaml")
// if err := viper.ReadInConfig(); err != nil {
// return nil, err
// }
// fmt.Println("Using config file:", viper.ConfigFileUsed())
// return &config{
// gnmiTarget: viper.GetString("gnmi-target"),
// ceosTarget: viper.GetString("ceos-target"),
// controller: viper.GetString("controller"),
// }, nil
//}
//
//func add(opts *transport.TransportOption, writer *fileWriter) {
// var errs int
// start := time.Now()
// if err := pnd.AddDevice("", opts, sbiID); err != nil {
// log.Error(err)
// errs++
// }
//
// duration := time.Since(start)
// writer.write(fmt.Sprintf("%v;add;%v;%v;%v;%v\n", time.Now().UnixNano(), opts.Address, opts.Type.String(), duration, errs))
//}
//
//func get(ouid string, opts *transport.TransportOption, writer *fileWriter) {
// var errs int
// start := time.Now()
// _, err := pnd.Request(uuid.MustParse(ouid), "/system/config/hostname")
// if err != nil {
// log.Error(err)
// errs++
// }
//
// duration := time.Since(start)
// writer.write(fmt.Sprintf("%v;get;%v;%v;%v\n", time.Now().UnixNano(), opts.Type.String(), duration, errs))
//}
//
//func delete(ouid string, opts *transport.TransportOption, writer *fileWriter) {
// var errs int
// start := time.Now()
// if err := pnd.RemoveDevice(uuid.MustParse(ouid)); err != nil {
// log.Error(err)
// errs++
// }
//
// duration := time.Since(start)
// writer.write(fmt.Sprintf("%v;delete;%v;%v;%v\n", time.Now().UnixNano(), opts.Type.String(), duration, errs))
//}
//
//func executeExperiment(params experiment, c *config) error {
// expName := fmt.Sprintf("/out/results-%v-%v.csv", params.execMode, params.iterations)
// writer := newFileWriter(expName)
// coll := newCollector(targets, fmt.Sprintf("/out/metrics-%v-%v.json", params.execMode, params.iterations))
// coll.start()
// defer coll.stop()
// start := time.Now()
//
// opts := &transport.TransportOption{
// Address: c.ceosTarget,
// Username: "admin",
// Password: "admin",
// Tls: false,
// TransportOption: &transport.TransportOption_GnmiTransportOption{
// GnmiTransportOption: &transport.GnmiTransportOption{},
// },
// Type: params.execMode,
// }
//
// for i := 0; i < params.iterations; i++ {
// add(opts, writer)
// }
//
// resp, err := api.GetIds(c.controller)
// if err != nil {
// return err
// }
//
// ondList := resp[0].Ond
// for _, ond := range ondList {
// get(ond.Id, opts, writer)
// }
//
// for _, ond := range ondList {
// delete(ond.Id, opts, writer)
// }
// duration := time.Since(start)
// writer.write(fmt.Sprintf("%v;duration;sequential;%v;%v\n", time.Now().UnixNano(), params.iterations, duration))
// writer.close()
// log.WithFields(log.Fields{
// "duration": duration,
// "iterations": params.iterations,
// "exec": params.execMode,
// }).Info("experiment ended")
// return nil
//}
ceos-target: clab-thesis-ceos:6030
cli_pnd: f8c649be-60ee-4a53-acf9-cebc8eebf3c2
cli_sbi: f370efe4-fb3c-411b-81b6-7f536027eccb
controller: clab-thesis-gosdn:55055
gnmi-target: clab-thesis-gnmi-target:7030
/*
Copyright © 2021 Manuel Kieweg <mail@manuelkieweg.de>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package cmd
import (
"context"
"net"
spb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/southbound"
"code.fbi.h-da.de/danet/gosdn/csbi"
"code.fbi.h-da.de/danet/gosdn/csbi/config"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"google.golang.org/grpc/peer"
)
// generateCmd represents the generate command.
var generateCmd = &cobra.Command{
Use: "generate",
Short: "generates a blank csbi boilerplate",
Run: func(cmd *cobra.Command, args []string) {
var t spb.Type
switch opcode {
case "plugin":
t = spb.Type_TYPE_PLUGIN
case "csbi":
t = spb.Type_TYPE_CONTAINERISED
default:
log.Fatal("invalid opcode")
}
addr, err := net.ResolveTCPAddr("tcp", "localhost:55055")
if err != nil {
log.Fatal(err)
}
repo := csbi.NewRepository(config.RepositoryBasePath())
ctx := peer.NewContext(context.Background(), &peer.Peer{Addr: addr})
_, err = csbi.Generate(ctx, nil, repo, t)
if err != nil {
log.Error(err)
}
},
}
var opcode string
func init() {
rootCmd.AddCommand(generateCmd)
generateCmd.Flags().StringVar(&opcode, "type", "plugin", "generation target (csbi or plugin)")
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment