예제 #1
0
// Remove a vlan
func (self *Vxlan) RemoveVlan(vlanId uint16, vni uint32) error {
	vlan := self.vlanDb[vlanId]
	if vlan == nil {
		log.Fatalf("Could not find the vlan %d", vlanId)
	}

	// Make sure the flood lists are empty
	if vlan.localFlood.NumOutput() != 0 {
		log.Fatalf("VLAN flood list is not empty")
	}

	log.Infof("Deleting vxlan: %d, vlan: %d", vni, vlanId)

	// Uninstall the flood lists
	vlan.allFlood.Delete()
	vlan.localFlood.Delete()

	// Uninstall mac miss Entries
	vlan.localMacMiss.Delete()
	vlan.vtepMacMiss.Delete()

	// uninstall vtep vlan mapping flows
	for _, portVlanFlow := range vlan.vtepVlanFlowDb {
		portVlanFlow.Delete()
	}

	// Remove it from DB
	delete(self.vlanDb, vlanId)

	return nil
}
예제 #2
0
파일: service.go 프로젝트: rowhit/os
func enable(c *cli.Context) {
	changed := false
	cfg, err := config.LoadConfig()
	if err != nil {
		log.Fatal(err)
	}

	for _, service := range c.Args() {
		if val, ok := cfg.Rancher.ServicesInclude[service]; !ok || !val {
			if strings.HasPrefix(service, "/") && !strings.HasPrefix(service, "/var/lib/rancher/conf") {
				log.Fatalf("ERROR: Service should be in path /var/lib/rancher/conf")
			}
			if _, err := compose.LoadServiceResource(service, true, cfg); err != nil {
				log.Fatalf("could not load service %s", service)
			}
			cfg.Rancher.ServicesInclude[service] = true
			changed = true
		}
	}

	if changed {
		if err := cfg.Set("rancher.services_include", cfg.Rancher.ServicesInclude); err != nil {
			log.Fatal(err)
		}
	}
}
예제 #3
0
파일: join.go 프로젝트: yehohanan7/swarm
func join(c *cli.Context) {
	dflag := getDiscovery(c)
	if dflag == "" {
		log.Fatalf("discovery required to join a cluster. See '%s join --help'.", c.App.Name)
	}

	addr := c.String("advertise")
	if addr == "" {
		log.Fatal("missing mandatory --advertise flag")
	}
	if !checkAddrFormat(addr) {
		log.Fatal("--advertise should be of the form ip:port or hostname:port")
	}

	joinDelay, err := time.ParseDuration(c.String("delay"))
	if err != nil {
		log.Fatalf("invalid --delay: %v", err)
	}
	if joinDelay < time.Duration(0)*time.Second {
		log.Fatalf("--delay should not be a negative number")
	}

	hb, err := time.ParseDuration(c.String("heartbeat"))
	if err != nil {
		log.Fatalf("invalid --heartbeat: %v", err)
	}
	if hb < 1*time.Second {
		log.Fatal("--heartbeat should be at least one second")
	}
	ttl, err := time.ParseDuration(c.String("ttl"))
	if err != nil {
		log.Fatalf("invalid --ttl: %v", err)
	}
	if ttl <= hb {
		log.Fatal("--ttl must be strictly superior to the heartbeat value")
	}

	d, err := discovery.New(dflag, hb, ttl, getDiscoveryOpt(c))
	if err != nil {
		log.Fatal(err)
	}

	// if joinDelay is 0, no delay will be executed
	// if joinDelay is larger than 0,
	// add a random delay between 0s and joinDelay at start to avoid synchronized registration
	if joinDelay > 0 {
		r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
		delay := time.Duration(r.Int63n(int64(joinDelay)))
		log.Infof("Add a random delay %s to avoid synchronized registration", delay)
		time.Sleep(delay)
	}

	for {
		log.WithFields(log.Fields{"addr": addr, "discovery": dflag}).Infof("Registering on the discovery service every %s...", hb)
		if err := d.Register(addr); err != nil {
			log.Error(err)
		}
		time.Sleep(hb)
	}
}
예제 #4
0
func delete(serviceName string, etcdPath string) error {
	log.Infoln("cli.delete():Start Delete")
	client, err := etcdclient.NewEtcdClient(etcdPath)
	if err != nil {
		log.Fatalf("cli.delete():%+v\n", err)
		fmt.Printf("[error]cli.delete():%+v\n", err)
		return err
	}

	//quary service
	s, err := client.GetService(serviceName)
	if err != nil {
		log.Fatalf("cli.delete():%+v\n", err)
		fmt.Printf("[error]cli.delete():%+v\n", err)
		return err
	}

	//delete from etcd
	err = client.DeleteService(serviceName)
	if err != nil {
		log.Fatalf("cli.delete():%+v\n", err)
		fmt.Printf("[error]cli.delete():%+v\n", err)
	}

	//delete from swarm
	err = service.DeleteService(s)
	if err != nil {
		log.Fatalf("cli.delete():%+v\n", err)
		fmt.Printf("[error]cli.delete():%+v\n", err)
		return err
	}
	return nil
}
예제 #5
0
func (d *daemon) registerService() {
	// Create an objdb client
	objdbClient := client.NewClient()

	// Get the address to be used for local communication
	localIP, err := objdbClient.GetLocalAddr()
	if err != nil {
		log.Fatalf("Error getting locla IP address. Err: %v", err)
	}

	// service info
	srvInfo := objdb.ServiceInfo{
		ServiceName: "netmaster",
		HostAddr:    localIP,
		Port:        9999,
	}

	// Register the node with service registry
	err = objdbClient.RegisterService(srvInfo)
	if err != nil {
		log.Fatalf("Error registering service. Err: %v", err)
	}

	log.Infof("Registered netmaster service with registry")
}
예제 #6
0
//Show displays the details of an Account.
func Show(cmd *cli.Cmd) {
	email := cmd.String(cli.StringArg{
		Name:      "EMAIL",
		Desc:      "email address",
		HideValue: true,
	})

	cmd.Action = func() {
		a := authorization.Account{
			Email: *email,
		}

		account, resp, errs := a.ShowAcct()

		if len(errs) > 0 {
			log.Fatalf("Could not retrieve account: %s", errs[0])
		}

		if resp.StatusCode != 200 {
			log.Fatalf("Could not retrieve account: %s", resp.Status)
		}

		printAccountDetail(account)
	}
}
예제 #7
0
파일: grpc.go 프로젝트: otsimo/otsimoctl
func discovery() {
	var err error
	var opts []grpc.DialOption

	if insecureDiscovery {
		opts = append(opts, grpc.WithInsecure())
	} else {
		auth := credentials.NewClientTLSFromCert(nil, getServerName(discoveryServiceURL))
		opts = append(opts, grpc.WithTransportCredentials(auth))
	}
	discoveryConn, err = grpc.Dial(discoveryServiceURL, opts...)
	if err != nil {
		logrus.Fatalf("grpc.go: error while connection to discovery service %v", err)
	}
	discoveryClient = pb.NewDiscoveryClient(discoveryConn)
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	res, err := discoveryClient.Get(ctx, &pb.DiscoveryRequest{
		Environment: discoveryEnv,
		SdkVersion:  Version + "-otsimoctl",
		OsName:      runtime.GOOS,
	})
	if err != nil {
		logrus.Fatalf("grpc:go: failed to get discovery config err=%v", err)
	}
	discoveryServices = res
}
예제 #8
0
//Archive an Application
func Archive(cmd *cli.Cmd) {
	uuid := cmd.String(cli.StringArg{
		Name:      "UUID",
		Desc:      "Application UUID",
		HideValue: true,
	})

	cmd.Action = func() {
		app := application.Application{
			UUID: *uuid,
		}

		_, resp, errs := app.Delete()

		if errs != nil {
			log.Fatalf("Could not archive applications: %s", errs)
		}

		if resp.StatusCode != 202 {
			log.Fatalf("Could not archive applications: %s", resp.Status)
		}

		fmt.Printf("Application %s accepted for archival\n", *uuid)
	}
}
예제 #9
0
파일: server.go 프로젝트: tayzlor/traefik
func (server *Server) prepareServer(router *mux.Router, entryPoint *EntryPoint, oldServer *manners.GracefulServer, middlewares ...negroni.Handler) (*manners.GracefulServer, error) {
	log.Info("Preparing server")
	// middlewares
	var negroni = negroni.New()
	for _, middleware := range middlewares {
		negroni.Use(middleware)
	}
	negroni.UseHandler(router)
	tlsConfig, err := server.createTLSConfig(entryPoint.TLS)
	if err != nil {
		log.Fatalf("Error creating TLS config %s", err)
		return nil, err
	}

	if oldServer == nil {
		return manners.NewWithServer(
			&http.Server{
				Addr:      entryPoint.Address,
				Handler:   negroni,
				TLSConfig: tlsConfig,
			}), nil
	}
	gracefulServer, err := oldServer.HijackListener(&http.Server{
		Addr:      entryPoint.Address,
		Handler:   negroni,
		TLSConfig: tlsConfig,
	}, tlsConfig)
	if err != nil {
		log.Fatalf("Error hijacking server %s", err)
		return nil, err
	}
	return gracefulServer, nil
}
예제 #10
0
파일: main.go 프로젝트: moul/converter
func Action(c *cli.Context) {
	args := append([]string{c.Command.Name}, c.Args()...)
	if len(args) == 0 {
		logrus.Fatalf("You need to use at least one filter")
	}

	chain, err := NewConverterChain(args)
	if err != nil {
		logrus.Fatalf("Failed to create a converter: %v", err)
	}

	input, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		logrus.Fatalf("Failed to read from stdin: %v", err)
	}

	conversionFunc, err := chain.ConversionFunc("[]byte", "interface{}")
	if err != nil {
		logrus.Fatalf("Failed to generate a conversion func: %v", err)
	}

	var output interface{}
	if err = conversionFunc(input, &output); err != nil {
		logrus.Fatalf("Failed to convert: %v", err)
	}

	fmt.Printf("%v\n", output)
}
예제 #11
0
//Show an Application.
func Show(cmd *cli.Cmd) {
	uuid := cmd.String(cli.StringArg{
		Name:      "UUID",
		Desc:      "Application UUID",
		HideValue: true,
	})

	cmd.Action = func() {
		app := application.Application{
			UUID: *uuid,
		}

		application, resp, errs := app.Show()

		if errs != nil {
			log.Fatalf("Could not retrieve application: %s", errs)
		}

		if resp.StatusCode != 200 {
			log.Fatalf("Could not retrieve application: %s", resp.Status)
		}

		printAppDetail(application)
	}
}
예제 #12
0
// Run initializes the driver
func Run(ctx *cli.Context) {

	gitRepoURL := fmt.Sprint(pluginPath, ctx.String("repo"))
	if gitRepoURL == "" {
		log.Fatalf("Exiting: A git URL is required to be used as a shared datastore for the endpoints")
	}
	log.Debugf("The plugin repo is [ %s ]", gitRepoURL)

	gitPollInterval := ctx.Int("poll-interval")
	if gitPollInterval == 0 {
		gitPollInterval = control.DefaultInterval
	}
	log.Debugf("The git polling interval is [ %d ]", gitPollInterval)

	var d ipvlan.Driver
	var err error
	if d, err = ipvlan.New(version, ctx); err != nil {
		log.Fatalf("unable to create driver: %s", err)
	}
	// concatenate the absolute path to the spec file handle
	absSocket := fmt.Sprint(pluginPath, ctx.String("socket"))
	log.Info("IPVlan network driver initialized successfully")
	log.Debugf("The plugin absolute path and handle is [ %s ]", absSocket)
	if err := d.Listen(absSocket); err != nil {
		log.Fatal(err)
	}
}
예제 #13
0
// Register netplugin with service registry
func registerService(objdbClient objdb.ObjdbApi, opts cliOpts) error {
	// Get the address to be used for local communication
	localIP, err := objdbClient.GetLocalAddr()
	if err != nil {
		log.Fatalf("Error getting locla IP address. Err: %v", err)
		return err
	}

	// service info
	srvInfo := objdb.ServiceInfo{
		ServiceName: "netplugin",
		HostAddr:    localIP,
		Port:        ofnet.OFNET_AGENT_PORT,
	}

	// Register the node with service registry
	err = objdbClient.RegisterService(srvInfo)
	if err != nil {
		log.Fatalf("Error registering service. Err: %v", err)
		return err
	}

	log.Infof("Registered netplugin service with registry")
	return nil
}
예제 #14
0
func configureSyslog(syslogParam string) {
	var err error
	var hook log.Hook

	// disable colors if we're writing to syslog *and* we're the default text
	// formatter, because the tty detection is useless here.
	if tf, ok := log.StandardLogger().Formatter.(*log.TextFormatter); ok {
		tf.DisableColors = true
	}

	if syslogParam == "kernel" {
		hook, err = logrus_syslog.NewSyslogHook("", "", syslog.LOG_INFO, "netplugin")
		if err != nil {
			log.Fatalf("Could not connect to kernel syslog")
		}
	} else {
		u, err := url.Parse(syslogParam)
		if err != nil {
			log.Fatalf("Could not parse syslog spec: %v", err)
		}

		hook, err = logrus_syslog.NewSyslogHook(u.Scheme, u.Host, syslog.LOG_INFO, "netplugin")
		if err != nil {
			log.Fatalf("Could not connect to syslog: %v", err)
		}
	}

	log.AddHook(hook)
}
예제 #15
0
func pluginInstall(c *cli.Context) {
	// Input validation
	pluginSource := c.String("source")
	if pluginSource == "" {
		log.Fatalln("Missing required input: source")
	}

	pluginName := c.String("name")
	if pluginName == "" {
		log.Fatalf("Missing required input: name")
	}

	pluginType := c.String("type")
	if pluginType == "" {
		pluginType = plugins.TypeGeneric
	}

	// Install
	log.Infof("=> Installing plugin (%s)...", plugins.PrintableName(pluginName, pluginType))
	printableName, err := plugins.InstallPlugin(c.App.Version, pluginSource, pluginName, pluginType)
	if err != nil {
		log.Fatalf("Failed to install plugin, err: %s", err)
	}
	fmt.Println()
	log.Infoln(colorstring.Greenf("Plugin (%s) installed", printableName))
}
예제 #16
0
func spawnGlobalDaemon() {
	if globalDaemon != nil {
		log.Debugf("Global daemon already exists. Skipping.")
		return
	}
	t := std_log.New(os.Stderr, "", 0)
	eng := NewTestEngine(t)
	globalEngine = eng
	globalDaemon = mkDaemonFromEngine(eng, t)

	// Spawn a Daemon
	go func() {
		log.Debugf("Spawning global daemon for integration tests")
		listenURL := &url.URL{
			Scheme: testDaemonProto,
			Host:   testDaemonAddr,
		}
		job := eng.Job("serveapi", listenURL.String())
		job.SetenvBool("Logging", true)
		if err := job.Run(); err != nil {
			log.Fatalf("Unable to spawn the test daemon: %s", err)
		}
	}()

	// Give some time to ListenAndServer to actually start
	// FIXME: use inmem transports instead of tcp
	time.Sleep(time.Second)

	if err := eng.Job("acceptconnections").Run(); err != nil {
		log.Fatalf("Unable to accept connections for test api: %s", err)
	}
}
예제 #17
0
//ResetPassword requests the password reset operation to start.
func ResetPassword(cmd *cli.Cmd) {
	email := cmd.String(cli.StringArg{
		Name:      "EMAIL",
		Desc:      "email address",
		HideValue: true,
	})

	cmd.Action = func() {
		a := authorization.Account{
			Email: *email,
		}

		account, resp, errs := a.ResetPassword()

		if len(errs) > 0 {
			log.Fatalf("Could not retrieve account: %s", errs[0])
		}

		if resp.StatusCode != 204 {
			log.Fatalf("Could not reset account password: %s", resp.Status)
		}

		fmt.Println("Password reset instructions sent to:", account.Email)
	}
}
예제 #18
0
파일: app.go 프로젝트: aduermael/libcompose
func ProjectPort(p *project.Project, c *cli.Context) {
	if len(c.Args()) != 2 {
		logrus.Fatalf("Please pass arguments in the form: SERVICE PORT")
	}

	index := c.Int("index")
	protocol := c.String("protocol")

	service, err := p.CreateService(c.Args()[0])
	if err != nil {
		logrus.Fatal(err)
	}

	containers, err := service.Containers()
	if err != nil {
		logrus.Fatal(err)
	}

	if index < 1 || index > len(containers) {
		logrus.Fatalf("Invalid index %d", index)
	}

	output, err := containers[index-1].Port(fmt.Sprintf("%s/%s", c.Args()[1], protocol))
	if err != nil {
		logrus.Fatal(err)
	}
	fmt.Println(output)
}
예제 #19
0
// Remove a vlan
func (self *Vxlan) RemoveVlan(vlanId uint16, vni uint32) error {
	vlan := self.vlanDb[vlanId]
	if vlan == nil {
		log.Fatalf("Could not find the vlan %d", vlanId)
	}

	// Make sure the flood lists are empty
	if (vlan.allFlood.NumOutput() != 0) || (vlan.localFlood.NumOutput() != 0) {
		log.Fatalf("VLAN flood list is not empty")
	}

	// make sure there are no mac routes still installed in this vlan
	for _, macRoute := range self.macRouteDb {
		if macRoute.Vni == vni {
			log.Fatalf("Vlan %d still has routes. Route: %+v", vlanId, macRoute)
		}
	}

	// Uninstall the flood lists
	vlan.allFlood.Delete()
	vlan.localFlood.Delete()

	// Remove it from DB
	delete(self.vlanDb, vlanId)

	return nil
}
예제 #20
0
func Show(cmd *cli.Cmd) {
	applicationUuid := cmd.String(cli.StringArg{
		Name:      "APPLICATION_UUID",
		Desc:      "Application UUID",
		HideValue: true,
	})

	uuid := cmd.String(cli.StringArg{
		Name:      "DEPLOYMENT_UUID",
		Desc:      "Deployment UUID",
		HideValue: true,
	})
	cmd.Action = func() {
		d := deployments.Deployment{}
		deployment, resp, errs := d.Show(*applicationUuid, *uuid)

		if len(errs) > 0 {
			log.Fatalf("Could not retrieve deployment: %s", errs[0])
		}

		if resp.StatusCode != 200 {
			log.Fatalf("Could not retrieve deployment: %s", resp.Status)
		}

		printDeploymentDetail(*deployment)
	}
}
예제 #21
0
func (b *Bridge) setupBridge(externalPort string) error {

	la := netlink.NewLinkAttrs()
	la.Name = b.bridgeName
	bridge, _ := netlink.LinkByName(b.bridgeName)

	if bridge == nil {
		log.Debugf("Bridge %s does not exist ", b.bridgeName)
		out, err := exec.Command("ovs-vsctl", "add-br", b.bridgeName).CombinedOutput()
		if err != nil {
			log.Fatalf("Bridge %s creation failed been created.  Resp: %s, err: %s", b.bridgeName, out, err)
		}
		log.Infof("Bridge %s has been created.  Resp: %s", b.bridgeName, out)

		out, err = exec.Command("ovs-vsctl", "add-port", b.bridgeName, externalPort).CombinedOutput()
		if err != nil {
			log.Fatalf("Failed to add external port %s.  Resp: %s, err: %s", externalPort, out, err)
		}
		log.Infof("External port %s has been added to %s. Resp: %s", externalPort, b.bridgeName, out)

		out, err = exec.Command("ifconfig", externalPort, "0.0.0.0").CombinedOutput()
		if err != nil {
			log.Fatalf("Failed to ip address of port %s. Resp: %s, err: %s", externalPort, out, err)
		}
		log.Infof("Ip address of port  %s has been cleaned. Resp: %s", externalPort, out)

		return err
	} else {
		log.Debugf("Bridge %s already exsist", b.bridgeName)
	}

	return nil
}
예제 #22
0
func Show(cmd *cli.Cmd) {
	uuid := cmd.String(cli.StringArg{
		Name:      "UUID",
		Desc:      "Application UUID",
		HideValue: true,
	})

	var a App

	cmd.Action = func() {
		resp, body, errs := application.Show(*uuid)

		if errs != nil {
			log.Fatalf("Could not retrieve application: %s", errs)
		}

		if resp.StatusCode != 200 {
			log.Fatalf("Could not retrieve application: %s", resp.Status)
		}

		err := json.Unmarshal([]byte(body), &a)

		if err != nil {
			log.Fatal(err)
		}

		printAppDetail(a)
	}
}
예제 #23
0
// InitApp initializes the application given a config and connects to backends.
// It also seeds any needed information to the database.
func InitApp(Config *Configuration) *App {
	// Connect to MongoDB
	session, err := mgo.Dial(Config.MongoURL + ":" + Config.MongoPort)
	if err != nil {
		log.Fatalf("mongoDB connection failed: %v", err)
	}
	// Create Shuttles object to store database session and collections
	app := App{
		session,
		session.DB("shuttle_tracking").C("updates"),
		session.DB("shuttle_tracking").C("vehicles"),
		session.DB("shuttle_tracking").C("routes"),
		session.DB("shuttle_tracking").C("stops"),
	}

	// Ensure unique vehicle identification
	vehicleIndex := mgo.Index{
		Key:      []string{"vehicleID"},
		Unique:   true,
		DropDups: true}
	app.Vehicles.EnsureIndex(vehicleIndex)

	// Read vehicle configuration file
	serr := readSeedConfiguration("seed/vehicle_seed.json", &app)
	if serr != nil {
		log.Fatalf("error reading vehicle configuration file: %v", serr)
	}

	return &app
}
예제 #24
0
func List(cmd *cli.Cmd) {
	var a []App

	all := cmd.BoolOpt("a all", false, "List all applications, including archived")

	cmd.Action = func() {
		resp, body, errs := application.List()

		if errs != nil {
			log.Fatalf("Could not retrieve applications: %s", errs)
		}

		if resp.StatusCode != 200 {
			log.Fatalf("Could not retrieve applications: %s", resp.Status)
		}

		err := json.Unmarshal([]byte(body), &a)

		if err != nil {
			log.Fatal(err)
		}

		printAppBrief(a, *all)
	}
}
예제 #25
0
func (d *daemon) execOpts() {
	if err := d.parseOpts(); err != nil {
		log.Fatalf("Failed to parse cli options. Error: %s", err)
	}

	if d.opts.help {
		fmt.Fprintf(os.Stderr, "Usage: %s [OPTION]...\n", os.Args[0])
		flagSet.PrintDefaults()
		os.Exit(0)
	}

	if d.opts.debug {
		log.SetLevel(log.DebugLevel)
	}

	sd, err := initStateDriver(&d.opts)
	if err != nil {
		log.Fatalf("Failed to init state-store. Error: %s", err)
	}

	if _, err = resources.NewStateResourceManager(sd); err != nil {
		log.Fatalf("Failed to init resource manager. Error: %s", err)
	}

	// Register netmaster service
	d.registerService()

	// initialize policy manager
	master.InitPolicyMgr()
}
예제 #26
0
func Action(c *cli.Context) {
	if len(c.Args()) != 1 {
		logrus.Fatalf("usage: gotty-client [GoTTY URL]")
	}

	// setting up logrus
	logrus.SetOutput(os.Stderr)
	if c.Bool("debug") {
		logrus.SetLevel(logrus.DebugLevel)
	} else {
		logrus.SetLevel(logrus.InfoLevel)
	}

	// create Client
	url := c.Args()[0]
	client, err := gottyclient.NewClient(url)
	if err != nil {
		logrus.Fatalf("Cannot create client: %v", err)
	}

	if c.Bool("skip-tls-verify") {
		client.SkipTLSVerify = true
	}

	// loop
	if err = client.Loop(); err != nil {
		logrus.Fatalf("Communication error: %v", err)
	}
}
예제 #27
0
func destroy(c *cli.Context) {
	log.Infoln("Destroy")

	additionalEnvs, err := config.CreateEnvItemsModelFromSlice(MachineParamsAdditionalEnvs.Get())
	if err != nil {
		log.Fatalf("Invalid Environment parameter: %s", err)
	}

	configModel, err := config.ReadMachineConfigFileFromDir(MachineWorkdir.Get(), additionalEnvs)
	if err != nil {
		log.Fatalln("Failed to read Config file: ", err)
	}

	isOK, err := pathutil.IsPathExists(path.Join(MachineWorkdir.Get(), "Vagrantfile"))
	if err != nil {
		log.Fatalln("Failed to check 'Vagrantfile' in the WorkDir: ", err)
	}
	if !isOK {
		log.Fatalln("Vagrantfile not found in the WorkDir!")
	}

	log.Infof("configModel: %#v", configModel)

	if err := doCleanup(configModel, "will-be-destroyed"); err != nil {
		log.Fatalf("Failed to Cleanup: %s", err)
	}

	if err := doDestroy(configModel); err != nil {
		log.Fatalf("Failed to Destroy: %s", err)
	}

	log.Infoln("=> Destroy DONE - OK")
}
예제 #28
0
func Create(cmd *cli.Cmd) {
	value := cmd.String(cli.StringArg{
		Name:      "VALUE",
		Desc:      "Value to be stored as secret",
		HideValue: true,
	})

	labels := cmd.Strings(cli.StringsOpt{
		Name:      "l label",
		Desc:      "Label to attach to Secret. This option may be included more than once.",
		HideValue: true,
	})

	cmd.Action = func() {
		s := secrets.Secret{
			Value:  *value,
			Labels: *labels,
		}

		secret, resp, errs := s.Create()

		if len(errs) > 0 {
			log.Fatalf("Could not create secret: %s", errs[0])
		}

		if resp.StatusCode != 201 {
			log.Fatalf("Could not create secret: %s", resp.Status)
		}

		printSecretDetail(secret)
	}
}
예제 #29
0
func prepareServer(router *mux.Router, globalConfiguration *GlobalConfiguration, oldServer *manners.GracefulServer, middlewares ...negroni.Handler) (*manners.GracefulServer, error) {
	log.Info("Preparing server")
	// middlewares
	var negroni = negroni.New()
	for _, middleware := range middlewares {
		negroni.Use(middleware)
	}
	negroni.UseHandler(router)
	tlsConfig, err := createTLSConfig(globalConfiguration.Certificates)
	if err != nil {
		log.Fatalf("Error creating TLS config %s", err)
		return nil, err
	}

	if oldServer == nil {
		return manners.NewWithServer(
			&http.Server{
				Addr:      globalConfiguration.Port,
				Handler:   negroni,
				TLSConfig: tlsConfig,
			}), nil
	}
	server, err := oldServer.HijackListener(&http.Server{
		Addr:      globalConfiguration.Port,
		Handler:   negroni,
		TLSConfig: tlsConfig,
	}, tlsConfig)
	if err != nil {
		log.Fatalf("Error hijacking server %s", err)
		return nil, err
	}
	return server, nil
}
예제 #30
0
// setupTestServer creates a listener for the rest requests.
func setupTestServer(m *testing.M) {

	// Read client cert
	cert, err := tls.LoadX509KeyPair("/tmp/certs/server.crt", "/tmp/certs/server.key")
	if err != nil {
		log.Fatalf("%v", err)
		return
	}

	// Read CA cert
	ca, err := ioutil.ReadFile("/tmp/certs/ca.crt")
	if err != nil {
		log.Errorf("%v", err)
		return
	}

	caPool := x509.NewCertPool()
	caPool.AppendCertsFromPEM(ca)

	// Setup HTTPS server
	tlsCfg := &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      caPool,
	}
	tlsCfg.BuildNameToCertificate()
	router := mux.NewRouter()

	// register handlers
	t := router.Headers().Methods("GET").Subrouter()
	t.HandleFunc(testPodURL, restWrapper(testPodGet))
	t.HandleFunc(svcWatchURL, restWrapper(serviceWatch))
	t.HandleFunc(epWatchURL, restWrapper(epWatch))

	server := &http.Server{Addr: testServerURL, Handler: router, TLSConfig: tlsCfg}

	go func() {
		err := server.ListenAndServeTLS("", "")
		if err != nil {
			log.Fatalf("server returned %v", err)
		}
	}()

	// make sure the listener is ready before returning
	for count := 0; count < 5; count++ {
		stat, err := osexec.Command("netstat", "-tlpn").CombinedOutput()
		if err != nil {
			log.Fatalf("Unable to check server status: %v", err)
			return
		}

		if strings.Contains(string(stat), ":443") {
			return
		}

		time.Sleep(time.Second)
		log.Infof("stat : %s", stat)
	}

	log.Fatalf("Kube server not ready after 5 sec")
}