Ejemplo n.º 1
0
        /// <summary>
        /// Check if a specific flag is set
        /// </summary>
        /// <param name="value">Flag to check</param>
        /// <returns>True if set, false if unset</returns>
        public bool IsSet(DatabaseChanges value)
        {
            // If value is None, then the enum must be zero, since no other change could have happened
            if (value == DatabaseChanges.None)
            {
                return(value == 0);
            }

            return((DatabaseChanges & value) != 0);
        }
Ejemplo n.º 2
0
        private void CreateDatabase(DatabaseChanges dbChanges)
        {
            this.AddOperation(new CreateDatabase {
                Database = dbChanges.NewDatabase.Name
            });

            foreach (var table in dbChanges.NewDatabase.Tables)
            {
                if (!dbChanges.NewDatabase.IsIgnored(table.Name))
                {
                    this.AddTable(table);
                }
            }
        }
Ejemplo n.º 3
0
        private Result AutoMigrate(DatabaseChanges changeSet, DateTime?maxTime = null)
        {
            //生成所有自动迁移操作
            var auto = new AutomationMigration()
            {
                Context = this
            };

            auto.GenerateOpertions(changeSet);
            var autoMigrations = auto.Operations;

            if (autoMigrations.Count > 0)
            {
                this.GenerateTimeId(autoMigrations, maxTime);

                return(this.MigrateUpBatch(autoMigrations));
            }

            return(true);
        }
Ejemplo n.º 4
0
        private void DropDatabase(DatabaseChanges dbChanges)
        {
            //反向按表间的引用关系删除表。
            var tables = dbChanges.OldDatabase.Tables;

            for (int i = tables.Count - 1; i >= 0; i--)
            {
                if (!dbChanges.NewDatabase.IsIgnored(tables[i].Name))
                {
                    this.RemoveTable(tables[i]);
                }
            }

            //当版本号嵌入到当前数据库中时,也不支持自动 DropDatabase。
            if (!Context.DbVersionProvider.IsEmbaded())
            {
                this.AddOperation(new DropDatabase {
                    Database = dbChanges.OldDatabase.Name
                });
            }
        }
