Exemple #1
0
func (s *systemtestSuite) verifyEPs(containers []*container) error {
	var err error

	// get the list of eps to verify
	epList := make([]string, len(containers))
	for ix, cont := range containers {
		epList[ix] = cont.eth0.ip
	}

	err = nil
	dbgOut := ""
	for try := 0; try < 20; try++ {
		for _, n := range s.nodes {
			if n.Name() == "k8master" {
				continue
			}
			dbgOut, err = n.verifyEPs(epList)
			if err != nil {
				break
			}
		}

		if err == nil {
			logrus.Info("EPs %+v verified on all nodes", epList)
			return nil
		}
		time.Sleep(1 * time.Second)
	}
	logrus.Errorf("Failed to verify EPs after 20 sec %v", err)
	logrus.Info("Debug output:\n %s", dbgOut)
	return err
}
// PrintRunningStep ...
func PrintRunningStep(title, version string, idx int) {
	if len(version) > 25 {
		version = "..." + stringutil.MaxLastChars(version, 22)
	}
	content := fmt.Sprintf("| (%d) %s (%s) |", idx, title, version)
	charDiff := len(content) - stepRunSummaryBoxWidthInChars

	if charDiff < 0 {
		// shorter than desired - fill with space
		content = fmt.Sprintf("| (%d) %s (%s)%s |", idx, title, version, strings.Repeat(" ", -charDiff))
	} else if charDiff > 0 {
		// longer than desired - trim title
		trimmedTitleWidth := len(title) - charDiff - 3
		if trimmedTitleWidth < 0 {
			log.Errorf("Step Version too long, can't present title at all! : %s", version)
		} else {
			content = fmt.Sprintf("| (%d) %s... (%s) |", idx, title[0:trimmedTitleWidth], version)
		}
	}

	sep := strings.Repeat("-", len(content))
	log.Info(sep)
	log.Infof(content)
	log.Info(sep)
	log.Info("|" + strings.Repeat(" ", stepRunSummaryBoxWidthInChars-2) + "|")
}
Exemple #3
0
func setupLogging() {
	if config.Settings.Moire.Debug {
		log.Info("Logging in DEBUG mode")
		log.SetLevel(log.DebugLevel)
	}

	// log.SetFlags(log.Ldate | log.Ltime | log.Llongfile)
	log.SetFormatter(&log.TextFormatter{})

	if config.Settings.Moire.SentryDSN != "" {
		levels := []log.Level{
			log.PanicLevel,
			log.FatalLevel,
			log.ErrorLevel,
		}

		hook, err := logrus_sentry.NewSentryHook(config.Settings.Moire.SentryDSN, levels)
		if err != nil {
			log.Error("Unable to connect to sentry")
		} else {
			log.Info("Adding Sentry Hook")
			log.AddHook(hook)
		}
	}
}
Exemple #4
0
// OptionKVOpts function returns an option setter for kvstore options
func OptionKVOpts(opts map[string]string) Option {
	return func(c *Config) {
		if opts["kv.cacertfile"] != "" && opts["kv.certfile"] != "" && opts["kv.keyfile"] != "" {
			log.Info("Option Initializing KV with TLS")
			tlsConfig, err := tlsconfig.Client(tlsconfig.Options{
				CAFile:   opts["kv.cacertfile"],
				CertFile: opts["kv.certfile"],
				KeyFile:  opts["kv.keyfile"],
			})
			if err != nil {
				log.Errorf("Unable to set up TLS: %s", err)
				return
			}
			if _, ok := c.Scopes[datastore.GlobalScope]; !ok {
				c.Scopes[datastore.GlobalScope] = &datastore.ScopeCfg{}
			}
			if c.Scopes[datastore.GlobalScope].Client.Config == nil {
				c.Scopes[datastore.GlobalScope].Client.Config = &store.Config{TLS: tlsConfig}
			} else {
				c.Scopes[datastore.GlobalScope].Client.Config.TLS = tlsConfig
			}
			// Workaround libkv/etcd bug for https
			c.Scopes[datastore.GlobalScope].Client.Config.ClientTLS = &store.ClientTLSConfig{
				CACertFile: opts["kv.cacertfile"],
				CertFile:   opts["kv.certfile"],
				KeyFile:    opts["kv.keyfile"],
			}
		} else {
			log.Info("Option Initializing KV without TLS")
		}
	}
}
Exemple #5
0
// Start implementation of the tether.Extension interface
func (t *Toolbox) Start() error {
	t.Service.PrimaryIP = t.defaultIP

	t.stop = make(chan struct{})
	on := make(chan struct{})

	t.Service.PowerCommand.PowerOn.Handler = func() error {
		log.Info("toolbox: service is ready (power on event received)")
		close(on)
		return nil
	}

	err := t.Service.Start()
	if err != nil {
		return err
	}

	// Wait for the vmx to send the OS_PowerOn message,
	// at which point it will be ready to service vix command requests.
	log.Info("toolbox: waiting for initialization")

	select {
	case <-on:
	case <-time.After(time.Second):
		log.Warn("toolbox: timeout waiting for power on event")
	}

	return nil
}
Exemple #6
0
func buildRedirectURL(core *roll.Core, w http.ResponseWriter, responseType, subject, scope string, app *roll.Application) (string, error) {
	log.Info("build redirect, app ctx: ", app.RedirectURI)

	var redirectURL string
	switch responseType {
	case "token":
		//Create signed token
		token, err := generateJWT(subject, scope, core, app)
		if err != nil {
			return "", err
		}
		redirectURL = fmt.Sprintf("%s#access_token=%s&token_type=Bearer", app.RedirectURI, token)
	case "code":
		token, err := generateSignedCode(core, subject, scope, app)
		if err != nil {
			return "", err
		}
		redirectURL = fmt.Sprintf("%s?code=%s", app.RedirectURI, token)
	default:
		panic(errors.New("unexpected response type in buildRedirectURL: " + responseType))
	}

	log.Info("redirect url: ", redirectURL)

	return redirectURL, nil
}
Exemple #7
0
func runVault(docker *dockerclient.DockerClient) (string, string) {
	var bootedContainer bool

	//Is vault running?
	log.Info("Is vault running?")
	info := dockerutil.GetAcceptanceTestContainerInfo(docker, "atest-vault")

	if info != nil {
		log.Info("Vault container found - state is: ", info.State.StateString())
		log.Fatal("You must kill and remove the container manually - can't get the root token from an existing container in this test")
		return "", "" //not reached
	}

	log.Info("Vault is not running - create container context")
	bootedContainer = true
	vaultContainerCtx := createVaultTestContainerContext()

	//Create and start the container.
	log.Info("Create and start the container")
	containerId := dockerutil.CreateAndStartContainer(docker, []string{"IPC_LOCK"}, nil, vaultContainerCtx)

	if bootedContainer {
		//Give the container a little time to boot
		time.Sleep(1 * time.Second)
	}

	//Now initialize and unseal the damn vault
	rootToken := initializeVault()

	return containerId, rootToken
}
Exemple #8
0
func (s *systemtestSuite) createVolume(host, tenant, name string, opts map[string]string) error {
	log.Infof("Creating %s/%s on %s", tenant, name, host)

	optsStr := []string{}

	if opts != nil {
		for key, value := range opts {
			optsStr = append(optsStr, "--opt")
			optsStr = append(optsStr, key+"="+value)
		}
	}

	cmd := fmt.Sprintf("docker volume create -d volplugin --name %s/%s %s", tenant, name, strings.Join(optsStr, " "))

	if out, err := s.vagrant.GetNode(host).RunCommandWithOutput(cmd); err != nil {
		log.Info(string(out))
		return err
	}

	if out, err := s.volcli(fmt.Sprintf("volume get %s %s", tenant, name)); err != nil {
		log.Error(out)
		return err
	}

	if out, err := s.vagrant.GetNode(host).RunCommandWithOutput(cmd); err != nil {
		log.Info(string(out))
		return err
	}

	return nil
}
Exemple #9
0
func BuildConnection(ws *websocket.Conn) {
	log.Info("BuildConnection()")
	token := ws.Request().URL.Query().Get("token")
	log.Debug(token)
	var uci userConnectionInfo
	err := validateToken(token, time.Now(), ws.RemoteAddr(), &uci)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Error("validation error")
		// how should this reply to the client?
		return
	}

	onlineUser := &OnlineUser{
		Connection: ws,
		Uci:        uci,
		Send:       make(chan envelope, 256),
	}
	runningRoom.Users[onlineUser] = true
	go onlineUser.PushToClient()
	onlineUser.PullFromClient()
	delete(runningRoom.Users, onlineUser)
	log.Info("tore down user connection")
}
Exemple #10
0
//NewLoadBalancer creates a new instance of a Round Robin load balancer
func (rrf *RoundRobinLoadBalancerFactory) NewLoadBalancer(backendName, caCertPath string, servers []config.ServerConfig) (LoadBalancer, error) {
	var rrlb RoundRobinLoadBalancer

	if backendName == "" {
		return nil, fmt.Errorf("Expected non-empty backend name")
	}

	if len(servers) == 0 {
		return nil, fmt.Errorf("Expected at least one server in servers argument")
	}

	rrlb.backend = backendName
	rrlb.servers = ring.New(len(servers))

	for _, s := range servers {

		lbEndpoint := new(LoadBalancerEndpoint)
		lbEndpoint.Address = fmt.Sprintf("%s:%d", s.Address, s.Port)
		metrics.SetGauge([]string{"endpoint", lbEndpoint.Address}, 1.0)
		lbEndpoint.PingURI = s.PingURI
		lbEndpoint.Up = true
		lbEndpoint.CACertPath = caCertPath

		log.Info("Spawing health check for address ", lbEndpoint.Address)
		healthCheckFunction := MakeHealthCheck(lbEndpoint, s, true)
		go healthCheckFunction()

		log.Info("Adding server with address ", lbEndpoint.Address)
		rrlb.servers.Value = lbEndpoint
		rrlb.servers = rrlb.servers.Next()
	}

	return &rrlb, nil
}
Exemple #11
0
// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
func TestFormat1TestSuite(t *testing.T) {
	//ts := new(Format1TestSuite)
	log.Info("TestFormat1TestSuite - Running test suite")
	suite.Run(t, new(Format1TestSuite))
	log.Info("TestFormat1TestSuite - Finished test suite")

}
Exemple #12
0
func importCountries(conn *transaction.Connection, config model.YAMLCountries) (err error) {
	log.Info("Import countries started")

	if err = conn.RemoveCountriesTranslations(); err != nil {
		return
	}
	for countryCode, country := range config.Countries {
		if conn.IsCountryExist(countryCode) == false {
			err = errors.New("Missing country")
			break
		}

		errorInsideTranslation := false
		for languageCode, translation := range country.Translations {
			if conn.IsLanguageExist(languageCode) == false {
				errorInsideTranslation = true
				err = errors.New("No language")
				break
			}

			if err = conn.CreateCountryTranslation(countryCode, languageCode, translation); err != nil {
				errorInsideTranslation = true
				break
			}
		}

		if errorInsideTranslation == true {
			break
		}
	}
	log.Info("Import countries finished")
	return
}
Exemple #13
0
func importPhoneNumbersCategories(conn *transaction.Connection, config model.YAMLPhoneNumbersCategories) (err error) {
	log.Info("Import phonenumber categories started")

	if err = conn.RemovePhonenumbersAndCategories(); err != nil {
		return
	}

	for categoryCode, category := range config.Categories {
		if err = conn.CreatePhonenumberCategory(categoryCode); err != nil {
			break
		}

		errorInsideTranslation := false
		for languageCode, translation := range category.Translations {
			if conn.IsLanguageExist(languageCode) == false {
				errorInsideTranslation = true
				err = errors.New("No language")
				break
			}

			if err = conn.CreatePhonenumberCategoryTranslation(categoryCode, languageCode, translation); err != nil {
				errorInsideTranslation = true
				break
			}
		}

		if errorInsideTranslation == true {
			break
		}
	}
	log.Info("Import phonenumber categories finished")
	return
}
Exemple #14
0
func (r *Runner) getVersions(options *flags.Options) (siVersion, cloudVersion int, err error) {
	var siError, cloudError error
	versionChan := make(chan struct{}, 2)

	go func() {
		siVersion, siError = r.imgDataOrigin.GetLatestVersion(options)
		log.Info("siVersion: ", siVersion)
		versionChan <- struct{}{}
	}()

	go func() {
		cloudVersion, cloudError = r.imgDataTarget.GetLatestVersion(options)
		log.Info("cloudVersion: ", cloudVersion)
		versionChan <- struct{}{}
	}()

	for i := 0; i < 2; i++ {
		<-versionChan
	}

	if siError != nil {
		return 0, 0, siError
	}
	if cloudError != nil {
		if _, ok := cloudError.(*cloud.ErrVersionNotFound); !ok {
			return 0, 0, cloudError
		}
	}
	return
}
Exemple #15
0
//GetManifestsV2Handler is
func GetManifestsV2Handler(ctx *macaron.Context) (int, []byte) {
	repository := ctx.Params(":repository")
	namespace := ctx.Params(":namespace")
	tag := ctx.Params(":tag")

	t := new(models.DockerTagV2)
	if _, err := t.Get(namespace, repository, tag); err != nil && err == gorm.ErrRecordNotFound {
		log.Info("Not found repository in tetting tag manifest: %s/%s:%s", namespace, repository, tag)

		result, _ := module.EncodingError(module.BLOB_UNKNOWN, fmt.Sprintf("%s/%s", namespace, repository))
		return http.StatusNotFound, result
	} else if err != nil && err != gorm.ErrRecordNotFound {
		log.Info("Failed to get tag manifest %s/%s:%s : ", namespace, repository, tag, err.Error())

		result, _ := module.EncodingError(module.UNKNOWN, err.Error())
		return http.StatusBadRequest, result
	}

	digest, _ := signature.DigestManifest([]byte(t.Manifest))

	ctx.Resp.Header().Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json")
	ctx.Resp.Header().Set("Docker-Content-Digest", digest)
	ctx.Resp.Header().Set("Content-Length", fmt.Sprint(len(t.Manifest)))

	return http.StatusOK, []byte(t.Manifest)
}
Exemple #16
0
// we'll connect to the database through this function
func Init() {
	dbMutex.Lock()
	defer dbMutex.Unlock()

	if initialized {
		return
	}

	DBUrl = url.URL{
		Scheme:   "postgres",
		Host:     config.Constants.DbAddr,
		Path:     config.Constants.DbDatabase,
		RawQuery: "sslmode=disable",
	}

	logrus.Info("Connecting to DB on %s", DBUrl.String())

	DBUrl.User = url.UserPassword(config.Constants.DbUsername, config.Constants.DbPassword)

	var err error
	DB, err = gorm.Open("postgres", DBUrl.String())
	//	DB, err := gorm.Open("sqlite3", "/tmp/gorm.db")
	if err != nil {
		logrus.Fatal(err.Error())
	}

	DB.SetLogger(logrus.StandardLogger())

	logrus.Info("Connected!")
	initialized = true
}
Exemple #17
0
//HeadBlobsV2Handler is
func HeadBlobsV2Handler(ctx *macaron.Context) (int, []byte) {
	digest := ctx.Params(":digest")
	tarsum := strings.Split(digest, ":")[1]

	i := new(models.DockerImageV2)
	if err := i.Get(tarsum); err != nil && err == gorm.ErrRecordNotFound {
		log.Info("Not found blob: %s", tarsum)

		result, _ := module.EncodingError(module.BLOB_UNKNOWN, digest)
		return http.StatusNotFound, result
	} else if err != nil && err != gorm.ErrRecordNotFound {
		log.Info("Failed to get blob %s: %s", tarsum, err.Error())

		result, _ := module.EncodingError(module.UNKNOWN, err.Error())
		return http.StatusBadRequest, result
	}

	ctx.Resp.Header().Set("Content-Type", "application/json; charset=utf-8")
	ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
	ctx.Resp.Header().Set("Docker-Content-Digest", digest)
	ctx.Resp.Header().Set("Content-Length", fmt.Sprint(i.Size))

	result, _ := json.Marshal(map[string]string{})
	return http.StatusOK, result
}
Exemple #18
0
func main() {
	log.Info("GlusterD starting")

	context.Init()

	for _, c := range commands.Commands {
		context.Rest.SetRoutes(c.Routes())
	}

	sigCh := make(chan os.Signal)
	signal.Notify(sigCh)
	go func() {
		for s := range sigCh {
			log.WithField("signal", s).Debug("Signal recieved")
			switch s {
			case os.Interrupt:
				log.WithField("signal", s).Info("Recieved SIGTERM. Stopping GlusterD.")
				context.Rest.Stop()
				log.Info("Termintaing GlusterD.")
				os.Exit(0)

			default:
				continue
			}
		}
	}()

	err := context.Rest.Listen()
	if err != nil {
		log.Fatal("Could not start GlusterD Rest Server. Aborting.")
	}
}
Exemple #19
0
func (d *DBConf) init() {

	// get the schema, and apply it before moving on
	s := version.GetSchemaFromDb(d.db)

	// bootstrap
	if s.Version == version.First {
		logrus.Info("Bootstrapping config db")
		err := s.Apply(d.db)
		if err != nil {
			logrus.Errorf("Unable to bootstrap config %s", err.Error())
		}

	}

	// if we don't have the correct version, apply the new one
	if version.LatestSchema().Greater(s) {
		logrus.Info("Upgrading config db version from %s to %s", s.Version, version.LatestSchema().Version)
		err := version.LatestSchema().Apply(d.db)
		if err != nil {
			logrus.Errorf("Unable to apply schema version %s to config db %s", version.LatestSchema().Version, err.Error())
		}
	}

	logrus.Infof("Using db config version %s", s.Version)

	err := d.initAdminUser()
	if err != nil {
		logrus.Errorf("Unable init admin user: %s", err)
	}
}
Exemple #20
0
func (pm *ProcessManager) background(waitChan chan pidChangeNotification, subscriptions []chan int, signals chan os.Signal) {
	log.Info("Going into background mode")
	for {
		select {
		case status := <-waitChan:
			{
				pm.notify(status.wstatus.ExitStatus(), subscriptions)
				pm.tdcb()
				pm.killProcess(waitChan)
				return
			}
		case <-signals:
			{
				log.Info("Tearing down at signal")
				pm.notify(-1, subscriptions)
				pm.tdcb()
				pm.killProcess(waitChan)
				return
			}
		case tearDownChan := <-pm.teardown:
			{
				log.Info("Tearing down")
				pm.notify(-1, subscriptions)
				pm.killProcess(waitChan)
				pm.tdcb()
				tearDownChan <- nil
				return
			}
		case subscribe := <-pm.subscribe:
			{
				subscriptions = append(subscriptions, subscribe)
			}
		}
	}
}
Exemple #21
0
// GitCleanPull wipes dirty local changes and perform pull on specific git branch.
func (e *Engine) GitCleanPull() error {
	if !e.IsGitRepo() {
		return nil
	}

	// Clean all existing dirty changes
	cmd := exec.Command("git", "reset", "--hard")
	cmd.Dir = e.Root

	output, err := cmd.CombinedOutput()
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Fatal(string(output))

		return err
	}

	logrus.Info(string(output))

	err = e.GitFetchCheckoutPull()
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Fatal("Unabled to pull from git")

		return err
	}

	logrus.Info(string(output))
	return nil
}
Exemple #22
0
func main() {

	s := make([]string, 3)

	s[0] = "Hey"
	s[1] = "How"
	s[2] = "Are"

	log.Info("Values added to the Variable s")
	fmt.Println(s)

	log.Info("Adding other Variable in the Slice")
	k := append(s, "You")

	fmt.Println(k)

	// Two Dimensional Slice

	l := make([][]int, 4)

	for x := 0; x < 4; x++ {

		innerLen := x + 1
		l[x] = make([]int, innerLen)
		for y := 0; y < innerLen; y++ {

			l[x][y] = x + y

		}
	}

	fmt.Println(l)

}
Exemple #23
0
func main() {
	log.Info("Starting rancher-metadata")
	parseFlags()
	err := loadAnswers()
	if err != nil {
		log.Fatal("Cannot startup without a valid Answers file")
	}
	watchSignals()

	router.HandleFunc("/favicon.ico", http.NotFound)
	router.HandleFunc("/", root).
		Methods("GET", "HEAD").
		Name("Root")

	for _, version := range versions {
		router.HandleFunc("/{version:"+version+"}", metadata).
			Methods("GET", "HEAD").
			Name("Version:" + version)

		router.HandleFunc("/{version:"+version+"}/{key:.*}", metadata).
			Methods("GET", "HEAD").
			Name("Metadata")
	}

	log.Info("Listening on ", *listen)
	log.Fatal(http.ListenAndServe(*listen, router))
}
Exemple #24
0
func main() {
	c, err := NewContext()
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Fatal("Unable to load application context.")
		return
	}

	log.Info("Commence primary ignition.")

	log.Info("Launching job runner.")
	go Runner(c)

	// v1 routes
	http.HandleFunc("/v1/auth_service", BindContext(c, AuthDiscoverHandler))

	http.HandleFunc("/v1/job", BindContext(c, JobHandler))
	http.HandleFunc("/v1/job/kill", BindContext(c, JobKillHandler))
	http.HandleFunc("/v1/job/kill_all", BindContext(c, JobKillAllHandler))
	http.HandleFunc("/v1/job/queue_stats", BindContext(c, JobQueueStatsHandler))

	log.WithFields(log.Fields{
		"address": c.ListenAddr(),
	}).Info("Web API listening.")
	http.ListenAndServe(c.ListenAddr(), nil)
}
Exemple #25
0
func main() {

	log.Info("starting NNTP server...")
	conf, err := config.Ensure("settings.json")
	if err != nil {
		log.Fatal(err)
	}

	if conf.Log == "debug" {
		log.SetLevel(log.DebugLevel)
	}

	serv := &nntp.Server{
		Config: conf.NNTP,
		Feeds:  conf.Feeds,
	}
	serv.Storage, err = store.NewFilesytemStorage(conf.Store.Path, false)
	if err != nil {
		log.Fatal(err)
	}
	l, err := net.Listen("tcp", conf.NNTP.Bind)
	if err != nil {
		log.Fatal(err)
	}
	log.Info("listening on ", l.Addr())
	err = serv.Serve(l)
	if err != nil {
		log.Fatal(err)
	}
}
Exemple #26
0
func (m *mrtManager) enable(c *config.MrtConfig) error {
	if _, ok := m.writer[c.FileName]; ok {
		return fmt.Errorf("%s already exists", c.FileName)
	}

	rInterval := c.RotationInterval
	if rInterval != 0 && rInterval < 30 {
		log.Info("minimum mrt dump interval is 30 seconds")
		rInterval = 30
	}
	dInterval := c.DumpInterval
	if c.DumpType == config.MRT_TYPE_TABLE {
		if dInterval < 60 {
			log.Info("minimum mrt dump interval is 30 seconds")
			dInterval = 60
		}
	} else if c.DumpType == config.MRT_TYPE_UPDATES {
		dInterval = 0
		if len(c.TableName) > 0 {
			return fmt.Errorf("can't specify the table name with the update dump type")
		}
	}

	w, err := newMrtWriter(m.bgpServer, c.DumpType, c.FileName, c.TableName, rInterval, dInterval)
	if err == nil {
		m.writer[c.FileName] = w
	}
	return err
}
Exemple #27
0
func (s *Session) pingLoop() {
	s.wg.Add(1)
	defer func() {
		s.wg.Done()
		s.Shutdown()
	}()
	timer := time.NewTimer(time.Second * time.Duration(PingInterval))
	latestPing := time.Now().Unix()
	for {
		select {
		case _ = <-s.PingChan:
			// update ping recieved time
			latestPing = time.Now().Unix()
			// send pong message
		case <-timer.C:
			if time.Now().Unix()-latestPing >= PingInterval {
				log.Info("ping timeout")
				return
			}
		case _, ok := <-s.shutdownChan:
			if !ok {
				log.Info("shutdown analyze loop")
				return
			}
		}
	}
}
Exemple #28
0
//GetTagsListV2Handler is
func GetTagsListV2Handler(ctx *macaron.Context) (int, []byte) {
	var err error
	repository := ctx.Params(":repository")
	namespace := ctx.Params(":namespace")

	data := map[string]interface{}{}
	data["name"] = fmt.Sprintf("%s/%s", namespace, repository)

	r := new(models.DockerV2)

	if data["tags"], err = r.GetTags(namespace, repository); err != nil && err == gorm.ErrRecordNotFound {
		log.Info("Not found repository in getting tags list: %s/%s", namespace, repository)

		result, _ := module.EncodingError(module.BLOB_UNKNOWN, fmt.Sprintf("%s/%s", namespace, repository))
		return http.StatusNotFound, result
	} else if err != nil && err != gorm.ErrRecordNotFound {
		log.Info("Failed found repository in getting tags list %s/%s: %s", namespace, repository, err.Error())

		result, _ := module.EncodingError(module.UNKNOWN, err.Error())
		return http.StatusBadRequest, result
	}

	result, _ := json.Marshal(data)
	return http.StatusOK, result
}
Exemple #29
0
// test adding vlan
func setupVlans() error {
	for i := 0; i < NUM_AGENT; i++ {
		log.Info("Index %d \n", i)
		for j := 1; j < 5; j++ {
			log.Info("Index %d \n", j)
			//log.Infof("Adding Vlan %d on %s", j, localIpList[i])
			err := vrtrAgents[i].AddNetwork(uint16(j), uint32(j), "", "tenant1")
			if err != nil {
				log.Errorf("Error adding vlan %d to vrtrAgent. Err: %v", j, err)
				return err
			}
			err = vxlanAgents[i].AddNetwork(uint16(j), uint32(j), "", "default")
			if err != nil {
				log.Errorf("Error adding vlan %d to vxlanAgent. Err: %v", j, err)
				return err
			}
			err = vlanAgents[i].AddNetwork(uint16(j), uint32(j), "", "default")
			if err != nil {
				log.Errorf("Error adding vlan %d to vlanAgent. Err: %v", j, err)
				return err
			}
		}
	}
	for i := 0; i < NUM_VLRTR_AGENT; i++ {
		err := vlrtrAgents[i].AddNetwork(uint16(1), uint32(1),
			fmt.Sprintf("10.10.%d.%d", 1, 1), "default")
		if err != nil {
			log.Errorf("Error adding vlan 1 to vlrtrAgent. Err: %v", err)
			return err
		}
	}
	return nil
}
Exemple #30
0
//DoPost handles post requests, which are used to spawn new listener instances. This service is intended to
//support testability, and will likely not be exposed in production configurations.
func (SpawnKillerDef) DoPost(kvs kvstore.KVStore, resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	pidToKill := resourceIDFromURI(req.RequestURI)
	log.Info("request kill of pid ", pidToKill)

	pid, err := strconv.Atoi(pidToKill)
	if err != nil {
		resp.WriteHeader(http.StatusBadRequest)
		return nil, err
	}

	if !isSpawnedPid(pid) {
		myError := fmt.Errorf("Asked to kill pid %d, which we did not spawn", pid)
		log.Warn(myError.Error())
		resp.WriteHeader(http.StatusBadRequest)
		return nil, myError
	}

	log.Info("Killing ", pid)
	cmd := exec.Command("kill", pidToKill)

	err = cmd.Run()
	if err != nil {
		resp.WriteHeader(http.StatusInternalServerError)
		return nil, err
	}

	removePid(pid)
	log.Info("Stone cold killa finished")

	return nil, nil
}