Beispiel #1
0
func (cli *MongoClient) SaveTweet(tweets []anaconda.Tweet) {
	session, err := mgo.Dial(config.MongoDBServerHost)
	if err != nil {
		logrus.Errorln(err)
	}
	defer session.Close()
	db := session.DB("oreppoid")
	col := db.C("tweet")

	for _, tweet := range tweets {
		logrus.Infoln("saving...", tweet.Text)
		insertTweet := Tweet{
			Text:      tweet.Text,
			Name:      tweet.User.Name,
			UserId:    tweet.User.IdStr,
			CreatedAt: tweet.CreatedAt,
		}
		err := col.Insert(insertTweet)
		if err != nil {
			logrus.Fatalln(err)
		}
	}

	logrus.Infoln("tweets are saved in mongo")

}
Beispiel #2
0
// Setup download selected version to target dir and unpacks it
func (v *Version) Setup(rootDir string) error {
	sdkRoot := filepath.Join(rootDir, v.Release)
	os.MkdirAll(sdkRoot, 0755)
	targetFile := filepath.Join(rootDir, v.name)

	if _, err := os.Stat(targetFile); os.IsNotExist(err) {
		resp, err := req.Get(
			v.remoteURL,
			&req.RequestOptions{
				UserAgent: "Mozilla/5.0 (compatible; Gobu; +https://github.com/dz0ny/gobu)",
			},
		)
		if err != nil {
			return err
		}

		log.Infoln("Starting download of ", v.String())
		err = resp.DownloadToFile(targetFile)
		if err != nil {
			return err
		}
		log.Infoln("Starting extraction of ", targetFile)
		if strings.HasSuffix(v.name, ".zip") {
			return archive.Unzip(targetFile, sdkRoot)
		}
		if strings.HasSuffix(v.name, ".tar.gz") {
			return archive.Untar(targetFile, sdkRoot)
		}
		return errors.New("Unsuported archive type")

	}
	return nil
}
func (p *AuthService) AuthOperation(operations []string, tokenid string, objectId string, collectionName string) (map[string]int, error) {
	logrus.Infoln("begin to list authorized operations")
	token, err := GetTokenById(tokenid)
	if err != nil {
		logrus.Errorln("get token error:", err)
		return nil, errors.New("get token error!")
	}

	data := p.getObjectById(objectId, collectionName)

	authParam := &AuthParam{
		auth_instanceId:     "",
		auth_token:          token,
		auth_collectionName: ""}

	result := make(map[string]int)

	for i := 0; i < len(operations); i++ {
		op := operations[i]
		policyValue, exist := AUTHDATA[op]
		if !exist {
			logrus.Infoln("no auth policy for specific operation, operation:", op)
			result[op] = 1
			continue
		}

		if p.check(policyValue, authParam, data) {
			result[op] = 1
		} else {
			result[op] = 0
		}
	}

	return result, nil
}
Beispiel #4
0
func startFrontends(httpConfig httpfrontend.Config, udpConfig udpfrontend.Config, logic *middleware.Logic, errChan chan<- error) (httpFrontend *httpfrontend.Frontend, udpFrontend *udpfrontend.Frontend) {
	if httpConfig.Addr != "" {
		httpFrontend = httpfrontend.NewFrontend(logic, httpConfig)

		go func() {
			log.Infoln("started serving HTTP on", httpConfig.Addr)
			if err := httpFrontend.ListenAndServe(); err != nil {
				errChan <- errors.New("failed to cleanly shutdown HTTP frontend: " + err.Error())
			}
		}()
	}

	if udpConfig.Addr != "" {
		udpFrontend = udpfrontend.NewFrontend(logic, udpConfig)

		go func() {
			log.Infoln("started serving UDP on", udpConfig.Addr)
			if err := udpFrontend.ListenAndServe(); err != nil {
				errChan <- errors.New("failed to cleanly shutdown UDP frontend: " + err.Error())
			}
		}()
	}

	return
}
//return a query language by authenticate
//this will be used for listAll, list and deleteAll interface
func (p *AuthService) BuildQueryByAuth(operation string, tokenId string) (query bson.M, err error) {
	logrus.Infoln("build query object by auth")

	token, err := GetTokenService().GetTokenById(tokenId)
	if err != nil {
		logrus.Errorln("get token error:", err)
		return nil, errors.New("get token by id error!")
	}

	authParam := &AuthParam{auth_token: token}

	policyValue, exist := p.authdata[operation]
	if !exist {
		logrus.Infoln("no auth policy for specific operation, operation:", operation)
		query = bson.M{}
		return
	}

	switch checkType := policyValue.(type) {
	case entity.OrCheck:
		orresult, orsuccess := p.orCheck_query(checkType.Basechecks, checkType.Andchecks, checkType.Orchecks, authParam)
		if !orsuccess {
			logrus.Warnln("build auth query error")
			return nil, errors.New("build auth query error")
		}
		query, err = format(orresult)
		if err != nil {
			logrus.Warnln("format query result to bson error %v", err)
			return nil, err
		}
		return
	case entity.AndCheck:
		andresult, andsuccess := p.andCheck_query(checkType.Basechecks, checkType.Andchecks, checkType.Orchecks, authParam)
		if !andsuccess {
			logrus.Warnln("build auth query error")
			return nil, errors.New("build auth query error")
		}
		query, err = format(andresult)
		if err != nil {
			logrus.Warnln("format query result to bson error %v", err)
			return nil, err
		}
		return
	case entity.BaseCheck:
		baseresult, basesuccess := p.baseCheck_query(checkType.Checktype, checkType.Value, authParam)
		if !basesuccess {
			logrus.Warnln("build auth query error")
			return nil, errors.New("build auth query error")
		}
		query, err = format(baseresult)
		if err != nil {
			logrus.Warnln("format query result to bson error %v", err)
			return nil, err
		}
		return
	default:
		logrus.Errorln("unkonwn check type:", checkType)
		return nil, errors.New("unknown check type")
	}
}
Beispiel #6
0
func main() {
	log.SetLevel(log.DebugLevel)
	log.Infoln("*******************************************")
	log.Infoln("Port Scanner")
	log.Infoln("*******************************************")

	t := time.Now()
	defer func() {
		if e := recover(); e != nil {
			log.Debugln(e)
		}
	}()

	log.Debugln(loadConfig("config.properties"))

	log.Debugln("Parsed input data ", len(portScannerTuple.portScannerResult))
	CheckPort(&portScannerTuple)

	for key, value := range portScannerTuple.portScannerResult {
		if value {
			log.Debugln("Port Scanner Result", key, " port is open :", value)
		}
	}

	log.Debugln("Total time taken %s to scan %d ports", time.Since(t), len(portScannerTuple.portScannerResult))
}
// Builds and populates a Switch struct then starts listening
// for OpenFlow messages on conn.
func NewSwitch(stream *util.MessageStream, dpid net.HardwareAddr, app AppInterface) *OFSwitch {
	var s *OFSwitch

	if switchDb[dpid.String()] == nil {
		log.Infoln("Openflow Connection for new switch:", dpid)

		s = new(OFSwitch)
		s.app = app
		s.stream = stream
		s.dpid = dpid

		// Initialize the fgraph elements
		s.initFgraph()

		// Save it
		switchDb[dpid.String()] = s

		// Main receive loop for the switch
		go s.receive()

	} else {
		log.Infoln("Openflow Connection for switch:", dpid)

		s = switchDb[dpid.String()]
		s.stream = stream
		s.dpid = dpid
	}

	// send Switch connected callback
	s.switchConnected()

	// Return the new switch
	return s
}
Beispiel #8
0
// OnDisconnect event. Terminates MumbleDJ process or retries connection if
// automatic connection retries are enabled.
func (dj *MumbleDJ) OnDisconnect(e *gumble.DisconnectEvent) {
	dj.Queue.Reset()
	if viper.GetBool("connection.retry_enabled") &&
		(e.Type == gumble.DisconnectError || e.Type == gumble.DisconnectKicked) {
		logrus.WithFields(logrus.Fields{
			"interval_secs": fmt.Sprintf("%d", viper.GetInt("connection.retry_interval")),
			"attempts":      fmt.Sprintf("%d", viper.GetInt("connection.retry_attempts")),
		}).Warnln("Disconnected from server. Retrying connection...")

		success := false
		for retries := 0; retries < viper.GetInt("connection.retry_attempts"); retries++ {
			logrus.Infoln("Retrying connection...")
			if client, err := gumble.DialWithDialer(new(net.Dialer), viper.GetString("connection.address")+":"+viper.GetString("connection.port"), dj.GumbleConfig, dj.TLSConfig); err == nil {
				dj.Client = client
				logrus.Infoln("Successfully reconnected to the server!")
				success = true
				break
			}
			time.Sleep(time.Duration(viper.GetInt("connection.retry_interval")) * time.Second)
		}
		if !success {
			dj.KeepAlive <- true
			logrus.Fatalln("Could not reconnect to server. Exiting...")
		}
	} else {
		dj.KeepAlive <- true
		logrus.Fatalln("Disconnected from server. No reconnect attempts will be made.")
	}
}
Beispiel #9
0
func doSetupOnOSX(isMinimalSetupMode bool) error {
	log.Infoln("Doing OS X specific setup")
	log.Infoln("Checking required tools...")
	if err := CheckIsHomebrewInstalled(isMinimalSetupMode); err != nil {
		return errors.New(fmt.Sprint("Homebrew not installed or has some issues. Please fix these before calling setup again. Err:", err))
	}

	if err := PrintInstalledXcodeInfos(); err != nil {
		return errors.New(fmt.Sprint("Failed to detect installed Xcode and Xcode Command Line Tools infos. Err:", err))
	}
	// if err := CheckIsXcodeCLTInstalled(); err != nil {
	// 	return errors.New(fmt.Sprint("Xcode Command Line Tools not installed. Err:", err))
	// }
	// if err := checkIsAnsibleInstalled(); err != nil {
	// 	return errors.New("Ansible failed to install")
	// }

	if err := CheckIsEnvmanInstalled(minEnvmanVersion); err != nil {
		return errors.New(fmt.Sprint("Envman failed to install:", err))
	}
	if err := CheckIsStepmanInstalled(minStepmanVersion); err != nil {
		return errors.New(fmt.Sprint("Stepman failed to install:", err))
	}
	log.Infoln("All the required tools are installed!")

	return nil
}
Beispiel #10
0
func doSetupToolkits() error {
	log.Infoln("Checking Bitrise Toolkits...")

	coreToolkits := toolkits.AllSupportedToolkits()

	for _, aCoreTK := range coreToolkits {
		toolkitName := aCoreTK.ToolkitName()
		isInstallRequired, checkResult, err := aCoreTK.Check()
		if err != nil {
			return fmt.Errorf("Failed to perform toolkit check (%s), error: %s", toolkitName, err)
		}

		if isInstallRequired {
			log.Infoln("No installed/suitable '" + toolkitName + "' found, installing toolkit ...")
			if err := aCoreTK.Install(); err != nil {
				return fmt.Errorf("Failed to install toolkit (%s), error: %s", toolkitName, err)
			}

			isInstallRequired, checkResult, err = aCoreTK.Check()
			if err != nil {
				return fmt.Errorf("Failed to perform toolkit check (%s), error: %s", toolkitName, err)
			}
		}
		if isInstallRequired {
			return fmt.Errorf("Toolkit (%s) still reports that it isn't (properly) installed", toolkitName)
		}

		log.Infoln(" * "+colorstring.Green("[OK]")+" "+toolkitName+" :", checkResult.Path)
		log.Infoln("        version :", checkResult.Version)
	}

	return nil
}
Beispiel #11
0
func doStop(c *cli.Context, client *etcd.Client) {
	cmd := &command.Command{
		Id:      time.Now().Format("20060102030405"),
		Type:    "remove",
		Name:    c.String("id"),
		Service: c.String("service"),
		Backend: c.String("backend"),
		Cluster: c.String("cluster"),
		Proto:   c.String("proto"),
	}
	if cmd.Name == "" {
		cmd.Image = c.String("image")
		if cmd.Image == "" {
			log.Fatalln("image name or container id is required!")
		}
	}

	log.Infoln("generate a new command: ", cmd.Marshal())

	if c.Bool("local") {
		log.Infoln("just stop container on local host")
		if err := cmd.Process(dockerClient(c), etcdClient(c), c.String("host"), c.GlobalString("prefix")); err != nil {
			log.WithFields(log.Fields{
				"error": err.Error(),
			}).Fatalln("execute command failed.")
		}
		return
	}

	dispatchCommand(c, client, cmd)
}
Beispiel #12
0
func waitForWatcher(ctx context.Context, watcher *inotify.Watcher, match matcherFunc, tpl *template.Template, monitor bool) {
	defer watcher.Close()

	for {
		select {
		case <-ctx.Done(): // Timeout
			os.Exit(2)
			return

		case ev := <-watcher.Event:
			if !match(ev) {
				break
			}
			if tpl != nil {
				tpl.Execute(os.Stdout, ev)
				log.Infoln()
			} else {
				log.Infoln(ev)
			}
			// Finish if not monitoring mode.
			if !monitor {
				return
			}

		case err := <-watcher.Error:
			log.Fatal(err)
		}
	}
}
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")
}
Beispiel #14
0
// SaveToFile ...
func SaveToFile(pth string, bitriseConf models.BitriseConfigModel) error {
	if pth == "" {
		return errors.New("No path provided")
	}

	file, err := os.Create(pth)
	if err != nil {
		return err
	}
	defer func() {
		if err := file.Close(); err != nil {
			log.Fatalln("[BITRISE] - Failed to close file:", err)
		}
	}()

	contBytes, err := generateYAML(bitriseConf)
	if err != nil {
		return err
	}

	if _, err := file.Write(contBytes); err != nil {
		return err
	}
	log.Println()
	log.Infoln("=> Init success!")
	log.Infoln("File created at path:", pth)
	log.Infoln("With the content:")
	log.Infoln(string(contBytes))

	return nil
}
Beispiel #15
0
// RunSetup ...
func RunSetup(appVersion string, isMinimalSetupMode bool) error {
	log.Infoln("[BITRISE_CLI] - Setup")
	log.Infoln("Detected OS:", runtime.GOOS)
	switch runtime.GOOS {
	case "darwin":
		if err := doSetupOnOSX(isMinimalSetupMode); err != nil {
			return err
		}
	case "linux":
		if err := doSetupOnLinux(); err != nil {
			return err
		}
	default:
		return errors.New("Sorry, unsupported platform :(")
	}

	if err := SaveSetupSuccessForVersion(appVersion); err != nil {
		return fmt.Errorf("Failed to save setup-success into config file: %s", err)
	}

	// guide
	log.Infoln("We're ready to rock!!")
	fmt.Println()

	return nil
}
Beispiel #16
0
func checkIsAnsibleInstalled() error {
	progInstallPth, err := checkProgramInstalledPath("ansible")
	if err != nil {
		officialSiteURL := "http://www.ansible.com/home"
		officialGitHubURL := "https://github.com/ansible/ansible"
		log.Infoln("")
		log.Infoln("Ansible was not found.")
		log.Infoln("Ansible is used for system provisioning.")
		log.Infoln("You can find more information on Ansible's official website:", officialSiteURL)
		log.Infoln(" or on it's GitHub page:", officialGitHubURL)
		log.Infoln("You can install Ansible through brew:")
		log.Infoln("$ brew update && brew install ansible")
		isInstall, err := goinp.AskForBool("Would you like to install Ansible right now?")
		if err != nil {
			return err
		}
		if !isInstall {
			return errors.New("Ansible not found and install was not initiated.")
		}

		log.Infoln("$ brew update --verbose")
		if err := bitrise.RunCommand("brew", "update", "--verbose"); err != nil {
			return err
		}
		log.Infoln("$ brew install ansible")
		if err := bitrise.RunCommand("brew", "install", "ansible"); err != nil {
			return err
		}

		// just check again
		return checkIsAnsibleInstalled()
	}
	log.Infoln(" * [OK] Ansible :", progInstallPth)
	return nil
}
Beispiel #17
0
Datei: gow.go Projekt: zchee/_gow
func logEvent(events fsevents.Event) {
	// Split "file" flag separate "."
	// Detection file extension
	f := strings.Split(events.Path, ".")
	if StringInSlice(f[len(f)-1], strings.Split(*file, ",")) {
		note := ""
		for bit, description := range noteDescription {
			if events.Flags&bit == bit {
				note += description + " "
			}
		}

		log.Infoln("EventID:", events.ID)
		log.Infoln("Path:", events.Path)
		log.Infoln("Flags:", note)

		for _, events := range noteDescription {
			// switch event.Flags & eventType {
			switch true {

			case events == *event:
				go execCommand(*command)
			}
		}
	}
}
Beispiel #18
0
func printAboutUtilityWorkflows() {
	log.Error("Utility workflows can't be triggered directly")
	fmt.Println()
	log.Infoln("Note about utility workflows:")
	log.Infoln("Utility workflow names start with '_' (example: _my_utility_workflow),")
	log.Infoln(" these can't be triggered directly but can be used by other workflows")
	log.Infoln(" in the before_run and after_run blocks.")
}
Beispiel #19
0
func (sw Swarm) Initialize(servers []string) (err error) {

	var clusterContainers []*engine.Container
	var engines []docker.Docker

	// Ensure the cluster is in Store
	if err = sw.Store.Write("/cluster", "", ""); err != nil {
		return err
	}

	// Nodes
	for _, server := range servers {

		// Connect to Docker
		log.Infoln("Connecting to Docker on:", server)
		eng, err := docker.New(server, "")
		engines = append(engines, eng)
		if err != nil {
			return err
		}

		// Agent
		if _, err = sw.agent(server, eng); err != nil {
			return err
		}
	}

	// Manager
	var swarmManager *engine.Container
	for _, container := range clusterContainers {
		if container.Name == "swarm_manager" {
			swarmManager = container
			break
		}
	}
	if swarmManager == nil {
		i := utils.PickServer(servers)
		if swarmManager, err = sw.manager(servers[i], engines[i]); err != nil {
			return
		}
	}

	// Connect manager
	log.Infoln("Connecting to Swarm manager on:", "tcp://"+swarmManager.Addr())
	for i := 0; i < 3; i++ {
		// We have to wait swarm manager to init
		time.Sleep(200 * time.Millisecond)
		_, err = docker.New("tcp://"+swarmManager.Addr(), "")
		if err == nil {
			break
		}
	}
	if err != nil {
		return
	}
	return sw.Store.Write("manager", swarmManager.Addr(), "cluster/docker/swarm")
}
Beispiel #20
0
func checkIsBitriseToolInstalled(toolname, minVersion string, isInstall bool) error {
	doInstall := func() error {
		installCmdLines := []string{
			"curl -L https://github.com/bitrise-io/" + toolname + "/releases/download/" + minVersion + "/" + toolname + "-$(uname -s)-$(uname -m) > /usr/local/bin/" + toolname,
			"chmod +x /usr/local/bin/" + toolname,
		}
		officialGithub := "https://github.com/bitrise-io/" + toolname
		fmt.Println()
		log.Warnln("No supported " + toolname + " version found.")
		log.Infoln("You can find more information about "+toolname+" on it's official GitHub page:", officialGithub)
		fmt.Println()

		// Install
		log.Infoln("Installing...")
		fmt.Println(strings.Join(installCmdLines, "\n"))
		if err := bitrise.RunBashCommandLines(installCmdLines); err != nil {
			return err
		}

		// check again
		return checkIsBitriseToolInstalled(toolname, minVersion, false)
	}

	// check whether installed
	progInstallPth, err := CheckProgramInstalledPath(toolname)
	if err != nil {
		if !isInstall {
			return err
		}

		return doInstall()
	}
	verStr, err := bitrise.RunCommandAndReturnStdout(toolname, "-version")
	if err != nil {
		log.Infoln("")
		return errors.New("Failed to get version")
	}

	// version check
	isVersionOk, err := bitrise.IsVersionGreaterOrEqual(verStr, minVersion)
	if err != nil {
		log.Error("Failed to validate installed version")
		return err
	}
	if !isVersionOk {
		log.Warn("Installed "+toolname+" found, but not a supported version: ", verStr)
		if !isInstall {
			return errors.New("Failed to install required version.")
		}
		log.Warn("Updating...")
		return doInstall()
	}

	log.Infoln(" * "+colorstring.Green("[OK]")+" "+toolname+" :", progInstallPth)
	log.Infoln("        version :", verStr)
	return nil
}
Beispiel #21
0
func main() {
	//TODO os.Getenv("DOMAIN")
	configureSocial()
	// Load all configuration
	appCfg = &AppConfig{}
	mgoCfg := &MgoConfig{}
	natsCfg := &NatsConfig{}
	loadConfiguration(appCfg, mgoCfg, natsCfg)

	log.Infoln("Initializing NatsMailClient")
	initMail()
	var mailErr error
	mailClient, mailErr = client.NewNatsMailClient(natsCfg.Endpoint)
	if mailErr != nil {
		log.Errorf("Cannot initialize mail client: %s", mailErr.Error())
	}
	//Mongo configuration
	log.Infoln("Loading configuration of MongoDB")
	mgoStorage := auth.NewMgoStorage()
	mgoStorage.ConnectionString = mgoCfg.URI
	mgoStorage.Database = mgoCfg.DB
	err := mgoStorage.OpenSession()
	if err != nil {
		log.Panic(err)
	}
	log.Infoln("Initializing auth provider")
	mgoAuthProvider := auth.NewAuthProvider(mgoStorage)
	authProvider = mgoAuthProvider
	passManager = mgoAuthProvider

	log.Infoln("Initializing reverse proxy")

	log.Infoln("Registering handlers")
	//Handle login and register

	clientConn, _ := nats.Connect(natsCfg.Endpoint)
	defer clientConn.Close()
	mux, natsErr := natsproxy.NewNatsClient(clientConn)
	if natsErr != nil {
		log.Panic("Cannot initialize NATS client")
	}
	mux.GET("/activate/:activateToken", activateHandler)
	mux.POST("/login", loginHandler)
	mux.POST("/register", registerHandler)

	mux.POST("/requestpasswordreset", requestPasswordResetHandler)
	mux.POST("/resetpassword/:resettoken", passwordResetHandler)
	// mux.Get("/auth/{provider}/callback", handleSocialLogin)
	// mux.Get("/auth/{provider}", gothic.BeginAuthHandler)
	//else handle via proxy

	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	fmt.Println("Press Ctrl+C for exit.")
	<-sig
}
Beispiel #22
0
func checkIsStepmanInstalled() error {
	progInstallPth, err := checkProgramInstalledPath("stepman")
	if err != nil {
		log.Infoln("")
		log.Infoln("stepman was not found.")
		return errors.New("stepman was not found")
	}
	log.Infoln(" * [OK] stepman :", progInstallPth)
	return nil
}
Beispiel #23
0
//call dcos deployment module to create a cluster
func CreateCluster(cluster entity.Cluster, x_auth_token string) (err error) {
	var request dcosentity.Request
	request.UserName = cluster.Owner
	request.ClusterName = cluster.Name
	//	request.RequestId=
	request.ClusterNumber = cluster.Instances
	if cluster.Type == "mgmt" {
		request.IsLinkerMgmt = true
	}
	if cluster.Type == "user" {
		request.IsLinkerMgmt = false
	}

	request.ProviderInfo = getProvider(cluster.UserId, x_auth_token)

	clusterId := cluster.ObjectId.Hex()

	var servers *[]dcosentity.Server
	//send request to deployment module
	servers, err = SendCreateClusterRequest(request)
	if err != nil {
		logrus.Errorf("send request to dcos deploy error is %v", err)
		//update status of all hosts in the cluster FAILED
		updateHostStatusInCluster(clusterId, HOST_STATUS_FAILED, x_auth_token)
		//update cluster status FAILED
		logrus.Infoln("set cluster status to FAILED")
		GetClusterService().UpdateStatusById(clusterId, CLUSTER_STATUS_FAILED, x_auth_token)
		return
	}

	//loop servers and update hosts in database
	logrus.Infoln("update cluster host status wo RUNNING")
	err = updateHosts(clusterId, servers, x_auth_token)
	if err != nil {
		logrus.Errorf("update hosts error is %v", err)
		return
	}

	//update status RUNNING
	logrus.Infoln("set cluster status to RUNNING and endpoint")
	currentCluster, _, err := GetClusterService().QueryById(clusterId, x_auth_token)
	if err != nil {
		logrus.Errorf("get cluster by id [%v] error %v", clusterId, err)
		return err
	}

	currentCluster.Status = CLUSTER_STATUS_RUNNING
	currentCluster.Endpoint = buildEndPoint(servers, currentCluster.Name)

	GetClusterService().UpdateCluster(currentCluster, x_auth_token)

	// GetClusterService().UpdateStatusById(clusterId, CLUSTER_STATUS_RUNNING, x_auth_token)
	return
}
Beispiel #24
0
func printAvailableTriggerFilters(triggerMap []models.TriggerMapItemModel) {
	log.Infoln("The following trigger filters are available:")
	for _, triggerItem := range triggerMap {
		log.Infoln(" * " + triggerItem.Pattern)
	}

	fmt.Println()
	log.Infoln("You can trigger a workflow with:")
	log.Infoln("-> bitrise trigger the-trigger-filter")
	fmt.Println()
}
Beispiel #25
0
func (c *Command) Process(dockerClient *docker.Client, etcdClient *etcd.Client, hostIp, prefix string) error {
	// todo: check parameters...
	switch c.Type {
	case "add":
		container, err := c.runContainer(dockerClient)
		if err != nil {
			return err
		}

		if c.Service != "" {
			if err = c.registerInstance(etcdClient, container, hostIp, prefix); err != nil {
				return err
			}
		} else {
			log.Infoln("skip over instance register.")
		}

	case "remove":
		containers, err := c.findContainers(dockerClient)
		if err != nil {
			return err
		}

		return c.stopInstances(dockerClient, etcdClient, containers, prefix)

	case "update":
		container, err := c.runContainer(dockerClient)
		if err != nil {
			return err
		}

		if c.Service != "" {
			if err = c.registerInstance(etcdClient, container, hostIp, prefix); err != nil {
				return err
			}
		} else {
			log.Infoln("skip over instance register.")
		}

		containers, err := c.findReplacedContainers(dockerClient)
		if err != nil {
			return err
		}
		return c.stopInstances(dockerClient, etcdClient, containers, prefix)

	default:
		log.WithFields(log.Fields{
			"operation": c.Type,
		}).Errorln("unknown operation type.")
		return errors.New("unknown type")
	}
	return nil
}
Beispiel #26
0
func main() {
	//TODO os.Getenv("DOMAIN")
	configureSocial()
	// Load all configuration
	appCfg = &AppConfig{}
	rdisCfg := &RedisConfig{}
	natsCfg := &NatsConfig{}
	loadConfiguration(appCfg, rdisCfg, natsCfg)

	//Mongo configuration
	log.Infoln("Loading configuration of Redis")
	rdisStorage := storage.NewRedisStorage()
	rdisStorage.URL = rdisCfg.URI
	rdisStorage.Password = rdisCfg.Password
	rdisStorage.Database = rdisCfg.DB
	tokenStorage = rdisStorage
	err := tokenStorage.OpenSession()
	defer tokenStorage.CloseSession()
	if err != nil {
		log.Panic(err)
	}

	log.Infoln("Initializing NATS proxy")
	proxyConn, _ := nats.Connect(natsCfg.Endpoint)
	multiProxy, err := natsproxy.NewNatsProxy(proxyConn)
	multiProxy.AddHook("/login.*", loginHook)
	defer proxyConn.Close()
	if err != nil {
		log.Panic("Cannot initialize NATS proxy")
	}

	log.Infoln("Registering handlers")
	//Handle login and register
	mux := http.NewServeMux()
	log.Infoln("Start listening on " + appCfg.Port)
	mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		log.Println("Handling")
		transformToken(req)
		log.Println(req.Header)
		multiProxy.ServeHTTP(rw, req)
	})

	//Init HTTP2 server
	srv := &http.Server{
		Addr:    ":" + appCfg.Port,
		Handler: mux,
	}
	http2.ConfigureServer(srv, nil)
	serveErr := srv.ListenAndServe()
	if serveErr != nil {
		log.Errorln(serveErr)
	}
}
Beispiel #27
0
func (s *Server) Bootstrap() {
	log.Infoln("bootstrapping server")
	router := httprouter.New()
	s.router = router

	log.Infoln("loading routes")
	s.mapRoutes()
	log.Infoln("loading endpoints")
	s.DefineEndpoints()

	log.Infoln("serving")
	http.ListenAndServe(s.config.address, s.router)
}
Beispiel #28
0
func doSetup(c *cli.Context) {
	log.Infoln("[BITRISE_CLI] - Setup - Still work-in-progress")
	log.Infoln("Detected OS:", runtime.GOOS)
	switch runtime.GOOS {
	case "darwin":
		doSetupOnOSX()
	case "linux":
		doSetupOnLinux()
	default:
		log.Fatalln("Sorry, unsupported platform :(")
	}
	os.Exit(1)
}
Beispiel #29
0
func doSetupOnOSX(isMinimalSetupMode bool) error {
	log.Infoln("Doing OS X specific setup")
	log.Infoln("Checking required tools...")

	if err := CheckIsHomebrewInstalled(isMinimalSetupMode); err != nil {
		return errors.New(fmt.Sprint("Homebrew not installed or has some issues. Please fix these before calling setup again. Err:", err))
	}

	if err := PrintInstalledXcodeInfos(); err != nil {
		return errors.New(fmt.Sprint("Failed to detect installed Xcode and Xcode Command Line Tools infos. Err:", err))
	}
	return nil
}
Beispiel #30
0
func setup(c *cli.Context) {
	PrintBitriseHeaderASCIIArt(c.App.Version)

	if err := bitrise.RunSetup(c.App.Version, c.Bool(MinimalModeKey)); err != nil {
		log.Fatalln("Setup failed:", err)
	}

	log.Infoln("To start using bitrise:")
	log.Infoln("* cd into your project's directory (if you're not there already)")
	log.Infoln("* call: bitrise init")
	log.Infoln("* follow the guide")
	fmt.Println()
	log.Infoln("That's all :)")
}