Ejemplo n.º 5
0
        public void GenerateOpertions(DatabaseChanges dbChanges)
        {
            this._operations.Clear();

            switch (dbChanges.ChangeType)
            {
            case ChangeType.Added:
                this.CreateDatabase(dbChanges);
                break;

            case ChangeType.Removed:
                this.DropDatabase(dbChanges);
                break;

            case ChangeType.Modified:
                //为了保证外键的变化与表的变化不冲突,按照以下顺序生成操作:添加的表、修改的表(外键)、删除的表。
                foreach (var item in dbChanges.TablesChanged.Where(t => t.ChangeType == ChangeType.Added))
                {
                    this.GenerateOpertions(item);
                }
                foreach (var item in dbChanges.TablesChanged.Where(t => t.ChangeType == ChangeType.Modified))
                {
                    this.GenerateOpertions(item);
                }
                foreach (var item in dbChanges.TablesChanged.Where(t => t.ChangeType == ChangeType.Removed))
                {
                    this.GenerateOpertions(item);
                }
                break;

            default:
                break;
            }

            foreach (var action in this._relationActions)
            {
                action();
            }
            this._relationActions.Clear();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Connects to raven traffic event source and registers all the requests to the file defined in the config
        /// </summary>
        /// <param name="config">configuration containing the connection, the file to write to, etc.</param>
        /// <param name="store">the store to work with</param>
        private async Task RecordRequests(TrafficToolConfiguration config, IDocumentStore store)
        {
            var id = Guid.NewGuid().ToString();

            using (var client = DatabaseChanges.CreateClientWebSocket(store.GetRequestExecutor()))
            {
                var url = store.Urls.First() + "/admin/traffic-watch";
                var uri = new Uri(url.ToWebSocketPath());

                await client.ConnectAsync(uri, CancellationToken.None)
                .ConfigureAwait(false);


                // record traffic no more then 7 days
                var day     = 24 * 60 * 60;
                var timeout = (int)config.Timeout.TotalMilliseconds / 1000;
                timeout = Math.Min(timeout, 7 * day);
                if (timeout <= 0)
                {
                    timeout = 7 * day;
                }

                try
                {
                    string resourceName   = config.ResourceName ?? "N/A";
                    var    connectMessage = new DynamicJsonValue
                    {
                        ["Id"]           = id,
                        ["DatabaseName"] = resourceName,
                        ["Timeout"]      = timeout
                    };

                    var stream = new MemoryStream();

                    JsonOperationContext context;
                    using (_jsonContextPool.AllocateOperationContext(out context))
                        using (var writer = new BlittableJsonTextWriter(context, stream))
                        {
                            context.Write(writer, connectMessage);
                            writer.Flush();

                            ArraySegment <byte> bytes;
                            stream.TryGetBuffer(out bytes);
                            await client.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None)
                            .ConfigureAwait(false);
                        }

                    var requestsCounter = 0;
                    using (var fileStream = File.Create(config.RecordFilePath))
                    {
                        Stream finalStream = fileStream;
                        if (config.IsCompressed)
                        {
                            finalStream = new GZipStream(fileStream, CompressionMode.Compress, leaveOpen: true);
                        }

                        using (var streamWriter = new StreamWriter(finalStream))
                        {
                            var jsonWriter = new JsonTextWriter(streamWriter)
                            {
                                Formatting = Formatting.Indented
                            };
                            jsonWriter.WriteStartArray();
                            var sp = Stopwatch.StartNew();

                            while (true)
                            {
                                using (var reader = await Receive(client, context))
                                {
                                    if (reader == null)
                                    {
                                        // server asked to close connection
                                        break;
                                    }

                                    string type;
                                    if (reader.TryGet("Type", out type))
                                    {
                                        if (type.Equals("Heartbeat"))
                                        {
                                            continue;
                                        }
                                    }

                                    string error;
                                    if (reader.TryGet("Error", out error))
                                    {
                                        throw new InvalidOperationException("Server returned error: " + error);
                                    }

                                    var notification = new TrafficWatchChange();
                                    notification.TimeStamp           = GetDateTimeFromJson(reader, "TimeStamp");
                                    notification.RequestId           = GetIntFromJson(reader, "RequestId");
                                    notification.HttpMethod          = GetStringFromJson(reader, "HttpMethod");
                                    notification.ElapsedMilliseconds = GetIntFromJson(reader, "ElapsedMilliseconds");
                                    notification.ResponseStatusCode  = GetIntFromJson(reader, "ResponseStatusCode");
                                    notification.DatabaseName        = GetStringFromJson(reader, "DatabaseName");
                                    notification.CustomInfo          = GetStringFromJson(reader, "CustomInfo");
                                    notification.InnerRequestsCount  = GetIntFromJson(reader, "InnerRequestsCount");
                                    // notification.QueryTimings = GetRavenJObjectFromJson(reader, "QueryTimings"); // TODO (TrafficWatch) : Handle this both server and client sides

                                    if (config.PrintOutput)
                                    {
                                        Console.Write("\rRequest #{0} Stored...\t\t ", ++requestsCounter);
                                    }

                                    var jobj = JObject.FromObject(notification);
                                    jobj.WriteTo(jsonWriter);

                                    if (sp.ElapsedMilliseconds > 5000)
                                    {
                                        streamWriter.Flush();
                                        sp.Restart();
                                    }
                                }
                            }
                            jsonWriter.WriteEndArray();
                            streamWriter.Flush();
                            if (config.IsCompressed)
                            {
                                finalStream.Dispose();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\r\n\nError while reading messages from server : " + ex);
                }
                finally
                {
                    Console.WriteLine("\r\n\nClosing connection to server...`");
                    try
                    {
                        await
                        client.CloseAsync(WebSocketCloseStatus.NormalClosure, "CLOSE_NORMAL", CancellationToken.None)
                        .ConfigureAwait(false);
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Unset value flag in enum
 /// </summary>
 /// <param name="value">Flag to unset</param>
 public void Unset(DatabaseChanges value)
 {
     DatabaseChanges &= ~value;
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Set value flag in enum
 /// </summary>
 /// <param name="value">Flag to set</param>
 public void Set(DatabaseChanges value)
 {
     DatabaseChanges |= value;
 }