Esempio n. 1
0
func (self *ShardData) Query(querySpec *parser.QuerySpec, response chan *protocol.Response) error {
	// This is only for queries that are deletes or drops. They need to be sent everywhere as opposed to just the local or one of the remote shards.
	// But this boolean should only be set to true on the server that receives the initial query.
	if querySpec.RunAgainstAllServersInShard {
		if querySpec.IsDeleteFromSeriesQuery() {
			return self.logAndHandleDeleteQuery(querySpec, response)
		} else if querySpec.IsDropSeriesQuery() {
			return self.logAndHandleDropSeriesQuery(querySpec, response)
		}
	}

	if self.localShard != nil {
		var processor QueryProcessor
		if querySpec.IsListSeriesQuery() {
			processor = engine.NewListSeriesEngine(response)
		} else if querySpec.IsDeleteFromSeriesQuery() || querySpec.IsDropSeriesQuery() || querySpec.IsSinglePointQuery() {
			maxDeleteResults := 10000
			processor = engine.NewPassthroughEngine(response, maxDeleteResults)
		} else {
			if self.ShouldAggregateLocally(querySpec) {
				processor = engine.NewQueryEngine(querySpec.SelectQuery(), response)
			} else {
				maxPointsToBufferBeforeSending := 1000
				processor = engine.NewPassthroughEngine(response, maxPointsToBufferBeforeSending)
			}
		}
		err := self.localShard.Query(querySpec, processor)
		processor.Close()
		return err
	}

	healthyServers := make([]*ClusterServer, 0, len(self.clusterServers))
	for _, s := range self.clusterServers {
		if !s.IsUp() {
			continue
		}
		healthyServers = append(healthyServers, s)
	}
	healthyCount := len(healthyServers)
	if healthyCount == 0 {
		message := fmt.Sprintf("No servers up to query shard %d", self.id)
		response <- &protocol.Response{Type: &endStreamResponse, ErrorMessage: &message}
		return errors.New(message)
	}
	randServerIndex := int(time.Now().UnixNano() % int64(healthyCount))
	server := healthyServers[randServerIndex]
	request := self.createRequest(querySpec)

	return server.MakeRequest(request, response)
}
Esempio n. 2
0
func (self *ShardData) LogAndHandleDestructiveQuery(querySpec *parser.QuerySpec, request *protocol.Request, response chan *protocol.Response, runLocalOnly bool) error {
	requestNumber, err := self.wal.AssignSequenceNumbersAndLog(request, self)
	if err != nil {
		return err
	}
	var localResponses chan *protocol.Response
	if self.localShard != nil {
		localResponses = make(chan *protocol.Response, 1)

		// this doesn't really apply at this point since destructive queries don't output anything, but it may later
		maxPointsFromDestructiveQuery := 1000
		processor := engine.NewPassthroughEngine(localResponses, maxPointsFromDestructiveQuery)
		err := self.localShard.Query(querySpec, processor)
		processor.Close()
		if err != nil {
			return err
		}
	}
	if !runLocalOnly {
		responses := make([]chan *protocol.Response, len(self.clusterServers), len(self.clusterServers))
		for i, server := range self.clusterServers {
			responseChan := make(chan *protocol.Response, 1)
			responses[i] = responseChan
			// do this so that a new id will get assigned
			request.Id = nil
			server.MakeRequest(request, responseChan)
		}
		for i, responseChan := range responses {
			for {
				res := <-responseChan
				if *res.Type == endStreamResponse {
					self.wal.Commit(requestNumber, self.clusterServers[i].Id)
					break
				}
				response <- res
			}
		}
	}

	if localResponses != nil {
		for {
			res := <-localResponses
			if *res.Type == endStreamResponse {
				self.wal.Commit(requestNumber, self.localServerId)
				break
			}
			response <- res
		}
	}

	response <- &protocol.Response{Type: &endStreamResponse}
	return nil
}
Esempio n. 3
0
func (self *CoordinatorImpl) getShardsAndProcessor(querySpec *parser.QuerySpec, writer SeriesWriter) ([]*cluster.ShardData, cluster.QueryProcessor, chan bool, error) {
	shards := self.clusterConfiguration.GetShards(querySpec)
	shouldAggregateLocally := self.shouldAggregateLocally(shards, querySpec)

	var err error
	var processor cluster.QueryProcessor

	responseChan := make(chan *protocol.Response)
	seriesClosed := make(chan bool)

	selectQuery := querySpec.SelectQuery()
	if selectQuery != nil {
		if !shouldAggregateLocally {
			// if we should aggregate in the coordinator (i.e. aggregation
			// isn't happening locally at the shard level), create an engine
			processor, err = engine.NewQueryEngine(querySpec.SelectQuery(), responseChan)
		} else {
			// if we have a query with limit, then create an engine, or we can
			// make the passthrough limit aware
			processor = engine.NewPassthroughEngineWithLimit(responseChan, 100, selectQuery.Limit)
		}
	} else if !shouldAggregateLocally {
		processor = engine.NewPassthroughEngine(responseChan, 100)
	}

	if err != nil {
		return nil, nil, nil, err
	}

	if processor == nil {
		return shards, nil, nil, nil
	}

	go func() {
		for {
			response := <-responseChan

			if *response.Type == endStreamResponse || *response.Type == accessDeniedResponse {
				writer.Close()
				seriesClosed <- true
				return
			}
			if !(*response.Type == queryResponse && querySpec.IsExplainQuery()) {
				if response.Series != nil && len(response.Series.Points) > 0 {
					writer.Write(response.Series)
				}
			}
		}
	}()

	return shards, processor, seriesClosed, nil
}
Esempio n. 4
0
func (self *ShardData) deleteDataLocally(querySpec *parser.QuerySpec) (<-chan *p.Response, error) {
	localResponses := make(chan *p.Response, 1)

	// this doesn't really apply at this point since destructive queries don't output anything, but it may later
	maxPointsFromDestructiveQuery := 1000
	processor := engine.NewPassthroughEngine(localResponses, maxPointsFromDestructiveQuery)
	shard, err := self.store.GetOrCreateShard(self.id)
	if err != nil {
		return nil, err
	}
	defer self.store.ReturnShard(self.id)
	err = shard.Query(querySpec, processor)
	processor.Close()
	return localResponses, err
}
Esempio n. 5
0
func (self *ShardData) Query(querySpec *parser.QuerySpec, response chan *p.Response) {
	log.Debug("QUERY: shard %d, query '%s'", self.Id(), querySpec.GetQueryString())
	defer common.RecoverFunc(querySpec.Database(), querySpec.GetQueryString(), func(err interface{}) {
		response <- &p.Response{Type: &endStreamResponse, ErrorMessage: p.String(fmt.Sprintf("%s", err))}
	})

	// This is only for queries that are deletes or drops. They need to be sent everywhere as opposed to just the local or one of the remote shards.
	// But this boolean should only be set to true on the server that receives the initial query.
	if querySpec.RunAgainstAllServersInShard {
		if querySpec.IsDeleteFromSeriesQuery() {
			self.logAndHandleDeleteQuery(querySpec, response)
		} else if querySpec.IsDropSeriesQuery() {
			self.logAndHandleDropSeriesQuery(querySpec, response)
		}
	}

	if self.IsLocal {
		var processor QueryProcessor
		var err error

		if querySpec.IsListSeriesQuery() {
			processor = engine.NewListSeriesEngine(response)
		} else if querySpec.IsDeleteFromSeriesQuery() || querySpec.IsDropSeriesQuery() || querySpec.IsSinglePointQuery() {
			maxDeleteResults := 10000
			processor = engine.NewPassthroughEngine(response, maxDeleteResults)
		} else {
			query := querySpec.SelectQuery()
			if self.ShouldAggregateLocally(querySpec) {
				log.Debug("creating a query engine")
				processor, err = engine.NewQueryEngine(query, response)
				if err != nil {
					response <- &p.Response{Type: &endStreamResponse, ErrorMessage: p.String(err.Error())}
					log.Error("Error while creating engine: %s", err)
					return
				}
				processor.SetShardInfo(int(self.Id()), self.IsLocal)
			} else if query.HasAggregates() {
				maxPointsToBufferBeforeSending := 1000
				log.Debug("creating a passthrough engine")
				processor = engine.NewPassthroughEngine(response, maxPointsToBufferBeforeSending)
			} else {
				maxPointsToBufferBeforeSending := 1000
				log.Debug("creating a passthrough engine with limit")
				processor = engine.NewPassthroughEngineWithLimit(response, maxPointsToBufferBeforeSending, query.Limit)
			}

			if query.GetFromClause().Type != parser.FromClauseInnerJoin {
				// Joins do their own filtering since we need to get all
				// points before filtering. This is due to the fact that some
				// where expressions will be difficult to compute before the
				// points are joined together, think where clause with
				// left.column = 'something' or right.column =
				// 'something_else'. We can't filter the individual series
				// separately. The filtering happens in merge.go:55

				processor = engine.NewFilteringEngine(query, processor)
			}
		}
		shard, err := self.store.GetOrCreateShard(self.id)
		if err != nil {
			response <- &p.Response{Type: &endStreamResponse, ErrorMessage: p.String(err.Error())}
			log.Error("Error while getting shards: %s", err)
			return
		}
		defer self.store.ReturnShard(self.id)
		err = shard.Query(querySpec, processor)
		// if we call Close() in case of an error it will mask the error
		if err != nil {
			response <- &p.Response{Type: &endStreamResponse, ErrorMessage: p.String(err.Error())}
			return
		}
		processor.Close()
		response <- &p.Response{Type: &endStreamResponse}
		return
	}

	if server := self.randomHealthyServer(); server != nil {
		log.Debug("Querying server %d for shard %d", server.GetId(), self.Id())
		request := self.createRequest(querySpec)
		server.MakeRequest(request, response)
		return
	}

	message := fmt.Sprintf("No servers up to query shard %d", self.id)
	response <- &p.Response{Type: &endStreamResponse, ErrorMessage: &message}
	log.Error(message)
}
Esempio n. 6
0
func (self *ShardData) Query(querySpec *parser.QuerySpec, response chan *p.Response) {
	// This is only for queries that are deletes or drops. They need to be sent everywhere as opposed to just the local or one of the remote shards.
	// But this boolean should only be set to true on the server that receives the initial query.
	if querySpec.RunAgainstAllServersInShard {
		if querySpec.IsDeleteFromSeriesQuery() {
			self.logAndHandleDeleteQuery(querySpec, response)
		} else if querySpec.IsDropSeriesQuery() {
			self.logAndHandleDropSeriesQuery(querySpec, response)
		}
	}

	if self.IsLocal {
		var processor QueryProcessor
		var err error

		if querySpec.IsListSeriesQuery() {
			processor = engine.NewListSeriesEngine(response)
		} else if querySpec.IsDeleteFromSeriesQuery() || querySpec.IsDropSeriesQuery() || querySpec.IsSinglePointQuery() {
			maxDeleteResults := 10000
			processor = engine.NewPassthroughEngine(response, maxDeleteResults)
		} else {
			query := querySpec.SelectQuery()
			if self.ShouldAggregateLocally(querySpec) {
				log.Debug("creating a query engine\n")
				processor, err = engine.NewQueryEngine(query, response)
				if err != nil {
					response <- &p.Response{Type: &endStreamResponse, ErrorMessage: p.String(err.Error())}
					log.Error("Error while creating engine: %s", err)
					return
				}
				processor.SetShardInfo(int(self.Id()), self.IsLocal)
			} else if query.HasAggregates() {
				maxPointsToBufferBeforeSending := 1000
				log.Debug("creating a passthrough engine\n")
				processor = engine.NewPassthroughEngine(response, maxPointsToBufferBeforeSending)
			} else {
				maxPointsToBufferBeforeSending := 1000
				log.Debug("creating a passthrough engine with limit\n")
				processor = engine.NewPassthroughEngineWithLimit(response, maxPointsToBufferBeforeSending, query.Limit)
			}
			processor = engine.NewFilteringEngine(query, processor)
		}
		shard, err := self.store.GetOrCreateShard(self.id)
		if err != nil {
			response <- &p.Response{Type: &endStreamResponse, ErrorMessage: p.String(err.Error())}
			log.Error("Error while getting shards: %s", err)
			return
		}
		defer self.store.ReturnShard(self.id)
		err = shard.Query(querySpec, processor)
		processor.Close()
		if err != nil {
			response <- &p.Response{Type: &endStreamResponse, ErrorMessage: p.String(err.Error())}
		}
		response <- &p.Response{Type: &endStreamResponse}
		return
	}

	healthyServers := make([]*ClusterServer, 0, len(self.clusterServers))
	for _, s := range self.clusterServers {
		if !s.IsUp() {
			continue
		}
		healthyServers = append(healthyServers, s)
	}
	healthyCount := len(healthyServers)
	if healthyCount == 0 {
		message := fmt.Sprintf("No servers up to query shard %d", self.id)
		response <- &p.Response{Type: &endStreamResponse, ErrorMessage: &message}
		log.Error(message)
		return
	}
	randServerIndex := int(time.Now().UnixNano() % int64(healthyCount))
	server := healthyServers[randServerIndex]
	request := self.createRequest(querySpec)

	server.MakeRequest(request, response)
}
Esempio n. 7
0
func (self *CoordinatorImpl) runQuerySpec(querySpec *parser.QuerySpec, seriesWriter SeriesWriter) error {
	shards := self.clusterConfiguration.GetShards(querySpec)

	shouldAggregateLocally := true
	var processor cluster.QueryProcessor
	var responseChan chan *protocol.Response
	var seriesClosed chan bool
	for _, s := range shards {
		// If the aggregation is done at the shard level, we don't need to
		// do it here at the coordinator level.
		if !s.ShouldAggregateLocally(querySpec) {
			seriesClosed = make(chan bool)
			shouldAggregateLocally = false
			responseChan = make(chan *protocol.Response)

			if querySpec.SelectQuery() != nil {
				processor = engine.NewQueryEngine(querySpec.SelectQuery(), responseChan)
			} else {
				bufferSize := 100
				processor = engine.NewPassthroughEngine(responseChan, bufferSize)
			}
			go func() {
				for {
					res := <-responseChan
					if *res.Type == endStreamResponse || *res.Type == accessDeniedResponse {
						seriesWriter.Close()
						seriesClosed <- true
						return
					}
					if res.Series != nil && len(res.Series.Points) > 0 {
						seriesWriter.Write(res.Series)
					}
				}
			}()
			break
		}
	}

	responses := make([]chan *protocol.Response, 0)
	for _, shard := range shards {
		responseChan := make(chan *protocol.Response, self.config.QueryShardBufferSize)
		go shard.Query(querySpec, responseChan)
		responses = append(responses, responseChan)
	}

	for i, responseChan := range responses {
		log.Debug("READING: shard: ", shards[i].String())
		for {
			response := <-responseChan
			log.Debug("GOT RESPONSE: ", response.Type, response.Series)
			if *response.Type == endStreamResponse || *response.Type == accessDeniedResponse {
				break
			}
			if shouldAggregateLocally {
				log.Debug("WRITING: ", len(response.Series.Points))
				seriesWriter.Write(response.Series)
				log.Debug("WRITING (done)")
				continue
			}

			// if the data wasn't aggregated at the shard level, aggregate
			// the data here
			log.Debug("YIELDING: ", len(response.Series.Points))
			if response.Series != nil {
				for _, p := range response.Series.Points {
					processor.YieldPoint(response.Series.Name, response.Series.Fields, p)
				}
			}
		}
		log.Debug("DONE: shard: ", shards[i].String())
	}
	if !shouldAggregateLocally {
		processor.Close()
		<-seriesClosed
		return nil
	}
	seriesWriter.Close()
	return nil
}