func (p *platform) NewSpan(s *Span) *Span { if s == nil { // completeley new trace return &Span{ Id: uuid.NewUUID().String(), TraceId: uuid.NewUUID().String(), ParentId: "0", Timestamp: time.Now(), Source: p.opts.Service, } } // existing trace in theory cp := &Span{} *cp = *s if len(s.TraceId) == 0 { cp.TraceId = uuid.NewUUID().String() } if len(s.ParentId) == 0 { cp.ParentId = "0" } if len(s.Id) == 0 { cp.Id = uuid.NewUUID().String() } if s.Timestamp.IsZero() { cp.Timestamp = time.Now() } if s.Source == nil { cp.Source = p.opts.Service } return cp }
func NewUUID() string { uuidLock.Lock() defer uuidLock.Unlock() result := uuid.NewUUID() // The UUID package is naive and can generate identical UUIDs if the // time interval is quick enough. // The UUID uses 100 ns increments so it's short enough to actively // wait for a new value. for uuid.Equal(lastUUID, result) == true { result = uuid.NewUUID() } lastUUID = result return result.String() }
func NewRule(title string, src string, eps []string) *Rule { return &Rule{ Id: uuid.NewUUID().String(), Title: title, Script: src, Endpoints: eps} }
func BatchEnq(d []OpSend, ttl ...uint32) { if len(d) <= 0 { return } c := pool.Get() defer c.Close() for _, v := range d { if data, err := json.Marshal(v); err != nil { fmt.Println("err:", err) } else { k := fmt.Sprintf("mk%v", uuid.NewUUID()) if len(ttl) > 0 && ttl[0] > 0 { if err := c.Send("SETEX", k, ttl[0], data); err != nil { log.Println("[Batch Q SetEx] err :", err) } } else { if err := c.Send("SET", k, data); err != nil { log.Println("[Batch Q SET] err :", err) } } if err := c.Send("RPUSH", OPQ_SEND, k); err != nil { log.Println("[Batch Q RPUSH] err :", err) } } } c.Flush() }
func New(ctx api.Context, id string, pod *api.Pod, prototype *mesos.ExecutorInfo, allowedRoles []string) (*T, error) { if prototype == nil { return nil, fmt.Errorf("illegal argument: executor is nil") } if len(allowedRoles) == 0 { allowedRoles = defaultRoles } key, err := MakePodKey(ctx, pod.Name) if err != nil { return nil, err } if id == "" { id = "pod." + uuid.NewUUID().String() } task := &T{ ID: id, Pod: *pod, State: StatePending, podKey: key, mapper: NewHostPortMapper(pod), Flags: make(map[FlagType]struct{}), prototype: prototype, allowedRoles: allowedRoles, } task.CreateTime = time.Now() return task, nil }
// GenerateThumbnail assumes that the images have already been saved to storage, // and that one or more image is contained within imagesValue. Returns the // resulting filename of the generated thumbnail if successful, or an error // otherwise. func (imagesValue *ImagesValue) GenerateThumbnail() (string, error) { if !imagesValue.IsComplete() { return "", errors.New("No images to generate thumbnail for.") } filename := MediaDir + ThumbnailDir + uuid.NewUUID().String() + ThumbnailType mw := imagick.NewMagickWand() defer mw.Destroy() err := mw.ReadImage(fieldsConfig.Website.Directory + (*imagesValue)[0]) if err != nil { return "", err } err = mw.ThumbnailImage(ThumbnailMaxWidth, ThumbnailMaxHeight) if err != nil { return "", err } err = mw.SetImageCompressionQuality(ThumbnailQuality) if err != nil { return "", err } err = mw.WriteImage(fieldsConfig.Website.Directory + filename) if err != nil { return "", err } return filename, nil }
func newHttpBroker(opts ...Option) Broker { options := Options{ Context: context.TODO(), } for _, o := range opts { o(&options) } addr := ":0" if len(options.Addrs) > 0 && len(options.Addrs[0]) > 0 { addr = options.Addrs[0] } reg, ok := options.Context.Value(registryKey).(registry.Registry) if !ok { reg = registry.DefaultRegistry } h := &httpBroker{ id: "broker-" + uuid.NewUUID().String(), address: addr, opts: options, r: reg, c: &http.Client{Transport: newTransport(options.TLSConfig)}, subscribers: make(map[string][]*httpSubscriber), unsubscribe: make(chan *httpSubscriber), exit: make(chan chan error), mux: http.NewServeMux(), } h.mux.Handle(DefaultSubPath, h) return h }
func (h *httpBroker) Subscribe(topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) { opt := newSubscribeOptions(opts...) // parse address for host, port parts := strings.Split(h.Address(), ":") host := strings.Join(parts[:len(parts)-1], ":") port, _ := strconv.Atoi(parts[len(parts)-1]) addr, err := extractAddress(host) if err != nil { return nil, err } id := uuid.NewUUID().String() var secure bool if h.opts.Secure || h.opts.TLSConfig != nil { secure = true } // register service node := ®istry.Node{ Id: h.id + "." + id, Address: addr, Port: port, Metadata: map[string]string{ "secure": fmt.Sprintf("%t", secure), }, } version := opt.Queue if len(version) == 0 { version = broadcastVersion } service := ®istry.Service{ Name: "topic:" + topic, Version: version, Nodes: []*registry.Node{node}, } subscriber := &httpSubscriber{ opts: opt, id: h.id + "." + id, topic: topic, ch: h.unsubscribe, fn: handler, svc: service, } if err := h.r.Register(service, registry.RegisterTTL(registerTTL)); err != nil { return nil, err } h.Lock() h.subscribers[topic] = append(h.subscribers[topic], subscriber) h.Unlock() return subscriber, nil }
func main() { log.Println("hello") mg := connect("192.168.56.101/figoTest") cp := mg.Copy() defer cp.Close() apps := map[string]string{} apps["com.test.com"] = "特斯特" apps["com.cool.me"] = "酷儿" apps["com.mi.me"] = "米密" m := &MapTest{ Id: bson.NewObjectId(), Dvid: uuid.NewUUID().String(), Ct: time.Now(), Mt: utee.Tick(), Apps: apps, } cp.DB(DB).C(C).Insert(m) // func (p *Student) incTest(){ // if err := p.ds.DB(DB).C(C).UpdateId(p.Id, bson.M{"$inc":bson.M{"visitTimes":1}});err!=nil { // log.Println("@err:",err) // } // } }
func (driver *MesosSchedulerDriver) frameworkReregistered(from *upid.UPID, pbMsg proto.Message) { log.V(1).Infoln("Handling Scheduler re-registered event.") msg := pbMsg.(*mesos.FrameworkReregisteredMessage) if driver.status == mesos.Status_DRIVER_ABORTED { log.Infoln("Ignoring FrameworkReregisteredMessage from master, driver is aborted!") return } if driver.connected { log.Infoln("Ignoring FrameworkReregisteredMessage from master,driver is already connected!") return } if !driver.masterPid.Equal(from) { log.Warningf("ignoring framework re-registered message because it was sent from '%v' instead of leading master '%v'", from, driver.masterPid) return } // TODO(vv) detect if message was from leading-master (sched.cpp) log.Infof("Framework re-registered with ID [%s] ", msg.GetFrameworkId().GetValue()) driver.connected = true driver.failover = false driver.connection = uuid.NewUUID() driver.withScheduler(func(s Scheduler) { s.Reregistered(driver, msg.GetMasterInfo()) }) }
func (s *Account) Create(ctx context.Context, req *account.CreateRequest, rsp *account.CreateResponse) error { // validate incoming if err := validateAccount(req.Account, "Create"); err != nil { return err } // set a uuid if we dont have one if len(req.Account.Id) == 0 { req.Account.Id = uuid.NewUUID().String() } // hash the pass salt := db.Salt() h, err := bcrypt.GenerateFromPassword([]byte(x+salt+req.Account.ClientSecret), 10) if err != nil { return errors.InternalServerError("go.micro.srv.auth.Create", err.Error()) } pp := base64.StdEncoding.EncodeToString(h) // to lower req.Account.ClientId = strings.ToLower(req.Account.ClientId) req.Account.Type = strings.ToLower(req.Account.Type) if err := db.Create(req.Account, salt, pp); err != nil { return errors.InternalServerError("go.micro.srv.auth.Create", err.Error()) } return nil }
// run healthchecker func (s *Sidecar) run(exit chan bool) { parts := strings.Split(s.address, ":") host := strings.Join(parts[:len(parts)-1], ":") port, _ := strconv.Atoi(parts[len(parts)-1]) id := s.name + "-" + uuid.NewUUID().String() node := ®istry.Node{ Id: id, Address: host, Port: port, } service := ®istry.Service{ Name: s.name, Nodes: []*registry.Node{node}, } log.Printf("Registering %s", node.Id) (*cmd.DefaultOptions().Registry).Register(service) if len(s.hcUrl) == 0 { return } log.Print("Starting sidecar healthchecker") go s.hcLoop(service, exit) <-exit }
// SaveDataIntoES save metrics and events to ES by using ES client func SaveDataIntoES(esClient *elastic.Client, indexName string, typeName string, sinkData interface{}) error { if indexName == "" || typeName == "" || sinkData == nil { return nil } // Use the IndexExists service to check if a specified index exists. exists, err := esClient.IndexExists(indexName).Do() if err != nil { return err } if !exists { // Create a new index. createIndex, err := esClient.CreateIndex(indexName).BodyString(mapping).Do() if err != nil { return err } if !createIndex.Acknowledged { return fmt.Errorf("Failed to create Index in ES cluster: %s", err) } } indexID := uuid.NewUUID() _, err = esClient.Index(). Index(indexName). Type(typeName). Id(indexID.String()). BodyJson(sinkData). Do() if err != nil { return err } return nil }
// URL: /user_center/change_password // 修改密码 func changePasswordHandler(handler *Handler) { user, _ := currentUser(handler) form := wtforms.NewForm( wtforms.NewPasswordField("current_password", "当前密码", wtforms.Required{}), wtforms.NewPasswordField("new_password", "新密码", wtforms.Required{}), wtforms.NewPasswordField("confirm_password", "新密码确认", wtforms.Required{}), ) if handler.Request.Method == "POST" && form.Validate(handler.Request) { if form.Value("new_password") == form.Value("confirm_password") { if user.CheckPassword(form.Value("current_password")) { c := handler.DB.C(USERS) salt := strings.Replace(uuid.NewUUID().String(), "-", "", -1) c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{ "password": encryptPassword(form.Value("new_password"), salt), "salt": salt, }}) message(handler, "密码修改成功", `密码修改成功`, "success") return } else { form.AddError("current_password", "当前密码错误") } } else { form.AddError("confirm_password", "密码不匹配") } } handler.renderTemplate("user_center/change_password.html", BASE, map[string]interface{}{ "form": form, "active": "change_password", }) }
// Create creates a workflow from the given factory name with the // provided args. Returns the unique UUID of the workflow. The // workflowpb.Workflow object is saved in the topo server after // creation. func (m *Manager) Create(ctx context.Context, factoryName string, args []string) (string, error) { m.mu.Lock() defer m.mu.Unlock() // Find the factory. factory, ok := factories[factoryName] if !ok { return "", fmt.Errorf("no factory named %v is registered", factoryName) } // Create the initial workflowpb.Workflow object. w := &workflowpb.Workflow{ Uuid: gouuid.NewUUID().String(), FactoryName: factoryName, State: workflowpb.WorkflowState_NotStarted, } // Let the factory parse the parameters and initialize the // object. if err := factory.Init(w, args); err != nil { return "", err } // Now save the workflow in the topo server. _, err := m.ts.CreateWorkflow(ctx, w) if err != nil { return "", err } // And we're done. return w.Uuid, nil }
// ---------------------- Handlers for Events from Master --------------- // func (driver *MesosSchedulerDriver) frameworkRegistered(from *upid.UPID, pbMsg proto.Message) { log.V(2).Infoln("Handling scheduler driver framework registered event.") msg := pbMsg.(*mesos.FrameworkRegisteredMessage) masterInfo := msg.GetMasterInfo() masterPid := masterInfo.GetPid() frameworkId := msg.GetFrameworkId() if driver.status == mesos.Status_DRIVER_ABORTED { log.Infof("ignoring FrameworkRegisteredMessage from master %s, driver is aborted", masterPid) return } if driver.connected { log.Infoln("ignoring FrameworkRegisteredMessage from master, driver is already connected", masterPid) return } if driver.stopped() { log.Infof("ignoring FrameworkRegisteredMessage from master %s, driver is stopped", masterPid) return } if !driver.masterPid.Equal(from) { log.Warningf("ignoring framework registered message because it was sent from '%v' instead of leading master '%v'", from, driver.masterPid) return } log.Infof("Framework registered with ID=%s\n", frameworkId.GetValue()) driver.frameworkInfo.Id = frameworkId // generated by master. driver.connected = true driver.failover = false driver.connection = uuid.NewUUID() driver.withScheduler(func(s Scheduler) { s.Registered(driver, frameworkId, masterInfo) }) }
func (s *Sidecar) run() { parts := strings.Split(s.address, ":") host := strings.Join(parts[:len(parts)-1], ":") port, _ := strconv.Atoi(parts[len(parts)-1]) id := s.name + "-" + uuid.NewUUID().String() node := ®istry.Node{ Id: id, Address: host, Port: port, } service := ®istry.Service{ Name: s.name, Nodes: []*registry.Node{node}, } log.Infof("Registering %s", node.Id) (*cmd.DefaultOptions().Registry).Register(service) if len(s.hcUrl) > 0 { log.Info("Starting sidecar healthchecker") exitCh := make(chan bool, 1) go s.hcLoop(service, exitCh) defer func() { exitCh <- true }() } ch := make(chan os.Signal, 1) signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL) <-ch }
func Sub(types []string) (chan *event.Record, chan bool) { mtx.Lock() defer mtx.Unlock() exit := make(chan bool) bus := &sub{ id: uuid.NewUUID().String(), ch: make(chan *event.Record, bufferSize), } // global subscribe if len(types) == 0 { subs[all] = append(subs[all], bus) } // type subscribe for _, typ := range types { subs[typ] = append(subs[typ], bus) } go func() { <-exit // we've been unsubscribed mtx.Lock() // remove the global subscriber if len(types) == 0 { var subscribers []*sub for _, s := range subs[all] { if s.id == bus.id { continue } subscribers = append(subscribers, s) } subs[all] = subscribers } // remove subscribers for type for _, typ := range types { var subscribers []*sub for _, s := range subs[typ] { if s.id == bus.id { continue } subscribers = append(subscribers, s) } subs[typ] = subscribers } mtx.Unlock() }() return bus.ch, exit }
func (provisioner *quobyteVolumeProvisioner) Provision() (*api.PersistentVolume, error) { if provisioner.options.PVC.Spec.Selector != nil { return nil, fmt.Errorf("claim Selector is not supported") } provisioner.config = "BASE" provisioner.tenant = "DEFAULT" cfg, err := parseAPIConfig(provisioner.plugin, provisioner.options.Parameters) if err != nil { return nil, err } for k, v := range provisioner.options.Parameters { switch goStrings.ToLower(k) { case "registry": provisioner.registry = v case "user": provisioner.user = v case "group": provisioner.group = v case "quobytetenant": provisioner.tenant = v case "quobyteconfig": provisioner.config = v case "adminsecretname", "adminsecretnamespace", "quobyteapiserver": continue default: return nil, fmt.Errorf("invalid option %q for volume plugin %s", k, provisioner.plugin.GetPluginName()) } } if !validateRegistry(provisioner.registry) { return nil, fmt.Errorf("Quoybte registry missing or malformed: must be a host:port pair or multiple pairs separated by commas") } // create random image name provisioner.volume = fmt.Sprintf("kubernetes-dynamic-pvc-%s", uuid.NewUUID()) manager := &quobyteVolumeManager{ config: cfg, } vol, sizeGB, err := manager.createVolume(provisioner) if err != nil { return nil, err } pv := new(api.PersistentVolume) pv.Spec.PersistentVolumeSource.Quobyte = vol pv.Spec.PersistentVolumeReclaimPolicy = provisioner.options.PersistentVolumeReclaimPolicy pv.Spec.AccessModes = provisioner.options.PVC.Spec.AccessModes if len(pv.Spec.AccessModes) == 0 { pv.Spec.AccessModes = provisioner.plugin.GetAccessModes() } pv.Spec.Capacity = api.ResourceList{ api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)), } return pv, nil }
// URL: /forgot_password // 忘记密码,输入用户名和邮箱,如果匹配,发出邮件 func forgotPasswordHandler(handler *Handler) { form := wtforms.NewForm( wtforms.NewTextField("username", "用户名", "", wtforms.Required{}), wtforms.NewTextField("email", "电子邮件", "", wtforms.Email{}), ) if handler.Request.Method == "POST" { if form.Validate(handler.Request) { var user User c := handler.DB.C(USERS) err := c.Find(bson.M{"username": form.Value("username")}).One(&user) if err != nil { form.AddError("username", "没有该用户") } else if user.Email != form.Value("email") { form.AddError("username", "用户名和邮件不匹配") } else { message2 := `Hi %s,<br> 我们的系统收到一个请求,说你希望通过电子邮件重新设置你在 Golang中国 的密码。你可以点击下面的链接开始重设密码: <a href="%s/reset/%s">%s/reset/%s</a><br> 如果这个请求不是由你发起的,那没问题,你不用担心,你可以安全地忽略这封邮件。 如果你有任何疑问,可以回复<a href="mailto:[email protected]">[email protected]</a>向我提问。` code := strings.Replace(uuid.NewUUID().String(), "-", "", -1) c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"resetcode": code}}) message2 = fmt.Sprintf(message2, user.Username, Config.Host, code, Config.Host, code) if Config.SendMailPath == "" { webhelpers.SendMail( "[Golang中国]重设密码", message2, Config.FromEmail, []string{user.Email}, webhelpers.SmtpConfig{ Username: Config.SmtpUsername, Password: Config.SmtpPassword, Host: Config.SmtpHost, Addr: Config.SmtpAddr, }, true, ) } else { webhelpers.SendMailExec( "[Golang中国]重设密码", message2, Config.FromEmail, []string{user.Email}, Config.SendMailPath, true, ) } message(handler, "通过电子邮件重设密码", "一封包含了重设密码指令的邮件已经发送到你的注册邮箱,按照邮件中的提示,即可重设你的密码。", "success") return } } } handler.renderTemplate("account/forgot_password.html", BASE, map[string]interface{}{"form": form}) }
func main() { cmd.Init() database := db.NewDB( db.Database("foo"), db.Table("bar"), ) type Thing struct { Name string } record := db.NewRecord(uuid.NewUUID().String(), db.Metadata{"key": "value"}, &Thing{"dbthing"}) fmt.Printf("Creating record: id: %s metadata: %+v bytes: %+v\n", record.Id(), record.Metadata(), string(record.Bytes())) if err := database.Create(record); err != nil { fmt.Println(err) return } rec, err := database.Read(record.Id()) if err != nil { fmt.Println(err) return } thing := new(Thing) if err := rec.Scan(&thing); err != nil { fmt.Println("Error scanning read record", err) return } fmt.Printf("Read record: id: %s metadata: %+v bytes: %+v\n", rec.Id(), rec.Metadata(), thing) fmt.Println("Searching for metadata key:value") records, err := database.Search(db.Metadata{"key": "value"}, 10, 0) if err != nil { fmt.Println(err) return } for _, record := range records { thing := new(Thing) if err := record.Scan(&thing); err != nil { fmt.Println("Error scanning record", record.Id(), err) return } fmt.Printf("Record: id: %s metadata: %+v bytes: %+v\n", record.Id(), record.Metadata(), thing) } fmt.Println("Deleting", record.Id()) if err := database.Delete(record.Id()); err != nil { fmt.Println(err) return } }
func (e *etcdSync) Leader(id string, opts ...sync.LeaderOption) (sync.Leader, error) { return &etcdLeader{ path: e.opts.Namespace, id: id, node: ®istry.Node{Id: uuid.NewUUID().String()}, api: client.NewKeysAPI(e.client), }, nil }
func imageToInstanceName(imageConfig *internalGCEImage) string { if imageConfig.machine == "" { return *instanceNamePrefix + "-" + imageConfig.image } // For benchmark test, node name has the format 'machine-image-uuid' to run // different machine types with the same image in parallel return imageConfig.machine + "-" + imageConfig.image + "-" + uuid.NewUUID().String()[:8] }
func imageToInstanceName(imageConfig *internalGCEImage) string { if imageConfig.machine == "" { return *instanceNamePrefix + "-" + imageConfig.image } // For benchmark test, node name has the format 'machine-image-uuid'. // Node name is added to test data item labels and used for benchmark dashboard. return imageConfig.machine + "-" + imageConfig.image + "-" + uuid.NewUUID().String()[:8] }
func (h *httpBroker) Init() error { if len(h.id) == 0 { h.id = "broker-" + uuid.NewUUID().String() } http.Handle(DefaultSubPath, h) return nil }
func sub(be *testing.B, c int) { be.StopTimer() m := mock.NewRegistry() b := NewBroker(Registry(m)) topic := uuid.NewUUID().String() if err := b.Init(); err != nil { be.Fatalf("Unexpected init error: %v", err) } if err := b.Connect(); err != nil { be.Fatalf("Unexpected connect error: %v", err) } msg := &Message{ Header: map[string]string{ "Content-Type": "application/json", }, Body: []byte(`{"message": "Hello World"}`), } var subs []Subscriber done := make(chan bool, c) for i := 0; i < c; i++ { sub, err := b.Subscribe(topic, func(p Publication) error { done <- true m := p.Message() if string(m.Body) != string(msg.Body) { be.Fatalf("Unexpected msg %s, expected %s", string(m.Body), string(msg.Body)) } return nil }, Queue("shared")) if err != nil { be.Fatalf("Unexpected subscribe error: %v", err) } subs = append(subs, sub) } for i := 0; i < be.N; i++ { be.StartTimer() if err := b.Publish(topic, msg); err != nil { be.Fatalf("Unexpected publish error: %v", err) } <-done be.StopTimer() } for _, sub := range subs { sub.Unsubscribe() } if err := b.Disconnect(); err != nil { be.Fatalf("Unexpected disconnect error: %v", err) } }
/** * The UUID package is naive and can generate identical UUIDs if the time interval is quick enough. * Block subsequent UUIDs for 200 Nanoseconds, the UUID uses 100 ns increments, we block for 200 to be safe * Blocks in a go routine, so that the caller doesn't have to wait. * TODO: save old unused UUIDs so that no one has to block. */ func NewUUID() types.UID { uuidLock.Lock() result := uuid.NewUUID() go func() { time.Sleep(200 * time.Nanosecond) uuidLock.Unlock() }() return types.UID(result.String()) }
/** * @See: https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/ */ func milterGetNewSessionId() [16]byte { uuid := strings.Replace(uuid.NewUUID().String(), "-", "", -1) uuidSwapped := uuid[14:19] + uuid[9:14] + uuid[0:9] + uuid[19:24] + uuid[24:] uuidBytes, _ := hex.DecodeString(uuidSwapped) res := [16]byte{} copy(res[:], uuidBytes[:]) return res }
func Gen(setName string, dayVal, total int) { for i := 0; i < total; i++ { v := fmt.Sprintf("mk%v", uuid.NewUUID()) d := []byte(v) Add(setName, d, dayVal) atomic.AddInt64(&COUNT, 1) fmt.Println("success to add @key", v, " @total:", COUNT) } }
func insertBTest() { n := fmt.Sprint("figo", uuid.NewUUID().String()) s := &Student{ Id: bson.NewObjectId(), Name: n, VisitTimes: 10, } err := ds.DB(DB).C(C2).Insert(s) utee.Chk(err) }